-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeystrokeSender.cs
More file actions
103 lines (90 loc) · 3.04 KB
/
Copy pathKeystrokeSender.cs
File metadata and controls
103 lines (90 loc) · 3.04 KB
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
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
namespace KeystrokePaster
{
public class KeystrokeSender
{
[DllImport("user32.dll")]
private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
[DllImport("user32.dll")]
private static extern short VkKeyScan(char ch);
[DllImport("user32.dll")]
private static extern uint MapVirtualKey(uint uCode, uint uMapType);
private const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
private const uint KEYEVENTF_KEYUP = 0x0002;
private const uint KEYEVENTF_UNICODE = 0x0004;
private const uint KEYEVENTF_SCANCODE = 0x0008;
public void SendText(string text, int delayMs)
{
foreach (char c in text)
{
SendChar(c);
if (delayMs > 0)
Thread.Sleep(delayMs);
}
}
private void SendChar(char c)
{
// Handle special characters that need specific key codes
if (c == '\r' || c == '\n')
{
if (c == '\r')
{
// Send Enter key
SendKeyPress((byte)Keys.Return);
}
return;
}
else if (c == '\t')
{
// Send Tab key
SendKeyPress((byte)Keys.Tab);
return;
}
// For regular characters, use VkKeyScan to get the virtual key code
short vkKeyScan = VkKeyScan(c);
if (vkKeyScan == -1)
{
// Character not in keyboard layout, use Unicode method
SendUnicodeChar(c);
}
else
{
byte vk = (byte)(vkKeyScan & 0xFF);
byte shiftState = (byte)(vkKeyScan >> 8);
// Press shift if needed
if ((shiftState & 1) != 0)
{
keybd_event((byte)Keys.ShiftKey, 0, 0, UIntPtr.Zero);
Thread.Sleep(10);
}
// Press and release the key
SendKeyPress(vk);
// Release shift if it was pressed
if ((shiftState & 1) != 0)
{
Thread.Sleep(10);
keybd_event((byte)Keys.ShiftKey, 0, KEYEVENTF_KEYUP, UIntPtr.Zero);
}
}
}
private void SendUnicodeChar(char c)
{
// Send key down
keybd_event(0, (byte)c, KEYEVENTF_UNICODE, UIntPtr.Zero);
Thread.Sleep(10);
// Send key up
keybd_event(0, (byte)c, KEYEVENTF_UNICODE | KEYEVENTF_KEYUP, UIntPtr.Zero);
}
private void SendKeyPress(byte vk)
{
// Key down
keybd_event(vk, 0, 0, UIntPtr.Zero);
Thread.Sleep(10);
// Key up
keybd_event(vk, 0, KEYEVENTF_KEYUP, UIntPtr.Zero);
}
}
}