如何在C#中创建具有不同线程的键盘钩子?

时间:2021-01-18 04:02:24

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?

我正在使用SetWindowsHookEx在c#中创建一个低级键盘钩子,问题是如何让on key事件函数在主线程的其他线程上运行?另外我目前还没有主线程以外的线程,所以如何创建一个将停止直到键盘钩子事件发生?

2 个解决方案

#1


2  

Here is the code for the C# Keyboard hook.

这是C#Keyboard钩子的代码。

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

你只需要调用Hook.CreateHook(METHODNAMEHERE);在一个新的Thread中(参见Thread类)。

#2


0  

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.

如果您使用的是Windows窗体应用程序,那么使用其他线程会有一些问题。他们需要使用Control.Invoke与表单控件进行通信。

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.

除此之外,启动“worker”线程,并使其等待一些ManualResetEvent或AutoResetEvent。当键盘钩子收到按键通知时,使用一些“共享”字段放置键,然后重置事件,“等待”线程可以处理它。

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

不要忘记在“共享”字段周围实现正确的锁定。

#1


2  

Here is the code for the C# Keyboard hook.

这是C#Keyboard钩子的代码。

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

你只需要调用Hook.CreateHook(METHODNAMEHERE);在一个新的Thread中(参见Thread类)。

#2


0  

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.

如果您使用的是Windows窗体应用程序,那么使用其他线程会有一些问题。他们需要使用Control.Invoke与表单控件进行通信。

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.

除此之外,启动“worker”线程,并使其等待一些ManualResetEvent或AutoResetEvent。当键盘钩子收到按键通知时,使用一些“共享”字段放置键,然后重置事件,“等待”线程可以处理它。

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

不要忘记在“共享”字段周围实现正确的锁定。