forked from kurumpa/dotSwitcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KeyboardHook.cs
85 lines (72 loc) · 2.54 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
74
75
76
77
78
79
80
81
82
83
84
85
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
namespace dotSwitcher
{
public class KeyboardHook
{
public event EventHandler<KeyboardEventArgs> KeyboardEvent;
private HookProc callback;
private IntPtr hookId = IntPtr.Zero;
public KeyboardHook()
{
callback = ProcessKeyPress;
}
public bool IsStarted()
{
return hookId != IntPtr.Zero;
}
public void Start()
{
if (IsStarted()) { return; }
hookId = LowLevelAdapter.SetHook(LowLevelAdapter.WH_KEYBOARD_LL, callback);
}
public void Stop()
{
if (!IsStarted()) { return; }
LowLevelAdapter.ReleaseHook(hookId);
hookId = IntPtr.Zero;
}
private void OnKeyboardEvent(KeyboardEventArgs e)
{
if (KeyboardEvent != null)
{
KeyboardEvent(this, e);
}
}
private IntPtr ProcessKeyPress(int nCode, IntPtr wParam, IntPtr lParam)
{
return ProcessKeyPressInt(nCode, wParam, lParam) ?
new IntPtr(1) :
LowLevelAdapter.NextHook(nCode, wParam, lParam);
}
// returns true if event is handled
private bool ProcessKeyPressInt(int nCode, IntPtr wParam, IntPtr lParam)
{
try
{
if (nCode < 0)
return false;
switch (wParam.ToInt32())
{
case LowLevelAdapter.WM_KEYDOWN:
case LowLevelAdapter.WM_SYSKEYDOWN:
var keybdinput = (KEYBDINPUT)Marshal.PtrToStructure(lParam, typeof(KEYBDINPUT));
var keyData = (Keys)keybdinput.Vk;
keyData |= LowLevelAdapter.KeyPressed(Keys.ControlKey) ? Keys.Control : 0;
keyData |= LowLevelAdapter.KeyPressed(Keys.Menu) ? Keys.Alt : 0;
keyData |= LowLevelAdapter.KeyPressed(Keys.ShiftKey) ? Keys.Shift : 0;
var winPressed = LowLevelAdapter.KeyPressed(Keys.LWin) || LowLevelAdapter.KeyPressed(Keys.RWin);
var args = new KeyboardEventArgs(keyData, winPressed);
OnKeyboardEvent(args);
return args.Handled;
}
}
catch { }
return false;
}
}
}