5

我正在用 C Sharp 创建一架钢琴,目前我有键盘键来播放声音。例如键 A 播放音符 C。我遇到的问题是我想同时按下多个键并发出声音。显然我不想将所有组合都放在 keyDown 类中,因为我将不得不做出数千个 if 语句。有没有办法解决?

4

1 回答 1

2

Windows 仅使用一个消息队列,因此每次在一个时间单位内只处理一个按键消息。您可以做的是在很短的时间间隔内获取所有按键事件(实例为 0.5 秒),将所有按下的按键保存在列表或队列中,然后根据按键异步播放所有声音(使用线程)。我以前从未这样做过,但我认为应该可行。希望有帮助...

编辑


好的,让我们看看:首先是保存密钥的列表

List<Key> _keys = new List<Key>();

然后启动一个计时器来检查在一个时间间隔内按下的键:

        var t = new System.Timers.Timer(500);    //you may try using an smaller value
        t.Elapsed += t_Elapsed;
        t.Start();

然后t_Elapsed方法(请注意,如果您在 WPF 中DispatcherTimer应该使用 an ,此计时器是 on System.Timers

    void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        if (_keys.Count > 0)
        {
             //Here get all keys and play the sound using threads
             _keys.Clear();
        }
    }

然后是 on key down 方法:

void OnKeyDownMethod(object sender, KeyPressedEventArgs e)  //not sure this is the name of the EventArgs class
 {
    _keys.Add(e.Key);    //need to check
 }

你可以试试这个,希望对你有帮助。

于 2013-03-15T16:55:26.553 回答