Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global Windows Key Press

I have a simple WPF application and I need to capture F1 key pressed in Windows (Operation System), even if my WPF window is minimized, or it isn't activated.

I have problems with detecting this. I searched on Internet and I found many results, but they didn't helped me.

For detecting a key pressed inside of application I used this simple code:

AddHandler(Keyboard.KeyDownEvent, (KeyEventHandler)KeyPressed);
private void KeyPressed(object sender, KeyEventArgs e)
{
      if (e.Key == Key.F1)
      {
           //my code went here
      }
}

But this doesn't work when my window isn't activated.

So, my question is: how to detect global key press?

I repeat: It is a WPF application.

like image 950
Ionică Bizău Avatar asked Aug 01 '12 03:08

Ionică Bizău


People also ask

Are Windows keys global?

Yes, the keys are global.

When KeyPress event occur?

The KeyPress event is used in the Windows Form when a user presses a character, space, or backspace key during the focus on the control, the KeyPress event occurs. Furthermore, the keypress event is raised only when printable keys or numbers such as alphabets (a, b, c) are processed with Windows Form.

How do you press a key in C++?

ki. wVk = 0x41; // virtual-key code for the "a" key ip. ki. dwFlags = 0; // 0 for key press SendInput(1, &ip, sizeof(INPUT)); // ...


1 Answers

No need to Keyboard Hooking. Just use 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

There is a sample in Microsoft Forums.

You can use these modifiers and Virtual-Key Codes:

MOD_ALT      (0x0001)
MOD_CONTROL  (0x0002)
MOD_NOREPEAT (0x4000)
MOD_SHIFT    (0x0004)
MOD_WIN      (0x0008)

for example F1 key is VK_F1 (0x70).

like image 180
Ria Avatar answered Oct 28 '22 09:10

Ria