C# 鼠标钩子使用

using System;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using System.Diagnostics;
using System.Collections.Generic;
using System.Drawing;

namespace MouseHookInfor
{
    public class MouseHook
    {
        private const int WM_MOUSEMOVE = 0x200;
        private const int WM_LBUTTONDOWN = 0x201;
        private const int WM_RBUTTONDOWN = 0x204;
        private const int WM_MBUTTONDOWN = 0x207;
        private const int WM_LBUTTONUP = 0x202;
        private const int WM_RBUTTONUP = 0x205;
        private const int WM_MBUTTONUP = 0x208;
        private const int WM_LBUTTONDBLCLK = 0x203;
        private const int WM_RBUTTONDBLCLK = 0x206;
        private const int WM_MBUTTONDBLCLK = 0x209;
        //全局的事件
        public event MouseEventHandler OnMouseActivity;
        static int hMouseHook = 0;   //鼠标钩子句柄
        //鼠标常量
        public const int WH_MOUSE_LL = 14;   //mouse   hook   constant
        HookProc MouseHookProcedure;   //声明鼠标钩子事件类型.
        //声明一个Point的封送类型
        [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;
        }
        //装置钩子的函数
        [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, Int32 wParam, IntPtr lParam);
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);
        public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
        ///  
        ///   墨认的构造函数构造当前类的实例.
        ///  
        public MouseHook()
        {
            Start();
        }
        //析构函数.
        ~MouseHook()
        {
            Stop();
        }
        public void Start()
        {
            //安装鼠标钩子
            if (hMouseHook == 0)
            {
                Process curProcess = Process.GetCurrentProcess();
                ProcessModule curModule = curProcess.MainModule;

                //生成一个HookProc的实例.
                MouseHookProcedure = new HookProc(MouseHookProc);
                hMouseHook = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProcedure, GetModuleHandle(curModule.ModuleName), 0);
                //如果装置失败停止钩子
                if (hMouseHook == 0)
                {
                    Stop();
                    throw new Exception("SetWindowsHookEx failed. ");
                }
            }
        }
        public void Stop()
        {
            bool retMouse = true;
            if (hMouseHook != 0)
            {
                retMouse = UnhookWindowsHookEx(hMouseHook);
                hMouseHook = 0;
            }
            //如果卸下钩子失败
            if (!(retMouse)) throw new Exception("UnhookWindowsHookEx   failed. ");
        }
        private int MouseHookProc(int nCode, Int32 wParam, IntPtr lParam)
        {
            //如果正常运行并且用户要监听鼠标的消息
            if ((nCode >= 0) && (OnMouseActivity != null))
            {
                MouseButtons button = MouseButtons.None;
                int clickCount = 0;
                switch (wParam)
                {
                    case WM_LBUTTONDOWN://鼠标左键down
                        button = MouseButtons.Left;
                        clickCount = 1;
                        break;
                    case WM_LBUTTONUP://鼠标左键up
                        //button = MouseButtons.Left;
                        //clickCount = 1;
                        break;
                    case WM_LBUTTONDBLCLK://鼠标左键双击
                        button = MouseButtons.Left;
                        clickCount = 2;
                        break;
                    case WM_RBUTTONDOWN://鼠标右键down
                        button = MouseButtons.Right;
                        clickCount = 1;
                        break;
                    case WM_RBUTTONUP://鼠标右键up
                        button = MouseButtons.Right;
                        clickCount = 1;
                        break;
                    case WM_RBUTTONDBLCLK://鼠标右键双击
                        button = MouseButtons.Right;
                        clickCount = 2;
                        break;
                }
                //从回调函数中得到鼠标的信息
                MouseHookStruct MyMouseHookStruct = (MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));
                MouseEventArgs e = new MouseEventArgs(button, clickCount, MyMouseHookStruct.pt.x, MyMouseHookStruct.pt.y, 0);
                OnMouseActivity(this, e);
            }
            return CallNextHookEx(hMouseHook, nCode, wParam, lParam);
        }
    }
}

主程序代码如下:

public Form1()
{
    MouseHook mh;//鼠标钩子
    mh = new MouseHook();
     mh.OnMouseActivity += mh_MouseActivity;
}

       void mh_MouseActivity(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && e.Clicks == 1)
            {
                 ...........
            }
        }





  
  
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是C#全局鼠标钩子的完整源码: 首先,创建一个名为MouseHook的类,实现IMouseHook接口: ```csharp using System; using System.Runtime.InteropServices; namespace MouseHookExample { public class MouseHook : IMouseHook { private const int WH_MOUSE_LL = 14; private const int WM_LBUTTONDOWN = 0x0201; private const int WM_RBUTTONDOWN = 0x0204; private LowLevelMouseProc _proc; private IntPtr _hookId = IntPtr.Zero; public event EventHandler<MouseEventArgs> LeftButtonDown; public event EventHandler<MouseEventArgs> RightButtonDown; public void Start() { _proc = HookCallback; _hookId = SetHook(_proc); } public void Stop() { UnhookWindowsHookEx(_hookId); _hookId = IntPtr.Zero; } private IntPtr SetHook(LowLevelMouseProc proc) { using (var curProcess = System.Diagnostics.Process.GetCurrentProcess()) using (var curModule = curProcess.MainModule) { return SetWindowsHookEx(WH_MOUSE_LL, proc, GetModuleHandle(curModule.ModuleName), 0); } } private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam) { if (nCode >= 0 && (wParam == (IntPtr)WM_LBUTTONDOWN || wParam == (IntPtr)WM_RBUTTONDOWN)) { var hookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT)); var args = new MouseEventArgs(hookStruct.pt.x, hookStruct.pt.y); if (wParam == (IntPtr)WM_LBUTTONDOWN) { LeftButtonDown?.Invoke(this, args); } else if (wParam == (IntPtr)WM_RBUTTONDOWN) { RightButtonDown?.Invoke(this, args); } } return CallNextHookEx(_hookId, nCode, wParam, lParam); } private delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelMouseProc lpfn, IntPtr hMod, uint dwThreadId); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private 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); [StructLayout(LayoutKind.Sequential)] private struct POINT { public int x; public int y; } [StructLayout(LayoutKind.Sequential)] private struct MSLLHOOKSTRUCT { public POINT pt; public uint mouseData; public uint flags; public uint time; public IntPtr dwExtraInfo; } } } ``` 接下来,定义一个名为MouseEventArgs的类,用于传递鼠标事件的参数: ```csharp using System; namespace MouseHookExample { public class MouseEventArgs : EventArgs { public int X { get; } public int Y { get; } public MouseEventArgs(int x, int y) { X = x; Y = y; } } } ``` 最后,定义一个名为IMouseHook的接口,用于规范MouseHook类的实现: ```csharp using System; namespace MouseHookExample { public interface IMouseHook { event EventHandler<MouseEventArgs> LeftButtonDown; event EventHandler<MouseEventArgs> RightButtonDown; void Start(); void Stop(); } } ``` 现在,我们可以在其他类中使用鼠标钩子: ```csharp using System; namespace MouseHookExample { class Program { static void Main(string[] args) { var mouseHook = new MouseHook(); mouseHook.LeftButtonDown += (sender, e) => Console.WriteLine($"Left button down at ({e.X}, {e.Y})"); mouseHook.RightButtonDown += (sender, e) => Console.WriteLine($"Right button down at ({e.X}, {e.Y})"); mouseHook.Start(); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); mouseHook.Stop(); } } } ``` 现在,当用户按下鼠标左键或右键时,程序将在控制台中输出相应的信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值