dotnet C# 全局 Windows 鼠标钩子
llovebo
共 4431字,需浏览 9分钟
·
2021-09-06 09:30
本文来告诉大家一个简单的方法实现全局的 鼠标钩子
实现封装方法十分简单,请看代码
public class MouseHookEventArgs : EventArgs
{
public bool Handle { get; set; }
/// <inheritdoc />
public MouseHookEventArgs(MouseMessages mouseMessage)
{
MouseMessage = mouseMessage;
}
public MouseMessages MouseMessage { get; }
public enum MouseMessages
{
MouseDown,
MouseMove,
MouseUp,
}
}
/// <summary>
/// 鼠标钩子
/// </summary>
public static class MouseHook
{
private delegate IntPtr MouseProc(int nCode, IntPtr wParam, IntPtr lParam);
private static MouseProc _proc = HookCallback;
private static IntPtr _hookID = IntPtr.Zero;
private const int WH_MOUSE_LL = 14;
private enum MouseMessages
{
WM_MOUSEMOVE = 0x0200
}
[ ]
private struct POINT
{
public int x;
public int y;
}
[ ]
private struct MSLLHOOKSTRUCT
{
private POINT pt;
private uint mouseData;
private uint flags;
private uint time;
private IntPtr dwExtraInfo;
}
[ ]
private static extern IntPtr SetWindowsHookEx(int idHook,
MouseProc lpfn, IntPtr hMod, uint dwThreadId);
[ ]
[ ]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[ ]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
IntPtr wParam, IntPtr lParam);
/// <summary>
/// 开启全局钩子
/// </summary>
/// <param name="moduleName"></param>
public static void Start(string moduleName)
{
Debug.WriteLine($"模块 {moduleName} 开启全局鼠标钩子");
_hookID = SetHook(_proc);
}
public static void Stop()
{
UnhookWindowsHookEx(_hookID);
}
private static IntPtr SetHook(MouseProc proc)
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_MOUSE_LL, proc,
Kernel32.GetModuleHandle(curModule.ModuleName), 0);
}
}
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 )
{
MouseHookEventArgs mouseHookEventArgs = null;
switch ((WM) wParam)
{
case WM.MOUSEMOVE:
mouseHookEventArgs=(new MouseHookEventArgs(MouseHookEventArgs.MouseMessages.MouseMove));
break;
case WM.LBUTTONDOWN:
mouseHookEventArgs=(new MouseHookEventArgs(MouseHookEventArgs.MouseMessages.MouseDown));
break;
case WM.LBUTTONUP:
mouseHookEventArgs=(new MouseHookEventArgs(MouseHookEventArgs.MouseMessages.MouseUp));
break;
}
//MSLLHOOKSTRUCT hookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));
if (mouseHookEventArgs != null)
{
OnMouseEvent(mouseHookEventArgs);
if (mouseHookEventArgs.Handle)
{
return IntPtr.Zero;
}
}
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
public static event EventHandler<MouseHookEventArgs> MouseEvent;
private static void OnMouseEvent(MouseHookEventArgs e)
{
MouseEvent?.Invoke(null, e);
}
}
本文会经常更新,请阅读原文: https://blog.lindexi.com/post/dotnet-C-%E5%85%A8%E5%B1%80-Windows-%E9%BC%A0%E6%A0%87%E9%92%A9%E5%AD%90.html
版权申明:本文来源于网友收集或网友提供,仅供学习交流之用,如果有侵权,请转告版主或者留言,本公众号立即删除。
支持小微:
腾讯云 搞活动了?玩服务器的可以搞搞。就这几天时间。
轻量 1C2G6M 60GB SSD盘297元/3年
链接:https://curl.qcloud.com/bR8ycXZa
右下角,您点一下在看图片
小微工资涨1毛
商务合作QQ:185601686
评论