如何在Windows上检测鼠标点击?(XP/Vista/7) 例如,当我的应用程序正在运行时,它将检测用户是否单击了某些东西(不是在该应用程序的UI上而是在Windows UI上)。如果是,则执行另一个进程。
我不知道这是否可能,希望有人能给我一些指导。
谢谢!
如何在Windows上检测鼠标点击?(XP/Vista/7) 例如,当我的应用程序正在运行时,它将检测用户是否单击了某些东西(不是在该应用程序的UI上而是在Windows UI上)。如果是,则执行另一个进程。
我不知道这是否可能,希望有人能给我一些指导。
谢谢!
[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("user32.dll",CharSet=CharSet.Auto,
CallingConvention=CallingConvention.StdCall)]
public static extern bool UnhookWindowsHookEx(int idHook);
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;
}
public static int MouseHookProc(int nCode, IntPtr wParam, 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);
}
[DllImport("user32.dll",CharSet=CharSet.Auto,
CallingConvention=CallingConvention.StdCall)]
public static extern int CallNextHookEx(int idHook, int nCode,
IntPtr wParam, IntPtr lParam);
HookProc
不再在User32.dll
中,也不再被识别,似乎已经移动到了winuser.dll
https://learn.microsoft.com/en-us/windows/win32/api/winuser/nc-winuser-hookproc @Christophe Geers - lupaulus虽然Christophe Geers的解决方案可以帮助您捕获鼠标事件,但它并不能为此问题提供完整的解决方案。 Edward想知道如何获取点击事件。
要获取点击事件,请使用Christophe Geers提供的解决方案。 并添加/编辑以下内容:
enum MouseMessages
{
WM_LBUTTONDOWN = 0x0201,
WM_LBUTTONUP = 0x0202,
WM_MOUSEMOVE = 0x0200,
WM_MOUSEWHEEL = 0x020A,
WM_RBUTTONDOWN = 0x0204,
WM_RBUTTONUP = 0x0205
}
public static int MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
//Marshall the data from the callback.
MouseHookStruct MyMouseHookStruct = (MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));
if (nCode >= 0 &&
MouseMessages.WM_LBUTTONDOWN == (MouseMessages)wParam)
{
// Do something here
}
return CallNextHookEx(hookHandle, nCode, wParam, lParam);
}
Windows钩子机制是你需要使用的工具。看一下这篇文章:在C#中处理全局鼠标和键盘钩子