views:

577

answers:

2

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?

+2  A: 

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).

Daok
What will happen if the new thread will stop after Hook.CreateHook(METHODNAMEHERE);?
Haim Bender
A: 

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.

Sunny
Your proposal offers to run some of the event handling on the UI thread..., I don't think thats such a good idea...
Haim Bender
There was already an answer how to set the hook on a separate thread. I'm just answering for the second part of the question, as well as just point some of the complications with using threads in windows form application.
Sunny
The answer on how to set the hook on a seperate thread dosn't work..
Haim Bender
So, set the hook on the UI thread. As it will not touch the form's controls, it's safe, and the only work it has to do is to set the key, and make the other thread to do the work, so it will do no harm.
Sunny