Global Windows Key Press

19,834

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:

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).

Share:
19,834

Related videos on Youtube

Ionică Bizău
Author by

Ionică Bizău

💻 Programmer ⚡️ Geek 🎹 Pianist & Organist 🚀 Learner 💡 Mentor 💫 Dreamer 🍏 Vegetarian 🙏 Jesus follower Website | GitHub | Twitter | PayPal Donations

Updated on July 11, 2022

Comments

  • Ionică Bizău
    Ionică Bizău almost 2 years

    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.

  • CodesInChaos
    CodesInChaos almost 12 years
    What a pleasant surprise. For once I come to a global hotkey thread and the top answer is RegisterHotKey and not SetWindowsHookEx.
  • HgCoder
    HgCoder almost 6 years
    I had errors on Windows 10 using the MOD_WIN modifier key. Windows may no longer allow you to hook with that modifier.