Search code examples
c#.netwindowshotkeys

Replace global hotkey


I have a application that lives in the tray and I would like to define serveral hotkeys which will trigger events in my program.

I found inspiration from the excellent answer by @AaronLS in this question: Set global hotkeys using C#

If I register a hot key that are already defined by another application RegisterHotKey will return false and not register it. So how can I override or replace a hot key?


Solution

  • So how can I override or replace a hot key?

    Ostensibly, you can't. That's by-design. Imagine if programs could hijack other program's hotkeys at-will - that wouldn't be pleasant.

    The Win32 UnregisterHotKey function requires the caller to be the same thread that registered using RegisterHotKey, which makes it impossible for another program to unregister another program's hotkeys:

    UnregisterHotKey function:

    Frees a hot key previously registered by the calling thread.

    What you can do is use Win32 to inject code into a remote process (assuming your own process has permsision to do this) then schedule code in that process's UI thread that then calls UnregisterHotKey - but that's another question.