HOOK——鼠标钩子程序

6 篇文章 0 订阅
这个博客展示了如何使用C#实现一个低级鼠标钩子(Low-Level Mouse Hook),通过`SetWindowsHookEx`函数注册钩子,监听并处理鼠标事件,如鼠标移动、点击和滚轮滚动等。代码中定义了`MouseHook`类,包含各种鼠标事件常量,并实现了事件处理回调函数`MouseHookProcedure`,用于在接收到鼠标事件时触发自定义的`OnMouseActivity`事件。
摘要由CSDN通过智能技术生成

MouseHook.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Common
{
    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;
        private const int WM_MOUSEWHEEL = 0x020A;
        //private const int WM_VSCROLL = 0x0115;

        public event MouseEventHandler OnMouseActivity;

        public static int hMouseHook = 0;

        public const int WH_MOUSE_LL = 14;//low level mouse event
        public const int WH_MOUSE = 7;//normal level mouse event
        //public const int WH_SYSMSGFILTER = 6;

        HookProc MouseHookProcedure;
        //Log _log = new Log("MouseHook", true, Log4netWrapper.Default);
        [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("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int GetLastError();

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

        [DllImport("kernel32.dll")]
        private static extern int GetCurrentThreadId();//获取在系统中的线程ID

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


        public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);


        public MouseHook()
        {
        }

        ~MouseHook()
        {
            Stop();
        }

        public void Start()
        {
            if (hMouseHook == 0)
            {
                MouseHookProcedure = new HookProc(MouseHookProc);
                //hMouseHook = SetWindowsHookEx(WH_SYSMSGFILTER, MouseHookProcedure, GetModuleHandle("user32"), 0);//第一个参数是WH_MOUSE_LL,表示捕获所有线程的鼠标消息,同时最后一个参数必须是0
                hMouseHook = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProcedure, GetModuleHandle("user32"), 0);//第一个参数是WH_MOUSE_LL,表示捕获所有线程的鼠标消息,同时最后一个参数必须是0
                //hMouseHook = SetWindowsHookEx(WH_MOUSE, MouseHookProcedure, GetModuleHandle("user32"), GetCurrentThreadId());//只捕获当前应用程序(当前线程)的鼠标消息,最后一个参数是当前线程id,使用GetCurrentThreadId()获得,一定不要使用托管线程id(Thread.CurrentThread.ManagedThreadId)。
                if (hMouseHook == 0)
                {
                    int errorCode = GetLastError();
                    //_log.E("SetWindowsHookEx failed.error code:" + errorCode);
                    Stop();
                }
            }
        }

        public void Stop()
        {
            bool retMouse = true;
            if (hMouseHook != 0)
            {
                retMouse = UnhookWindowsHookEx(hMouseHook);
                hMouseHook = 0;
            }

            if (!(retMouse))
            {
                //_log.E("UnhookWindowsHookEx failed.");
            }
        }

        private int MouseHookProc(int nCode, Int32 wParam, IntPtr lParam)
        {      
            //只处理鼠标滚动的情况 WM_MOUSEWHEEL  
            if ((wParam == WM_MOUSEWHEEL || wParam == WM_LBUTTONUP) && (nCode >= 0) && (OnMouseActivity != null))
            {
                MouseButtons button = MouseButtons.None;
                int clickCount = 0;

                switch (wParam)
                {
                    case WM_LBUTTONDOWN:
                        button = MouseButtons.Left;
                        clickCount = 1;
                        break;
                    case WM_LBUTTONUP:
                        button = MouseButtons.Left;
                        clickCount = 1;
                        break;
                    case WM_LBUTTONDBLCLK:
                        button = MouseButtons.Left;
                        clickCount = 2;
                        break;
                    case WM_RBUTTONDOWN:
                        button = MouseButtons.Right;
                        clickCount = 1;
                        break;
                    case WM_RBUTTONUP:
                        button = MouseButtons.Right;
                        clickCount = 1;
                        break;
                    case WM_RBUTTONDBLCLK:
                        button = MouseButtons.Right;
                        clickCount = 2;
                        break;
                    case WM_MOUSEWHEEL:
                        button = MouseButtons.None;
                        clickCount = 0;
                        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);
        }
    }
}

使用HOOK

 //启用钩子
 hook = new MouseHook();
 hook.OnMouseActivity += Hook_OnMouseActivity;
 hook.Start();

 //注销钩子
 hook.Stop();

钩子子程序

private static void Hook_OnMouseActivity(object sender, MouseEventArgs e)
        {
            try
            {
                    if (e.Button == System.Windows.Forms.MouseButtons.Left)
                    {
                        //业务处理
                    }
            }
            catch (Exception ex)
            {
                
            }
        }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值