用于检测鼠标在屏幕上任何位置单击的鼠标钩子事件

时间:2014-01-16 03:32:46

标签: c# winforms

以下是我尝试的代码:

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

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

    [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 ActivateMouseHook_Click(object sender, System.EventArgs e)
    {
        if (hHook == 0)
        {
            MouseHookProcedure = new HookProc(Form1.MouseHookProc);
            hHook = SetWindowsHookEx(WH_MOUSE,
                             MouseHookProcedure,
                             (IntPtr)0,
                             AppDomain.GetCurrentThreadId());
        }
    }

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

我正在尝试使用“酷”消息指示鼠标左键单击。但似乎没有消息出来。我的编码出了什么问题?

0 个答案:

没有答案