C# · 12月 26, 2021

c# – 如何检测鼠标点击?

如何在 Windows上检测鼠标点击? (XP / Vista / 7的).
例如,当我的应用程序运行时,它将检测用户是否点击某些东西(不是在该应用程序UI上,而是在Windows UI上).如果是,执行另一个进程.

我不知道这是否可能,我希望有人可以给我一些指导.

谢谢!

解决方法 如果要拦截任何鼠标点击,移动,鼠标滚轮点击等,您需要编写一个鼠标钩.

如果您想在自己的应用程序之外跟踪鼠标活动,这是AFAIK的唯一方法.如果要安装挂钩,则需要从User32.dll文件导入SetWindowsHookEx(…)函数.它涉及到interop(PInvoke),你必须导入(DllImport)一些功能.

这是Microsoft的官方文档,关于如何在C#中实现这一点:

How to set a Windows hook in Visual C# .NET

我会在这里总结一下,只是为了完成一个连接死亡的答案.

从SetWindowsHookEx函数开始:

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

现在你可以设置你的钩子例如:

public class Form1{ static int hHook = 0; public delegate int HookProc(int nCode,IntPtr wParam,IntPtr lParam); HookProc MouseHookProcedure; 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()); } }}

不要忘了解开它.您将需要另一个DllImport:

[DllImport(“user32.dll”,CallingConvention=CallingConvention.StdCall)]public static extern bool UnhookWindowsHookEx(int idHook);private void DeactivateMouseHook_Click(object sender,System.EventArgs e){ bool ret = UnhookWindowsHookEx(hHook);}

您可以使用HookProc代理(MouseHookProcedure)捕获鼠标活动.这涉及到一些编组以捕获数据.

[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;}public static int MouseHookProc(int nCode,IntPtr lParam){ MouseHookStruct MyMouseHookStruct = (MouseHookStruct) Marshal.PtrToStructure(lParam,typeof(MouseHookStruct)); // You can get the coördinates using the MyMouseHookStruct. // … return CallNextHookEx(hHook,nCode,wParam,lParam); }

别忘了调用钩链中的下一个项目(CallNextHookEx)!

[DllImport(“user32.dll”,CallingConvention=CallingConvention.StdCall)]public static extern int CallNextHookEx(int idHook,int nCode,IntPtr lParam);

PS:你可以对键盘做同样的事情.