Question

I'm creating a low level keyboard hook in c# using SetWindowsHookEx, question is how can I make the on keyboard event function run on a thread other from the main thread? Also I currently don't have a thread other then the main thread, so how can I create one that will halt until a keyboard hook event will occur?

Was it helpful?

Solution

Here is the code for the C# Keyboard hook.

You just need to call Hook.CreateHook(METHODNAMEHERE); in a new Thread (see the Thread class).

OTHER TIPS

As there is an answer how to set a hook on new thread, this only answers the second part of the question:

If you are using a windows form application, there are some catches in using additional threads. They need to use Control.Invoke to communicate with the form controls.

Other than that, start your "worker" thread, and make it wait on some ManualResetEvent or AutoResetEvent. When your keyboard hook receives a notification for key press, use some "shared" field to place the key, then reset the event so, the "waiting" thread can process it.

Do not forget to implement proper locking around the "shared" field.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top