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
2008-10-07 13:45:00
What will happen if the new thread will stop after Hook.CreateHook(METHODNAMEHERE);?
Haim Bender
2008-10-07 13:50:49
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
2008-10-07 13:45:26
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
2008-10-07 13:49:55
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
2008-10-07 13:52:09
The answer on how to set the hook on a seperate thread dosn't work..
Haim Bender
2008-10-07 14:39:58
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
2008-10-07 15:28:07