MouseTool.cs
2.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace RCS.WinClient.Common
{
internal struct Mouse_LL_Hook_Data
{
internal long yx;
internal readonly int mouseData;
internal readonly uint flags;
internal readonly uint time;
internal readonly IntPtr dwExtraInfo;
}
public static class MouseTool
{
public delegate int HookProc(int code, IntPtr wParam, IntPtr lParam);
//安装钩子
[DllImport("user32.dll")]
public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr pInstance, int threadID);
//卸载钩子
[DllImport("user32.dll", CallingConvention = CallingConvention.StdCall)]
public static extern bool UnhookWindowsHookEx(IntPtr pHookHandle);
[DllImport("user32.dll")]
public static extern int CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam); //parameter 'hhk' is ignored.
internal static event Action<IntPtr, Mouse_LL_Hook_Data> CallbackErroeHandle;
internal static event Action<int> InsertErrorHandle;
//鼠标点击
public const int WH_MOUSE_LL = 14;
//鼠标按下
public const int WM_LBUTTONDOWN = 0x0201;
//鼠标松开
public const int WM_LBUTTONUP = 0x0202;
private static IntPtr pMouseHook = IntPtr.Zero;
private static HookProc mouseHookProc;
private static int MouseHookCallback(int code, IntPtr wParam, IntPtr lParam)
{
if (code < 0)
{
return CallNextHookEx(IntPtr.Zero, code, wParam, lParam);
}
Mouse_LL_Hook_Data mhd = (Mouse_LL_Hook_Data)Marshal.PtrToStructure(lParam, typeof(Mouse_LL_Hook_Data))!;
CallbackErroeHandle?.Invoke(wParam, mhd);
return 0;
}
public static bool InsertMouseHook()
{
if (pMouseHook == IntPtr.Zero)
{
mouseHookProc = MouseHookCallback;
pMouseHook = SetWindowsHookEx(WH_MOUSE_LL, mouseHookProc, IntPtr.Zero, 0);
if (pMouseHook == IntPtr.Zero)
{
int error = Marshal.GetLastWin32Error();
InsertErrorHandle?.Invoke(error);
//MessageBox.Show($"Failed to install global mouse hook. Error code: {error}");
RemoveMouseHook();
return false;
}
}
return true;
}
public static bool RemoveMouseHook()
{
if (pMouseHook != IntPtr.Zero)
{
if (UnhookWindowsHookEx(pMouseHook))
{
pMouseHook = IntPtr.Zero;
}
else
{
return false;
}
}
return true;
}
}
}