Home > Net >  How to detect keyboard inputs?
How to detect keyboard inputs?

Time:05-25

I want to detect when a key on the keyboard is pressed to execute a command. So that when I press the F key it does an action. How I can do it?

CodePudding user response:

You need to process the keyboard events like KeyDown. These provide you with events on every key press or release.

Inside the Event handler you need to filter which key was pressed and execute whatever action needs to be done:

public void MyKeyDownEventHandler(object sender, KeyRoutedEventArgs e)
{
    if (e.Key == 70)
        {
            MessageBox.Show("'F' key pressed");
        }
}

Since the KeyDown event is bound to a control and will only be fired when the control has focus you need to think about from which control you want the event to be fired from. In order to get the event fired from everywhere in your app, this blog post provides a neat solution:

By registering the KeyDown event to all controls during startup of your app, it will always fire as long as your app is in focus since there is always one control in focus. To achieve this, add this to the OnStartup() method of your app (inside the app.xaml.cs):

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        EventManager.RegisterClassHandler(typeof(Control),
            Control.KeyDownEvent,
            new KeyEventHandler(MyKeyDownEventHandler));

        base.OnStartup(e);
    }
}
  • Related