0

我想编写一个计算窗口中鼠标点击次数的应用程序。经过一番研究,我发现了这个库: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();
    }
}

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

在此处输入图像描述

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

4

1 回答 1

0

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

于 2015-07-12T11:31:28.630 回答