鼠标钩子,仅在点击 Button 时响应

Mouse hook, respond only when clicked on Button

我开发了响应低级鼠标点击的 C# 应用程序。我用鼠标钩子来做到这一点。该应用程序工作正常,每当我单击任何 window 它都会响应并执行一些任务。但我想在这里做一个修改。我想在 window 上的任何按钮上执行单击时响应鼠标单击。如果我点击 window 的普通区域,它应该不会响应。目前它在我点击的任何地方响应。我找不到如何确定我是否单击了按钮。

这是我的代码:

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);

请帮我解决这个问题。谢谢。

您似乎在寻找类似 WindowFromPoint 的内容。

调用它来查看鼠标光标下的内容,然后您可以查询它以获取您感兴趣的任何属性。