How do I detect keyPress while not focused?

Well, if you had problems with System hooks, here is ready-made solution (based on http://www.dreamincode.net/forums/topic/180436-global-hotkeys/):

Define static class in your project:

public static class Constants
{
    //windows message id for hotkey
    public const int WM_HOTKEY_MSG_ID = 0x0312;
}

Define class in your project:

public class KeyHandler
{
    [DllImport("user32.dll")]
    private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);

    [DllImport("user32.dll")]
    private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

    private int key;
    private IntPtr hWnd;
    private int id;

    public KeyHandler(Keys key, Form form)
    {
        this.key = (int)key;
        this.hWnd = form.Handle;
        id = this.GetHashCode();
    }

    public override int GetHashCode()
    {
        return key ^ hWnd.ToInt32();
    }

    public bool Register()
    {
        return RegisterHotKey(hWnd, id, 0, key);
    }

    public bool Unregiser()
    {
        return UnregisterHotKey(hWnd, id);
    }
}

add usings:

using System.Windows.Forms;
using System.Runtime.InteropServices;

now, in your Form, add field:

private KeyHandler ghk;

and in Form constructor:

ghk = new KeyHandler(Keys.PrintScreen, this);
ghk.Register();

Add those 2 methods to your form:

private void HandleHotkey()
{
        // Do stuff...
}

protected override void WndProc(ref Message m)
{
    if (m.Msg == Constants.WM_HOTKEY_MSG_ID)
        HandleHotkey();
    base.WndProc(ref m);
}

HandleHotkey is your button press handler. You can change the button by passing different parameter here: ghk = new KeyHandler(Keys.PrintScreen, this);

Now your program reacts for buton input even if not focused.

Leave a Comment