-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHooker.cs
696 lines (615 loc) · 30.6 KB
/
Hooker.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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Diagnostics;
using System.Drawing;
using System.Reflection;
using System.ComponentModel;
namespace KeyReplace
{
public class Hooker
{
#region P/Invoke Structures
/// <summary>
/// The MSLLHOOKSTRUCT structure contains information about a low-level keyboard input event.
/// https://www.codeproject.com/script/Articles/ViewDownloads.aspx?aid=7294&zep=GlobalHook%2fGma.UserActivityMonitor%2fHookManager.Structures.cs&rzp=%2fKB%2fcs%2fglobalhook%2f%2fglobalhook2_src.zip
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct MouseLLHookStruct
{
/// <summary>
/// Specifies a Point structure that contains the X- and Y-coordinates of the cursor, in screen coordinates.
/// </summary>
public Point Point;
/// <summary>
/// If the message is WM_MOUSEWHEEL, the high-order word of this member is the wheel delta.
/// The low-order word is reserved. A positive value indicates that the wheel was rotated forward,
/// away from the user; a negative value indicates that the wheel was rotated backward, toward the user.
/// One wheel click is defined as WHEEL_DELTA, which is 120.
///If the message is WM_XBUTTONDOWN, WM_XBUTTONUP, WM_XBUTTONDBLCLK, WM_NCXBUTTONDOWN, WM_NCXBUTTONUP,
/// or WM_NCXBUTTONDBLCLK, the high-order word specifies which X button was pressed or released,
/// and the low-order word is reserved. This value can be one or more of the following values. Otherwise, MouseData is not used.
///XBUTTON1
///The first X button was pressed or released.
///XBUTTON2
///The second X button was pressed or released.
/// </summary>
public int MouseData;
/// <summary>
/// Specifies the event-injected flag. An application can use the following value to test the mouse Flags. Value Purpose
///LLMHF_INJECTED Test the event-injected flag.
///0
///Specifies whether the event was injected. The value is 1 if the event was injected; otherwise, it is 0.
///1-15
///Reserved.
/// </summary>
public int Flags;
/// <summary>
/// Specifies the Time stamp for this message.
/// </summary>
public int Time;
/// <summary>
/// Specifies extra information associated with the message.
/// </summary>
public int ExtraInfo;
public bool IsInjected
{ get { return (Flags & (int)MouseEventFlags.LLMHF_INJECTED) > 0; } }
public bool IsLowerInjected
{ get { return (Flags & (int)MouseEventFlags.LLMHF_LOWER_IL_INJECTED) > 0; } }
public bool IsXButton1
{
get { return (MouseData >> 16) == XBUTTON1; }
}
public int WheelDelta
{
get { return (MouseData >> 16); }
}
const int XBUTTON1 = 0x001;
const int XBUTTON2 = 0x002;
}
/// <summary>
/// The KBDLLHOOKSTRUCT structure contains information about a low-level keyboard input event.
/// </summary>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookstructures/cwpstruct.asp
/// </remarks>
[StructLayout(LayoutKind.Sequential)]
public struct KeyboardHookStruct
{
/// <summary>
/// Specifies a virtual-key code. The code must be a value in the range 1 to 254.
/// </summary>
public int VirtualKeyCode;
/// <summary>
/// Specifies a hardware scan code for the key.
/// </summary>
public int ScanCode;
/// <summary>
/// Specifies the extended-key flag, event-injected flag, context code, and transition-state flag.
/// </summary>
public int Flags;
/// <summary>
/// Specifies the Time stamp for this message.
/// </summary>
public int Time;
/// <summary>
/// Specifies extra information associated with the message.
/// </summary>
public int ExtraInfo;
public bool IsExtendedKey
{
get { return (Flags & (int)KeyboardEventFlags.LLKHF_EXTENDED) > 0; }
}
public bool IsLowerInjected
{
get { return (Flags & (int)KeyboardEventFlags.LLKHF_LOWER_IL_INJECTED) > 0; }
}
public bool IsInjected
{
get { return (Flags & (int)KeyboardEventFlags.LLKHF_INJECTED) > 0; }
set
{
/* //DEBUG - experimental feature!
if(value == true)
{
Flags |= (int)KeyboardEventFlags.LLKHF_INJECTED;
Flags |= (int)KeyboardEventFlags.LLKHF_LOWER_IL_INJECTED;
}else
{
Flags &= ~((int)KeyboardEventFlags.LLKHF_INJECTED);
Flags &= ~((int)KeyboardEventFlags.LLKHF_LOWER_IL_INJECTED);
}*/
}
}
public bool IsAltDown
{
get { return (Flags & (int)KeyboardEventFlags.LLKHF_ALTDOWN) > 0; }
}
public bool IsKeyUp
{
get { return (Flags & (int)KeyboardEventFlags.LLKHF_UP) > 0; }
}
}
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[StructLayout(LayoutKind.Sequential)]
private struct POINT
{
public int x;
public int y;
}
[StructLayout(LayoutKind.Sequential)]
private struct MSLLHOOKSTRUCT
{
public POINT pt;
public uint mouseData;
public uint flags;
public uint time;
public IntPtr dwExtraInfo;
}
#endregion
#region P/Invoke Constants
public enum KeyboardEventFlags : int
{
LLKHF_EXTENDED = 1,
LLKHF_LOWER_IL_INJECTED = 2,
//... reserved bits are 2-3
LLKHF_INJECTED = 16,
LLKHF_ALTDOWN = 32,
//... reserved bit 6
LLKHF_UP = 128
}
public enum MouseEventFlags : int
{
LLMHF_INJECTED = 1,
LLMHF_LOWER_IL_INJECTED = 2,
}
private const int WM_CHAR = 0x0102;
//values from Winuser.h in Microsoft SDK.
/// <summary>
/// Windows NT/2000/XP: Installs a hook procedure that monitors low-level mouse input events.
/// </summary>
private const int WH_MOUSE_LL = 14;
/// <summary>
/// Windows NT/2000/XP: Installs a hook procedure that monitors low-level keyboard input events.
/// </summary>
private const int WH_KEYBOARD_LL = 13;
/// <summary>
/// Installs a hook procedure that monitors mouse messages. For more information, see the MouseProc hook procedure.
/// </summary>
private const int WH_MOUSE = 7;
/// <summary>
/// Installs a hook procedure that monitors keystroke messages. For more information, see the KeyboardProc hook procedure.
/// </summary>
private const int WH_KEYBOARD = 2;
/// <summary>
/// The WM_MOUSEMOVE message is posted to a window when the cursor moves.
/// </summary>
private const int WM_MOUSEMOVE = 0x200;
/// <summary>
/// The WM_LBUTTONDOWN message is posted when the user presses the left mouse button
/// </summary>
private const int WM_LBUTTONDOWN = 0x201;
private const int WM_XBUTTONDOWN = 0x20B;
private const int WM_XBUTTONUP = 0x20C;
/// <summary>
/// The WM_RBUTTONDOWN message is posted when the user presses the right mouse button
/// </summary>
private const int WM_RBUTTONDOWN = 0x204;
/// <summary>
/// The WM_MBUTTONDOWN message is posted when the user presses the middle mouse button
/// </summary>
private const int WM_MBUTTONDOWN = 0x207;
/// <summary>
/// The WM_LBUTTONUP message is posted when the user releases the left mouse button
/// </summary>
private const int WM_LBUTTONUP = 0x202;
/// <summary>
/// The WM_RBUTTONUP message is posted when the user releases the right mouse button
/// </summary>
private const int WM_RBUTTONUP = 0x205;
/// <summary>
/// The WM_MBUTTONUP message is posted when the user releases the middle mouse button
/// </summary>
private const int WM_MBUTTONUP = 0x208;
/// <summary>
/// The WM_LBUTTONDBLCLK message is posted when the user double-clicks the left mouse button
/// </summary>
private const int WM_LBUTTONDBLCLK = 0x203;
/// <summary>
/// The WM_RBUTTONDBLCLK message is posted when the user double-clicks the right mouse button
/// </summary>
private const int WM_RBUTTONDBLCLK = 0x206;
/// <summary>
/// The WM_RBUTTONDOWN message is posted when the user presses the right mouse button
/// </summary>
private const int WM_MBUTTONDBLCLK = 0x209;
/// <summary>
/// The WM_MOUSEWHEEL message is posted when the user presses the mouse wheel.
/// </summary>
private const int WM_MOUSEWHEEL = 0x020A;
/// <summary>
/// The WM_KEYDOWN message is posted to the window with the keyboard focus when a nonsystem
/// key is pressed. A nonsystem key is a key that is pressed when the ALT key is not pressed.
/// </summary>
private const int WM_KEYDOWN = 0x100;
/// <summary>
/// The WM_KEYUP message is posted to the window with the keyboard focus when a nonsystem
/// key is released. A nonsystem key is a key that is pressed when the ALT key is not pressed,
/// or a keyboard key that is pressed when a window has the keyboard focus.
/// </summary>
private const int WM_KEYUP = 0x101;
/// <summary>
/// The WM_SYSKEYDOWN message is posted to the window with the keyboard focus when the user
/// presses the F10 key (which activates the menu bar) or holds down the ALT key and then
/// presses another key. It also occurs when no window currently has the keyboard focus;
/// in this case, the WM_SYSKEYDOWN message is sent to the active window. The window that
/// receives the message can distinguish between these two contexts by checking the context
/// code in the lParam parameter.
/// </summary>
private const int WM_SYSKEYDOWN = 0x104;
/// <summary>
/// The WM_SYSKEYUP message is posted to the window with the keyboard focus when the user
/// releases a key that was pressed while the ALT key was held down. It also occurs when no
/// window currently has the keyboard focus; in this case, the WM_SYSKEYUP message is sent
/// to the active window. The window that receives the message can distinguish between
/// these two contexts by checking the context code in the lParam parameter.
/// </summary>
private const int WM_SYSKEYUP = 0x105;
private const byte VK_SHIFT = 0x10;
private const byte VK_CAPITAL = 0x14;
private const byte VK_NUMLOCK = 0x90;
#endregion
#region P/Invoke Function Imports
/// <summary>
/// The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain.
/// You would install a hook procedure to monitor the system for certain types of events. These events
/// are associated either with a specific thread or with all threads in the same desktop as the calling thread.
/// </summary>
/// <param name="idHook">
/// [in] Specifies the type of hook procedure to be installed. This parameter can be one of the following values.
/// </param>
/// <param name="lpfn">
/// [in] Pointer to the hook procedure. If the dwThreadId parameter is zero or specifies the identifier of a
/// thread created by a different process, the lpfn parameter must point to a hook procedure in a dynamic-link
/// library (DLL). Otherwise, lpfn can point to a hook procedure in the code associated with the current process.
/// </param>
/// <param name="hMod">
/// [in] Handle to the DLL containing the hook procedure pointed to by the lpfn parameter.
/// The hMod parameter must be set to NULL if the dwThreadId parameter specifies a thread created by
/// the current process and if the hook procedure is within the code associated with the current process.
/// </param>
/// <param name="dwThreadId">
/// [in] Specifies the identifier of the thread with which the hook procedure is to be associated.
/// If this parameter is zero, the hook procedure is associated with all existing threads running in the
/// same desktop as the calling thread.
/// </param>
/// <returns>
/// If the function succeeds, the return value is the handle to the hook procedure.
/// If the function fails, the return value is NULL. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp
/// </remarks>
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern int SetWindowsHookEx(
int idHook,
HookProc lpfn,
IntPtr hMod,
int dwThreadId);
/// <summary>
/// The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.
/// </summary>
/// <param name="idHook">
/// [in] Handle to the hook to be removed. This parameter is a hook handle obtained by a previous call to SetWindowsHookEx.
/// </param>
/// <returns>
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp
/// </remarks>
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern int UnhookWindowsHookEx(int idHook);
/// <summary>
/// The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain.
/// A hook procedure can call this function either before or after processing the hook information.
/// </summary>
/// <param name="idHook">Ignored.</param>
/// <param name="nCode">
/// [in] Specifies the hook code passed to the current hook procedure.
/// The next hook procedure uses this code to determine how to process the hook information.
/// </param>
/// <param name="wParam">
/// [in] Specifies the wParam value passed to the current hook procedure.
/// The meaning of this parameter depends on the type of hook associated with the current hook chain.
/// </param>
/// <param name="lParam">
/// [in] Specifies the lParam value passed to the current hook procedure.
/// The meaning of this parameter depends on the type of hook associated with the current hook chain.
/// </param>
/// <returns>
/// This value is returned by the next hook procedure in the chain.
/// The current hook procedure must also return this value. The meaning of the return value depends on the hook type.
/// For more information, see the descriptions of the individual hook procedures.
/// </returns>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp
/// </remarks>
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
private static extern int CallNextHookEx(
int idHook,
int nCode,
int wParam,
IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern ushort GetAsyncKeyState(int vKey);
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
public static extern short GetKeyState(int keyCode);
[DllImport("user32.dll", SetLastError = true)]
static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll")]
public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, out uint ProcessId);
#endregion
#region P/Invoke Helper Functions
public static bool IsKeyPushedDown(Keys vKey)
{
return 0 != (GetAsyncKeyState((int)vKey) & 0x8000);
}
IntPtr GetActiveWindowHandle()
{
try
{
IntPtr hwnd = GetForegroundWindow();
uint pid;
GetWindowThreadProcessId(hwnd, out pid);
Process p = Process.GetProcessById((int)pid);
return p.MainWindowHandle;
}
catch (Exception)
{
return IntPtr.Zero;
}
}
#endregion
#region P/Invoke Callbacks
private delegate int HookProc(int nCode, int wParam, IntPtr lParam);
/// <summary>
/// Return TRUE if you are gonna continue. Return FALSE to block the input. Same goes for s_KeyUp.
/// </summary>
public static event Func<KeyboardHookStruct, bool> s_KeyDown;
public static event Func<KeyboardHookStruct, bool> s_KeyUp;
public static event Func<MouseButtons, MouseLLHookStruct, bool> s_MouseDown;
public static event Func<MouseButtons,MouseLLHookStruct, bool> s_MouseUp;
private static HookProc s_MouseDelegate;
private static HookProc s_KeyboardDelegate;
private static int s_MouseHookHandle=0;
private static int s_KeyboardHookHandle=0;
/// <summary>
/// A callback function which will be called every Time a keyboard activity detected.
/// </summary>
/// <param name="nCode">
/// [in] Specifies whether the hook procedure must process the message.
/// If nCode is HC_ACTION, the hook procedure must process the message.
/// If nCode is less than zero, the hook procedure must pass the message to the
/// CallNextHookEx function without further processing and must return the
/// value returned by CallNextHookEx.
/// </param>
/// <param name="wParam">
/// [in] Specifies whether the message was sent by the current thread.
/// If the message was sent by the current thread, it is nonzero; otherwise, it is zero.
/// </param>
/// <param name="lParam">
/// [in] Pointer to a CWPSTRUCT structure that contains details about the message.
/// </param>
/// <returns>
/// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx.
/// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx
/// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC
/// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook
/// procedure does not call CallNextHookEx, the return value should be zero.
/// </returns>
private static int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
if (nCode >= 0)
{
//read structure KeyboardHookStruct at lParam
KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
// raise KeyDown
if (s_KeyDown != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN))
{
if (!s_KeyDown.Invoke(MyKeyboardHookStruct))
return 1;
}
// raise KeyUp
else if (s_KeyUp != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP))
{
if (!s_KeyUp.Invoke(MyKeyboardHookStruct))
return 1;
}
/* //DEBUG - experimental feature!
MyKeyboardHookStruct.IsInjected = false;
Marshal.StructureToPtr(MyKeyboardHookStruct, lParam, false);*/
}
//forward to other application
return CallNextHookEx(s_KeyboardHookHandle, nCode, wParam, lParam);
}
/// <summary>
/// A callback function which will be called every Time a mouse activity detected.
/// </summary>
/// <param name="nCode">
/// [in] Specifies whether the hook procedure must process the message.
/// If nCode is HC_ACTION, the hook procedure must process the message.
/// If nCode is less than zero, the hook procedure must pass the message to the
/// CallNextHookEx function without further processing and must return the
/// value returned by CallNextHookEx.
/// </param>
/// <param name="wParam">
/// [in] Specifies whether the message was sent by the current thread.
/// If the message was sent by the current thread, it is nonzero; otherwise, it is zero.
/// </param>
/// <param name="lParam">
/// [in] Pointer to a CWPSTRUCT structure that contains details about the message.
/// </param>
/// <returns>
/// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx.
/// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx
/// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC
/// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook
/// procedure does not call CallNextHookEx, the return value should be zero.
/// </returns>
private static int MouseHookProc(int nCode, int wParam, IntPtr lParam)
{
if (nCode >= 0)
{
//Marshall the data from callback.
MouseLLHookStruct mouseHookStruct = (MouseLLHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseLLHookStruct));
bool passInput = true;
if (s_MouseDown != null)
{
if (wParam == WM_LBUTTONDOWN)
passInput = s_MouseDown(MouseButtons.Left, mouseHookStruct);
else if (wParam == WM_RBUTTONDOWN)
passInput = s_MouseDown(MouseButtons.Right, mouseHookStruct);
else if (wParam == WM_MBUTTONDOWN)
passInput = s_MouseDown(MouseButtons.Middle, mouseHookStruct);
else if (wParam == WM_XBUTTONDOWN)
{
passInput = s_MouseDown(mouseHookStruct.IsXButton1 ? MouseButtons.XButton1 : MouseButtons.XButton2,
mouseHookStruct);
}
}
if (s_MouseUp != null)
{
if (wParam == WM_LBUTTONUP)
passInput = s_MouseUp(MouseButtons.Left, mouseHookStruct);
else if (wParam == WM_RBUTTONUP)
passInput = s_MouseUp(MouseButtons.Right, mouseHookStruct);
else if (wParam == WM_MBUTTONUP)
passInput = s_MouseUp(MouseButtons.Middle, mouseHookStruct);
else if (wParam == WM_XBUTTONUP)
{
passInput = s_MouseUp(mouseHookStruct.IsXButton1 ? MouseButtons.XButton1 : MouseButtons.XButton2,
mouseHookStruct);
}
}
if (!passInput) return 1;
}
return CallNextHookEx(s_MouseHookHandle, nCode, wParam, lParam);
}
public static void HookMouse()
{
// install Mouse hook only if it is not installed and must be installed
if (s_MouseHookHandle == 0)
{
//See comment of this field. To avoid GC to clean it up.
s_MouseDelegate = MouseHookProc;
//install hook
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
s_MouseHookHandle = SetWindowsHookEx(
WH_MOUSE_LL,
s_MouseDelegate,
GetModuleHandle(curModule.ModuleName),
0);
}
//If SetWindowsHookEx fails.
if (s_MouseHookHandle == 0)
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
int errorCode = Marshal.GetLastWin32Error();
//do cleanup
//Initializes and throws a new instance of the Win32Exception class with the specified error.
throw new Win32Exception(errorCode);
}
}
}
public static void HookKeyboard()
{
if (s_KeyboardHookHandle == 0)
{
//See comment of this field. To avoid GC to clean it up.
s_KeyboardDelegate = KeyboardHookProc;
//install hook
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
s_KeyboardHookHandle = SetWindowsHookEx(
WH_KEYBOARD_LL,
s_KeyboardDelegate,
GetModuleHandle(curModule.ModuleName),
0);
}
//If SetWindowsHookEx fails.
if (s_KeyboardHookHandle == 0)
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
int errorCode = Marshal.GetLastWin32Error();
//do cleanup
//Initializes and throws a new instance of the Win32Exception class with the specified error.
throw new Win32Exception(errorCode);
}
}
}
public static void UnhookKeyboard()
{
if (s_KeyboardHookHandle != 0)
{
//uninstall hook
int result = UnhookWindowsHookEx(s_KeyboardHookHandle);
//reset invalid handle
s_KeyboardHookHandle = 0;
//Free up for GC
s_KeyboardDelegate = null;
//if failed and exception must be thrown
if (result == 0)
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
int errorCode = Marshal.GetLastWin32Error();
//Initializes and throws a new instance of the Win32Exception class with the specified error.
throw new Win32Exception(errorCode);
}
}
}
public static void UnhookMouse()
{
if (s_MouseHookHandle != 0)
{
//uninstall hook
int result = UnhookWindowsHookEx(s_MouseHookHandle);
//reset invalid handle
s_MouseHookHandle = 0;
//Free up for GC
s_MouseDelegate = null;
//if failed and exception must be thrown
if (result == 0)
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
int errorCode = Marshal.GetLastWin32Error();
//Initializes and throws a new instance of the Win32Exception class with the specified error.
throw new Win32Exception(errorCode);
}
}
}
#endregion
}
}