WPF使用mousekeyhook库计算点击次数 - LoaderLock错误

时间:2015-07-12 10:55:13

标签: c# wpf mousekeyhook

我想编写一个计算窗口中鼠标点击次数的应用程序。经过一些研究,我发现了这个库:MouseKeyHook 我创建了wpf应用程序并复制了示例代码:

public partial class MainWindow : Window
{
    private IKeyboardMouseEvents m_GlobalHook;

    public MainWindow()
    {
        InitializeComponent();
        Subscribe();
    }

    public void Subscribe()
    {
        // Note: for the application hook, use the Hook.AppEvents() instead
        m_GlobalHook = Hook.GlobalEvents();

        m_GlobalHook.MouseDownExt += GlobalHookMouseDownExt;
        m_GlobalHook.KeyPress += GlobalHookKeyPress;
    }

    private void GlobalHookKeyPress(object sender, KeyPressEventArgs e)
    {
        Console.WriteLine("KeyPress: \t{0}", e.KeyChar);
    }

    private void GlobalHookMouseDownExt(object sender, MouseEventExtArgs e)
    {
        Console.WriteLine("MouseDown: \t{0}; \t System Timestamp: \t{1}", e.Button, e.Timestamp);

        // uncommenting the following line will suppress the middle mouse button click
        // if (e.Buttons == MouseButtons.Middle) { e.Handled = true; }
    }

    public void Unsubscribe()
    {
        m_GlobalHook.MouseDownExt -= GlobalHookMouseDownExt;
        m_GlobalHook.KeyPress -= GlobalHookKeyPress;

        //It is recommened to dispose it
        m_GlobalHook.Dispose();
    }
}

没有错误或警告,应用程序会检测键入的点击次数和键。但只需点击几下,我就会收到错误消息:

enter image description here

有时只需点击几下,有时会在100次点击后显示此错误(MouseDown事件 - 鼠标左键)。此外,当错误发生时,我的光标会在几秒钟内显着减慢。

1 个答案:

答案 0 :(得分:0)

尝试在与main不同的线程中创建该Hook对象。在DllMain中运行并阻止GUI的代码经常会出现此问题。