Capture a keyboard keypress in the background

In case you have problem running Otiel's solution:

  1. You need to include:

     using System.Runtime.InteropServices; //required for dll import
    
  2. Another doubt for newbies like me: "top of the class" really means top of your class like this (not namespace or constructor):

    public partial class Form1 : Form
    {
        [DllImport("user32.dll")]
        public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifers, int vlc);
    
        [DllImport("user32.dll")]
        public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
    }
    
  3. You don't need to add user32.dll as reference to the project. WinForms always load this dll automatically.


What you want is a global hotkey.

  1. Import needed libraries at the top of your class:

    // DLL libraries used to manage hotkeys
    [DllImport("user32.dll")] 
    public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);
    [DllImport("user32.dll")]
    public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
    
  2. Add a field in your class that will be a reference for the hotkey in your code:

    const int MYACTION_HOTKEY_ID = 1;
    
  3. Register the hotkey (in the constructor of your Windows Form for instance):

    // Modifier keys codes: Alt = 1, Ctrl = 2, Shift = 4, Win = 8
    // Compute the addition of each combination of the keys you want to be pressed
    // ALT+CTRL = 1 + 2 = 3 , CTRL+SHIFT = 2 + 4 = 6...
    RegisterHotKey(this.Handle, MYACTION_HOTKEY_ID, 6, (int) Keys.F12);
    
  4. Handle the typed keys by adding the following method in your class:

    protected override void WndProc(ref Message m) {
        if (m.Msg == 0x0312 && m.WParam.ToInt32() == MYACTION_HOTKEY_ID) {
            // My hotkey has been typed
    
            // Do what you want here
            // ...
        }
        base.WndProc(ref m);
    }