简体   繁体   中英

C# UI multiple KeyDown Events ?? windows form application

I am working on an mp3 player with minimal UI, in C# using windowsForm app.

currently I have methods for open play and pause a song.

As I want the UI minimal, I only display the fileName of the playing song.

Now the problem is when I am trying to assign a KeyDown Event for each method.

As all in my form I can select and map a KeyPress Event to is the Empty form, but it can only hold 1 KeyDown event, which now means I can only get 1 method to run..

How can I solve this ?

I assume I could use KeyPress and KeyUp events for my other 2 methods to run, but I suppose theres a more clever solution ?

part of my code: in this example, OpenFile works... but Play doesnt work at the same time, because I havent assigned any EventHandler for it, I guess. But as I dont want any button in the UI.,, What can I then do ??

I dont want a traditional shortcut command either. like ctrl + key.

private void o(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.O)
            {
                openFileDialog1.ShowDialog();
            }
        }

        private void p(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.P)
            {
                player.Play();
            }
        }

Simply

private void o(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.O)
        {
            openFileDialog1.ShowDialog();
        }

        else if (e.KeyCode == Keys.P)
        {
            player.Play();
        }
    }

you may want to define only one event-handler, but you can check for several keys pressed.

I'd personally put it into a case statement and into a single method/function. This way you can expand without a web of if/thens.

private void o(object sender, KeyEventArgs e) {
switch (e.KeyCode) {
    case Keys.O: 
        openFileDialog1.ShowDialog();
        break;
    case Keys.P:
        player.Play();
        break;
    default: 
        break;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM