0

I'm using the following code to track keys being pressed in an external application.

It works, but unfortunately the external window doesn't track the hotkey anymore when the program is running.

Is there any way register the hotkey without affecting any external programs?

[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

RegisterHotKey(formHandle, MYACTION_HOTKEY_ID, 0, (int)Keys.D1);

protected override void WndProc(ref Message m)
{
    if (h != null)
        h.GlobalHotkeyListener(ref m);
    base.WndProc(ref m);
}



internal void GlobalHotkeyListener(ref Message m)
{
    if (IsRunning && m.Msg == 0x0312 && m.WParam.ToInt32() == MYACTION_HOTKEY_ID)
    {
        Point p;
        if (GetCursorPos(out p))
        {
            IntPtr hWnd = WindowFromPoint(p);
            Table t = IsTableRegistered(hWnd);
            if (hWnd != IntPtr.Zero && t != null)
            { 
                // Do stuff to window under mouse when hotkey is pressed
            }
        }
    }
}
Ðаn
  • 10,934
  • 11
  • 59
  • 95
  • 1
    What you seem to do is not monitoring the hot key event, but you rather replace the registered hotkey -- which leads to the previously existing hot key becoming unregistered. If you just want to monitor certain key presses, look perhaps here: http://stackoverflow.com/questions/604410/global-keyboard-capture-in-c-sharp-application –  May 13 '17 at 17:05
  • 1
    No. A hotkey doesn't do what you think it does. It does what you see it do. Listening for keystrokes without it affecting the active program requires SetWindowsHookEx() instead. Visit Nuget.org and search for "keyboard hook". – Hans Passant May 13 '17 at 17:05
  • That explains a lot. Thanks guys! –  May 13 '17 at 17:07

0 Answers0