-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathSendKeys.cs
executable file
·113 lines (99 loc) · 3.16 KB
/
SendKeys.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace NintendoSpy
{
// Keycodes: http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
// Letter keys map to 0x41.. etc. (i.e. capital ASCII letters)
public class SendKeys
{
const int INPUT_MOUSE = 0;
const int INPUT_KEYBOARD = 1;
const int INPUT_HARDWARE = 2;
const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
const uint KEYEVENTF_KEYUP = 0x0002;
const uint KEYEVENTF_UNICODE = 0x0004;
const uint KEYEVENTF_SCANCODE = 0x0008;
struct INPUT
{
public int type;
public InputUnion u;
}
[StructLayout(LayoutKind.Explicit)]
struct InputUnion
{
[FieldOffset(0)]
public MOUSEINPUT mi;
[FieldOffset(0)]
public KEYBDINPUT ki;
[FieldOffset(0)]
public HARDWAREINPUT hi;
}
[StructLayout(LayoutKind.Sequential)]
struct MOUSEINPUT
{
public int dx;
public int dy;
public uint mouseData;
public uint dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
struct KEYBDINPUT
{
public ushort wVk;
public ushort wScan;
public uint dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
struct HARDWAREINPUT
{
public uint uMsg;
public ushort wParamL;
public ushort wParamH;
}
[DllImport("user32.dll")]
static extern IntPtr GetMessageExtraInfo();
[DllImport("user32.dll", SetLastError = true)]
static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);
static INPUT inputForKey (ushort key, bool releasing)
{
return new INPUT {
type = INPUT_KEYBOARD,
u = new InputUnion {
ki = new KEYBDINPUT {
wVk = key,
wScan = 0,
dwFlags = releasing ? KEYEVENTF_KEYUP : 0,
dwExtraInfo = GetMessageExtraInfo(),
}
}
};
}
static void sendInputs (params INPUT[] inputs)
{
SendInput ((uint)inputs.Length, inputs, Marshal.SizeOf(typeof(INPUT)));
}
static public void PressKey (ushort key)
{
sendInputs (inputForKey (key, false));
}
static public void ReleaseKey(ushort key)
{
sendInputs (inputForKey (key, true));
}
static public void PressAndReleaseKey (ushort key)
{
sendInputs (
inputForKey (key, false),
inputForKey (key, true)
);
}
}
}