-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathKeyboardHook.cs
73 lines (56 loc) · 2.26 KB
/
KeyboardHook.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
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Ulavali
{
public class KeyboardHook
{
private const int WhKeyboardLl = 13;
private const int WmKeydown = 0x0100;
private readonly LowLevelKeyboardProc _proc = HookCallback;
private static IntPtr _hookId = IntPtr.Zero;
public static event HandelKeyPress OnKeyPress;
public void SetHook()
{
_hookId = SetHook(_proc);
}
public void UnHook()
{
UnhookWindowsHookEx(_hookId);
}
private IntPtr SetHook(LowLevelKeyboardProc proc)
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WhKeyboardLl, proc,
GetModuleHandle(curModule.ModuleName), 0);
}
}
private delegate IntPtr LowLevelKeyboardProc(
int nCode, IntPtr wParam, IntPtr lParam);
private static IntPtr HookCallback(
int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)WmKeydown)
{
int vkCode = Marshal.ReadInt32(lParam);
OnKeyPress(vkCode);
// Console.WriteLine((Keys)vkCode);
}
return CallNextHookEx(_hookId, nCode, wParam, lParam);
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook,
LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
}
public delegate void HandelKeyPress(int keyChar);
}