2015-09-25 70 views
0

我開發了響應低級別鼠標點擊的C#應用​​程序。我用鼠標鉤來做到這一點。該應用程序工作正常,每當我點擊任何窗口它響應並執行一些任務。但我想在這裏做一個修改。我想要在窗口上的任何按鈕上執行單擊時響應鼠標點擊。如果我點擊窗口的平坦區域,它不應該回應。目前它響應無論我點擊。我找不到如何識別我是否點擊了按鈕。鼠標鉤,僅在點擊按鈕時才作出響應

這是我的代碼:

private IntPtr SetHook(MouseHookHandler proc) 
    { 
     using (ProcessModule module = Process.GetCurrentProcess().MainModule) 
      return SetWindowsHookEx(WH_MOUSE_LL, proc, GetModuleHandle(module.ModuleName), 0); 
    } 
    private IntPtr HookFunc(int nCode, IntPtr wParam, IntPtr lParam) 
    { 
     if (nCode >= 0) 
     { 
      if (MouseMessages.WM_LBUTTONUP == (MouseMessages)wParam) 
       if (LeftButtonUp != null) 
        LeftButtonUp((MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT))); 
      if (MouseMessages.WM_RBUTTONUP == (MouseMessages)wParam) 
       if (RightButtonUp != null) 
        RightButtonUp((MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT))); 

     } 
     return CallNextHookEx(hookID, nCode, wParam, lParam); 
    } 

[StructLayout(LayoutKind.Sequential)] 
    public struct POINT 
    { 
     public int x; 
     public int y; 
    } 

[StructLayout(LayoutKind.Sequential)] 
    public struct MSLLHOOKSTRUCT 
    { 
     public POINT pt; 
     public uint mouseData; 
     public uint flags; 
     public uint time; 
     public IntPtr dwExtraInfo; 
    } 

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
    private static extern IntPtr SetWindowsHookEx(int idHook, 
     MouseHookHandler lpfn, IntPtr hMod, uint dwThreadId); 

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
    [return: MarshalAs(UnmanagedType.Bool)] 
    public static extern bool UnhookWindowsHookEx(IntPtr hhk); 

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
    private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam); 

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
    private static extern IntPtr GetModuleHandle(string lpModuleName); 

請幫我解決這個問題。謝謝。

回答

0

看來你正在尋找沿WindowFromPoint的東西。

調用以查看鼠標光標下的內容,然後可以查詢它是否感興趣的任何屬性。

+0

謝謝您的重播。現在我添加了下面的代碼: IntPtr win = WindowFromPoint(ms.pt); 我得到了窗口句柄作爲勝利。現在我可以通過傳遞'win'句柄的光標位置來使用GetChildAtPoint()嗎?或任何其他建議? – Vignesh

+0

我試圖使用ControlFromHandle將intptr'win'轉換爲Control,並且它始終返回null。如果成功,我可以調用GetChildAtPoint()方法。 – Vignesh

+0

ControlFromHandle僅適用於您的正常流程。嘗試GetClassName或GetWindowText(都是原生函數,所以使用pinvoke) –