Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyDown and KeyUp Multiple

Tags:

c#

keydown

I am creating a piano in C Sharp and currently I have keyboard keys to play sounds. For example key A plays Note C. problem I am having is there I want to be pressing multiple keys at the same time and have the sound out. obviously I don't want to have to put all combinations in the keyDown class as I will have to make thousands of if statements. Is there anyway around this?

like image 877
frz Avatar asked Nov 03 '22 02:11

frz


1 Answers

Windows works with an only one message queue, so in each time only a key down message will be handled at a time unit. What you can do is to get all key down events in a short time interval (0.5 seconds for instace), save all key pressed in a list or a queue, then play all sounds according to the keys asynchronically (using threads). I have never have done this before, but I think should works. Hope helps...

EDIT


Ok, let see: first the list where to save the keys

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

Then start a timer for checking the keys pressed in a time interval:

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

Then the t_Elapsed method (Note that if you are in WPF an DispatcherTimer should be used, this timer is 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();
        }
    }

And then the on key down method:

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

You may try this, hope be helpful.

like image 177
Raúl Otaño Avatar answered Nov 15 '22 06:11

Raúl Otaño