简体   繁体   English

在不同的线程中安装低级鼠标钩

[英]install low-level mouse hook in different thread

I need to install a WH_KEYBOARD_LL hook in my WPF application, that by itself is not a big problem. 我需要在WPF应用程序中安装WH_KEYBOARD_LL挂钩,这本身并不是一个大问题。 However I need to install it in a thread other than my main application thread because otherwise the cursor will freeze when the UI thread is busy. 但是,我需要将其安装在我的主应用程序线程之外的其他线程中,因为否则,当UI线程繁忙时,光标将冻结。 I have read this article and this SO question, but it is not quite working yet. 我已经阅读了这篇文章和这个 SO问题,但是还不能完全解决。 A comment in the question suggest me to start an Application in the thread that I create the hook, but then I get and exception saying I can't start 2 applications in the same AppDomain. 问题中的注释建议我在创建钩子的线程中启动一个Application,但是随后我得到异常提示说我无法在同一AppDomain中启动2个应用程序。 Are there any solutions to this or is there another, easier way to install the hook in another thread? 是否有解决方案,或者有另一种更简单的方法将钩子安装到另一个线程中?

You can create a new thread with a WPF dispatcher using this code: 您可以使用以下代码通过WPF调度程序创建新线程:

public class DispatcherBuilder : IBuilder<Dispatcher>
{
    public Dispatcher Build()
    {
        Dispatcher dispatcher = null;
        var manualResetEvent = new ManualResetEvent(false);
        var thread = new Thread(() =>
            {
                dispatcher = Dispatcher.CurrentDispatcher;
                var synchronizationContext = new DispatcherSynchronizationContext(dispatcher);
                SynchronizationContext.SetSynchronizationContext(synchronizationContext);

                manualResetEvent.Set();
                Dispatcher.Run();
            });
        thread.Start();
        manualResetEvent.WaitOne();
        manualResetEvent.Dispose();
        return dispatcher;
    }
}

The Build method creates a new thread with a WPF Dispatcher and correct synchronization context on it. Build方法使用WPF Dispatcher创建一个新线程,并在其上更正同步上下文。 This thread runs until you shut down the dispatcher. 该线程一直运行,直到您关闭调度程序为止。 You could then use eg Dispatcher.BeginInvoke to create your hook. 然后,您可以使用例如Dispatcher.BeginInvoke创建您的钩子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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