繁体   English   中英

WPF 中的全局鼠标钩子

[英]Global Mouse Hook in WPF

我需要在屏幕上而不是在我的应用程序内获取鼠标位置。

我在这里使用了全局鼠标和键盘钩子

它在 winforms 下工作正常,但在 wpf 下不起作用。

我正在使用代码的 version1 并使用以下内容

var activity = new UserActivityHook();
activity.OnMouseActivity += activity_OnMouseActivity;

但不是工作它给了我以下错误:

附加信息:找不到指定的模块

下面的代码

public void Start(bool InstallMouseHook, bool InstallKeyboardHook)
{
    // install Mouse hook only if it is not installed and must be installed
    if (hMouseHook == 0 && InstallMouseHook)
    {
        // Create an instance of HookProc.
        MouseHookProcedure = new HookProc(MouseHookProc);

        //install hook
        hMouseHook = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProcedure,
            Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);
        //If SetWindowsHookEx fails.
        if (hMouseHook == 0)
        {
            //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set. 
            int errorCode = Marshal.GetLastWin32Error();
            //do cleanup
            Stop(true, false, false);
            //Initializes and throws a new instance of the Win32Exception class with the specified error. 
            throw new Win32Exception(errorCode);
        }
    }
}

WPF 有没有其他选择,还是我遗漏了什么?

dotctor 的回答给出了鼠标位置,但不是我正在寻找的事件。

所以我自己想通了。 这是我的发现以供将来参考。

我们需要改变:

//install hook
hMouseHook = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProcedure,
             Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);

到以下几点:

// Install hook
hMouseHook = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProcedure, IntPtr.Zero, 0);

或者,您可以从此处下载编辑过的 cs 文件,然后我们可以使用该事件

activity.OnMouseActivity += activity_OnMouseActivity;

我们可以使用eXeY来获取鼠标位置。

  1. 向巫师寻求帮助! (用简单的方法做)
    添加对System.Windows.Forms引用并使用Control.MousePosition

  2. 成为炼金术士! (组合你的物品)
    结合Visual.PointToScreenMouse.GetPositionApplication.Current.MainWindow

  3. 使用能量脉轮 (win32)

     [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetCursorPos(ref Win32Point pt); [StructLayout(LayoutKind.Sequential)] internal struct Win32Point { public Int32 X; public Int32 Y; }; public static Point GetMousePosition() { var w32Mouse = new Win32Point(); GetCursorPos(ref w32Mouse); return new Point(w32Mouse.X, w32Mouse.Y); }

暂无
暂无

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

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