简体   繁体   中英

How do I create a keyboard hook with a different thread in C#?

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM