-
Notifications
You must be signed in to change notification settings - Fork 0
/
cHookClass.cs
412 lines (333 loc) · 16.3 KB
/
cHookClass.cs
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Pipes;
/*using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;*/
using System.Runtime.InteropServices;
using System.Drawing;
using System.Diagnostics;
namespace ActionLogger
{
/// <summary>
/// Класс для перехвата событий клавиатуры и мыши
/// </summary>
public class HookClass
{
private bool _installed;
#region API data definitions
[StructLayout(LayoutKind.Sequential)]
public class KBDLLHOOKSTRUCT
{
public uint vkCode;
public uint scanCode;
public KBDLLHOOKSTRUCTFlags flags;
public uint time;
public UIntPtr dwExtraInfo;
}
[Flags]
public enum KBDLLHOOKSTRUCTFlags : uint
{
LLKHF_EXTENDED = 0x01,
LLKHF_INJECTED = 0x10,
LLKHF_ALTDOWN = 0x20,
LLKHF_UP = 0x80,
}
[StructLayout(LayoutKind.Sequential)]
public struct MSLLHOOKSTRUCT
{
public POINT pt;
public int mouseData; // be careful, this must be ints, not uints (was wrong before I changed it...). regards, cmew.
public int flags;
public int time;
public UIntPtr dwExtraInfo;
}
public enum HookType : int
{
WH_JOURNALRECORD = 0,
WH_JOURNALPLAYBACK = 1,
WH_KEYBOARD = 2,
WH_GETMESSAGE = 3,
WH_CALLWNDPROC = 4,
WH_CBT = 5,
WH_SYSMSGFILTER = 6,
WH_MOUSE = 7,
WH_HARDWARE = 8,
WH_DEBUG = 9,
WH_SHELL = 10,
WH_FOREGROUNDIDLE = 11,
WH_CALLWNDPROCRET = 12,
WH_KEYBOARD_LL = 13,
WH_MOUSE_LL = 14
}
[StructLayout(LayoutKind.Sequential)]
struct MOUSEHOOKSTRUCT
{
public POINT pt;
public IntPtr hwnd;
public uint wHitTestCode;
public IntPtr dwExtraInfo;
}
public const int WM_KEYDOWN = 0x100;
public const int WM_KEYUP = 0x101;
public const int WM_LBUTTONDOWN = 0x0201;
public const int WM_LBUTTONUP = 0x0202;
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;
}
[StructLayout(LayoutKind.Sequential)]
public struct MSG
{
public IntPtr hwnd;
public UInt32 message;
public IntPtr wParam;
public IntPtr lParam;
public UInt32 time;
public POINT pt;
}
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int _Left;
public int _Top;
public int _Right;
public int _Bottom;
}
public const int WM_GETTEXT = 0x000D;
public const int WM_GETTEXTLENGTH = 0x000E;
#endregion
#region API declarations
delegate int HookProc(int code, IntPtr wParam, IntPtr lParam);
// Windows hook routines
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("user32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
static extern IntPtr SetWindowsHookEx(HookType hookType, HookProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll",CallingConvention = CallingConvention.StdCall)]
static extern int CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam,
IntPtr lParam);
[DllImport("user32.dll", SetLastError = true,CallingConvention = CallingConvention.StdCall)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
//Finding window in mouse position
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetWindowRect(IntPtr hwnd, out RECT lpRect);
//Get text of the current Window
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, int wParam, StringBuilder lParam);
#endregion
private IntPtr HHook;
private IntPtr HHookM;
private static HookProc KBCallbackDelegate = null;
private static HookProc MouseCallbackDelegate = null;
private static WindowsEnumerator weFinder = null;
private uint ThreadId;
public uint ProcessId {
get {
return ThreadId;
}
set {
ThreadId = value;
}
}
public bool Installed
{
get { return _installed; }
set { _installed = value; }
}
/// <summary>
/// Получение дескриптора текущего процесса
/// </summary>
/// <param name="Handle"></param>
/// <returns></returns>
public uint GetProcess(IntPtr Handle)
{
uint wndProcessId = 0;
uint threadId = 0; ;
threadId = GetWindowThreadProcessId(Handle, out wndProcessId);
ThreadId = threadId;
Process pProcess = Process.GetProcessById((int)wndProcessId);
ProcessModule pmModuleMain = pProcess.MainModule;
IntPtr hModule = GetModuleHandle(pmModuleMain.ModuleName);
StringBuilder exeName = new StringBuilder(1024);
cWindowsHelper.GetModuleFileNameEx(pProcess.Handle, hModule, exeName, 1024);
ActionHost.strTargetExeName = exeName.ToString();
return threadId;
}
/// <summary>
/// Каллбэк функция для клавиатурных событий. Пока отключена
/// </summary>
/// <param name="code">Флаг передачи управления следующему хуку</param>
/// <param name="wParam"> Содержит доп. информацию о сообщении </param>
/// <param name="lparam"> Содержит информацию о нажатых клавишах</param>
/// <returns></returns>
private int KBCallbackFunction(int code, IntPtr wParam, IntPtr lparam)
{
/*MSG msgstruct = (MSG) Marshal.PtrToStructure(wParam, typeof(MSG));
System.Windows.Forms.Message Message_ = new System.Windows.Forms.Message();
Message_.HWnd = msgstruct.hwnd;
Message_.LParam = msgstruct.lParam;*/
/*Message_.WParam = msgstruct.wParam;*/
ActionLogger.UserAction uaKbd = new ActionLogger.UserAction();
KBDLLHOOKSTRUCT kbinfo = (KBDLLHOOKSTRUCT) Marshal.PtrToStructure(lparam,typeof(KBDLLHOOKSTRUCT));
uaKbd.ThreadId = this.ThreadId;
System.Windows.Forms.Message msg = new System.Windows.Forms.Message();
msg.Msg = wParam.ToInt32();
msg.HWnd = IntPtr.Zero;
msg.WParam = wParam;
msg.LParam = lparam;
uaKbd.EventCode = msg;
uaKbd.ControlHandle = IntPtr.Zero;
uaKbd.KeyCode= (int)kbinfo.vkCode;
ActionHost.AddItem(uaKbd);
/* BinaryFormatter bfSerializer = new BinaryFormatter();
NamedPipeServerStream pipeStream = new NamedPipeServerStream("hookpipe");
bfSerializer.Serialize(pipeStream,uaKbd);
pipeStream.Close();*/
return CallNextHookEx(IntPtr.Zero, code, wParam, lparam);
}
/// <summary>
/// Callback функция для хука -- определение окна под мышью.
/// </summary>
private int MouseCallBackFunctionFinder(int code, IntPtr wparam, IntPtr LParam)
{
MSLLHOOKSTRUCT mouseInfo = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(LParam, typeof(MSLLHOOKSTRUCT));
System.Windows.Forms.Message msg = new System.Windows.Forms.Message();
msg.Msg = wparam.ToInt32();
if (msg.Msg == WM_LBUTTONDOWN)
{
//Записываем координаты мыши в DWORD
uint MousePt = unchecked((uint)((uint)mouseInfo.pt.Y << 16) | (uint)mouseInfo.pt.X);
System.Drawing.Point pt = new System.Drawing.Point(mouseInfo.pt.X, mouseInfo.pt.Y);
// Находим ближайшее окно
IntPtr hwnd = weFinder.FindWindowAtPos(pt);
ActionHost.TargetWindow = hwnd;
RECT rctWindowRect = new RECT();
GetWindowRect(hwnd, out rctWindowRect);
ActionHost.ptWindowPoint = new Point(rctWindowRect._Left, rctWindowRect._Top);
ActionHost.szTargetBounds.Width = rctWindowRect._Right - rctWindowRect._Left;
ActionHost.szTargetBounds.Height = rctWindowRect._Bottom - rctWindowRect._Top;
}
return CallNextHookEx(IntPtr.Zero, code, wparam, LParam);
}
/// <summary>
/// Callback функция для хука -- прослушивание событий мыши.
/// </summary>
private int MouseCallbackFunctionListener(int code, IntPtr wParam, IntPtr lparam)
{
MSLLHOOKSTRUCT mouseInfo = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lparam, typeof(MSLLHOOKSTRUCT));
// Инициализируем новый итем
ActionLogger.UserAction uaMouse = new ActionLogger.UserAction();
System.Windows.Forms.Message msg = new System.Windows.Forms.Message();
msg.Msg = wParam.ToInt32();
if (msg.Msg == WM_LBUTTONDOWN || msg.Msg == WM_LBUTTONUP)
{
//Записываем координаты мыши в DWORD
uint MousePt = unchecked( (uint)((uint)mouseInfo.pt.Y << 16) | (uint)mouseInfo.pt.X);
System.Drawing.Point pt = new System.Drawing.Point(mouseInfo.pt.X, mouseInfo.pt.Y);
//Рекурсивно находим самое нижнее из всех дочерних окон, в котором находится наша точка
IntPtr OldWnd = weFinder.ParentHandle;
IntPtr OldCWnd = IntPtr.Zero;
IntPtr hwnd = weFinder.FindWindowAtPos(pt);
while (hwnd != IntPtr.Zero)
{
OldCWnd = hwnd;
weFinder.ParentHandle = hwnd;
hwnd = weFinder.FindWindowAtPos(pt);
}
weFinder.ParentHandle = OldWnd;
hwnd = OldCWnd;
if (hwnd != IntPtr.Zero)
{
//Получаем текст окна
int len = SendMessage(hwnd, WM_GETTEXTLENGTH, 0, new StringBuilder()).ToInt32()+1;
StringBuilder strWindowText = new StringBuilder(len);
SendMessage(hwnd, WM_GETTEXT, len , strWindowText);
uaMouse.BriefInfo = strWindowText.ToString() + ":";
// Получаем класс окна
StringBuilder strWindowClass = new StringBuilder(128);
WindowsEnumerator.GetClassName(hwnd,strWindowClass,128);
uaMouse.BriefInfo += strWindowClass.ToString();
//Формирует ординарное сообщение Windows для помещения в хранилище
IntPtr PtrToPt = new IntPtr(MousePt);
msg.LParam = PtrToPt;
msg.WParam = new IntPtr(1);
uaMouse.KeyCode = (mouseInfo.mouseData >> 16);
uaMouse.EventCode = msg;
uaMouse.ThreadId = this.ThreadId;
//Записываем новый итем в модель.
ActionHost.AddItem(uaMouse);
}
}
// Передаем управление следующему хуку, если такой есть в системе.
return CallNextHookEx(IntPtr.Zero, code, wParam, lparam);
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="HandleTo">Дескриптор окна, к которому хотим подключиться</param>
public HookClass(IntPtr HandleTo)
{
weFinder = new WindowsEnumerator();
weFinder.ParentHandle = HandleTo;
if (HandleTo != IntPtr.Zero)
this.ThreadId = GetProcess(HandleTo);
KBCallbackDelegate = KBCallbackFunction;
}
/// <summary>
/// Делегат, который будет обрабатывать перехваченное сообщение из системной очереди,
/// выполняет определение окна
/// </summary>
public void SetPickHook()
{
MouseCallbackDelegate = MouseCallBackFunctionFinder;
}
/// <summary>
/// Делегат, который будет обрабатывать перехваченное сообщение из системной очереди,
/// выполняет прослушивание событий мыши
/// </summary>
public void SetListenHook()
{
MouseCallbackDelegate = MouseCallbackFunctionListener;
}
/// <summary>
/// Метод, устанавливающий системный хук на очередь сообщений Windows. Так как .NET не позволяет создать DLL
/// , которая могла бы расшарить адресное пространство с другим процессом, то ловим общесистемные события.
/// </summary>
/// <param name="install">True - устанавливаем хук, False - снимаем</param>
public void SetHook(bool install)
{
if (install)
{
Process pProcess = Process.GetCurrentProcess();
ProcessModule pmModuleMain = pProcess.MainModule;
IntPtr hModule = GetModuleHandle(pmModuleMain.ModuleName);
// Клавиатурный хук пока отключаем. HHook = SetWindowsHookEx(HookType.WH_KEYBOARD_LL, KBCallbackDelegate, hModule, 0);
HHookM = SetWindowsHookEx(HookType.WH_MOUSE_LL, MouseCallbackDelegate, hModule, 0);
if (/*HHook != IntPtr.Zero &&*/ HHookM != IntPtr.Zero) // Клавиатурный хук пока отключаем.
this._installed = true;
else
{
int errorcode = Marshal.GetLastWin32Error();
System.Windows.Forms.MessageBox.Show("Код ошибки " + errorcode.ToString());
}
}
else
{
// Клавиатурный хук пока отключаем. UnhookWindowsHookEx(HHook);
if (HHookM!=IntPtr.Zero)
UnhookWindowsHookEx(HHookM);
this._installed = false;
}
}
}
}