Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect keyPress while not focused?

Tags:

c#

forms

keypress

I am trying to detect the Print Screen button press while the form is not the current active application.

How to do that, if possible?

like image 685
James Holland Avatar asked Aug 17 '13 17:08

James Holland


1 Answers

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.

like image 106
Przemysław Kalita Avatar answered Oct 21 '22 01:10

Przemysław Kalita