Have an unfocused C# program activate on keypress (eg. F1 sets a label to "Hello World")

c#, key, listener

Solution

You can use WIN API RegisterHotKey function.

[DllImport("user32")]
public static extern int RegisterHotKey(IntPtr hwnd, int id, int fsModifiers, int vk);

Register hotkey on Form_Load event:

private void Form_Load(object sender, EventArgs e)
{
    RegisterHotKey(Handle, 42, 0, (int)Keys.F1);
}

Keep in mind that if you want to hook some keys combination, instead of zero you should pass one of following values (for Alt, Ctrl, Shift or Windows keys):

private const int MOD_ALT = 0x1;
private const int MOD_CONTROL = 0x2;
private const int MOD_SHIFT = 0x4;
private const int MOD_WIN = 0x8;

At this point when you press somewhere F1 key, system will send to your window WM_HOTKEY message. Process it inside WndProc:

private const int WM_HOTKEY = 0x312;

protected override void WndProc(ref Message m)
{
    base.WndProc(ref m);

    if (m.Msg == WM_HOTKEY)
    {
        if (!Visible)
            Visible = true;
        Activate();
        Keys vk = (Keys)(((int)m.LParam >> 16) & 0xFFFF);
        int fsModifiers = ((int)m.LParam & 0xFFFF);

        if (vk == Keys.F1 && sModifiers == 0)
            label.Text = "Hello World";
    }
}

BTW don't forget to unregister hotkey when closing form.

Problem

I am trying to make my program activate its task if a key is pressed anywhere, even if it is not in focus. (lets just use F1 for this example, and have the task being set a text on a label to "Hello World"). I looked at key listeners, hooks etc and is getting a headache trying to understand what is going on. Is there any easy way to make this work.

Original source