簡體   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