Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if any key is pressed

Tags:

c#

wpf

c#-4.0

How can I detect if any keyboard key is currently being pressed? I'm not interested in what the key is, I just want to know if any key is still pressed down.

if (Keyboard.IsKeyDown(Key.ANYKEY??)
{

}
like image 458
RobHurd Avatar asked Aug 22 '12 15:08

RobHurd


People also ask

How do you check if any key is pressed in Python?

To detect keypress, we will use the is_pressed() function defined in the keyboard module. The is_pressed() takes a character as input and returns True if the key with the same character is pressed on the keyboard.

How do I show keystrokes on Windows 10?

Go to Start , then select Settings > Accessibility > Keyboard, and turn on the On-Screen Keyboard toggle. A keyboard that can be used to move around the screen and enter text will appear on the screen. The keyboard will remain on the screen until you close it.

How do you check if a specific key is pressed in JavaScript?

Using JavaScript In plain JavaScript, you can use the EventTarget. addEventListener() method to listen for keyup event. When it occurs, check the keyCode 's value to see if an Enter key is pressed.


2 Answers

public static IEnumerable<Key> KeysDown()
{
    foreach (Key key in Enum.GetValues(typeof(Key)))
    {
        if (Keyboard.IsKeyDown(key))
            yield return key;
    }
}

you could then do:

if(KeysDown().Any()) //...
like image 97
Servy Avatar answered Oct 20 '22 00:10

Servy


If you want to detect key pressed only in our application (when your WPF window is activated) add KeyDown like below:

public MainWindow()
{
    InitializeComponent();
    this.KeyDown += new KeyEventHandler(MainWindow_KeyDown);
}

void MainWindow_KeyDown(object sender, KeyEventArgs e)
{
    MessageBox.Show("You pressed a keyboard key.");
}

If you want to detect when a key is pressed even your WPF window is not active is a little harder but posibile. I recomend RegisterHotKey (Defines a system-wide hot key) and UnregisterHotKey from Windows API. Try using these in C# from pinvoke.net or these tutorials:

  • Global Hotkeys: Register a hotkey that is triggered even when form isn't focused.
  • Simple steps to enable Hotkey and ShortcutInput user control

Thse is a sample in Microsoft Forums.

You will use Virtual-Key Codes. I Hope that I was clear and you will understand my answer.

like image 44
Ionică Bizău Avatar answered Oct 19 '22 23:10

Ionică Bizău