How to make the keydown function work with the program in the background?

Asked

Viewed 342 times

3

Code:

    if (e.KeyCode == Keys.F7)
    {
        A1 = !A1;
    }

How to make this code work without the program being in the foreground?

1 answer

2


You have register a global key in Windows. I have picked a response in the OS with what you must do:

Import the Win32 functions:

// 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);

Determine the ID of the key you want to handle:

const int MYACTION_HOTKEY_ID = 1;

Register the key already in the constructor of the main form:

// 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);

Create the method that will receive the Windows message to choose what to do:

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);
}

I put in the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.