• 0

[C#] Detect keypresses on any window


Question

I'm trying to be able to detect a keypress on any child window of my form, regardless of which child actually has the focus.

I've tried using a keyboard hook (through P/Invoke). This works, but for some reason this causes a very noticeable (2-3 second) lag in my application any time it calls the hook API or any other application calls the hook API.

I've also tried RegisterHotKey, but this causes the key to be unavailable for any other application while mine is running.

Can anyone offer any help? Is there another way to accomplish this that I just can't find, or is there an explanation for why P/Invoking SetWindowsHookEx causes such a performance drop?

Link to comment
https://www.neowin.net/forum/topic/261075-c-detect-keypresses-on-any-window/
Share on other sites

7 answers to this question

Recommended Posts

  • 0

I'll explain a bit more fully.

First, the child windows (they're actually control windows, not forms) are all on a UserControl, which is hosted on a Form (this is a plugin setup). The UserControl doesn't accept keypresses (although it should, KeyUp/Down simply don't fire), but it could still have focus. Likewise with the parent form. There are also toolbuttons on the parent form that frequently have focus. It would actually be QUITE a bit of work to have every possible control that could have focus all routing into a single event handler.

Having only the child windows handling KeyUp/Down would be acceptable, but there's a problem with that too. One of those child windows is actually a native window which I don't have access to the source code for, and which doesn't accept key events. But it can still have focus, and if it does have focus, I need to respond to certain events (Ctrl+C would be one fairly important one) and call a function on the native control. Likewise, other controls need to respond to keypresses (delete key for example) even when this native window has focus.

So, just funnelling all KeyDown/Up events into a single handler is logistically very difficult, and the one control that's going to have focus 95% of the time will be excluded anyway because it's just not capable of notifying me when a key press happens while it has focus.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.