在Windows 10的任何位置检测鼠标左键单击

时间:2018-12-18 14:01:02

标签: c# winforms

我希望我的应用无需在应用上集中精力即可检测屏幕上任意位置的鼠标单击。我希望它可以普遍检测鼠标事件,即使其最小化也是如此。到目前为止,我只能在我的应用程序中检测到鼠标事件,并且在触发左键单击时显示为“ Cool”。

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


            [DllImport("user32.dll", CharSet = CharSet.Auto,
                CallingConvention = CallingConvention.StdCall)]
            public static extern int SetWindowsHookEx(int idHook, HookProc lpfn,
            IntPtr hInstance, int threadId);

            [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = CharSet.Auto,
             CallingConvention = CallingConvention.StdCall)]
            public static extern bool UnhookWindowsHookEx(int idHook);

            [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = CharSet.Auto,
             CallingConvention = CallingConvention.StdCall)]
            public static extern int CallNextHookEx(int idHook, int nCode,
            IntPtr wParam, IntPtr lParam);

            static int hHook = 0;
            public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);
            HookProc MouseHookProcedure;
            public const int WH_MOUSE = 7;


            private void DeactivateMouseHook_Click(object sender, System.EventArgs e)
            {
                bool ret = UnhookWindowsHookEx(hHook);
            }

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

            [StructLayout(LayoutKind.Sequential)]
            public class MouseHookStruct
            {
                public POINT pt;
                public int hwnd;
                public int wHitTestCode;
                public int dwExtraInfo;
            }

            enum MouseMessages
            {
                WM_LBUTTONDOWN = 0x0201,
                WM_LBUTTONUP = 0x0202,
            }

            public static int MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam)
            {
                MouseHookStruct MyMouseHookStruct = (MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));

                if (nCode >= 0 && MouseMessages.WM_LBUTTONDOWN == (MouseMessages)wParam)
                {
                    MessageBox.Show("Cool");
                }
                return CallNextHookEx(hHook, nCode, wParam, lParam);
            }

        private void ActivateMouseHook_Click(object sender, EventArgs e)
        {
            if (hHook == 0)
            {
                MouseHookProcedure = new HookProc(Form1.MouseHookProc);
                hHook = SetWindowsHookEx(WH_MOUSE,
                                 MouseHookProcedure,
                                 (IntPtr)0,
                                 AppDomain.GetCurrentThreadId());
            }
        }
    }

任何帮助将不胜感激

0 个答案:

没有答案