最近发现个有趣的问题,我们如何向一个窗口发送 按键指令?
嗯,我稍微总结了下,大概有如下几种:
1:System.Windows.Forms.SendKeys. Send / SendWait
示例:
SendKeys.SendWait("^{A}"); // 模拟键:CTRL + A
组合键:
Ctrl = ^
Shift = +
Alt = %
2:keybd_event
声明:
[System.Runtime.InteropServices.DllImportAttribute("user32.dll", EntryPoint="keybd_event")]
public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo) ;
示列:
keybd_event (VK_CONTROL, 0, 0, 0);
keybd_event (VK_A, 0, 0, 0);
keybd_event (VK_A, 0, #KEYEVENTF_KEYUP, 0);
keybd_event (VK_CONTROL, 0, KEYEVENTF_KEYUP, 0); // 模拟键:CTRL + A
看了两大两种,但又没有对单一窗口,即使不是活动窗口也能投递按键消息呢?
答案肯定是有的,我稍微整合了一点,如下写到
声明:
[System.Runtime.InteropServices.DllImportAttribute("user32.dll", EntryPoint = "PostMessageA")]
static extern int PostMessageA(IntPtr hWnd, int Msg, int wParam, int lParam);
1:向 TextBox 发送单一按键,这个比较简单我们直接这样写就可以了
PostMessageA(textBox1.Handle, WM_CHAR, VK_A, 1);
详解:
1:目标编辑框
2:按下某键,并已发出WM_KEYDOWN, WM_KEYUP消息
3:VK_A = (int)Keys.A = ASCII(065)
4:发送字符数量,0和1 一样只发送一次
2:向(任意窗口)投递 CTRL + A 组合键
案例:
keybd_event (VK_CONTROL, 0, 0, 0);
PostMessage (hWnd, #WM_KEYDOWN, #VK_A, 0);
keybd_event (VK_CONTROL, 0, KEYEVENTF_KEYUP, 0);
// 不过也不是好完美了那,谁让本吊丝没把PostMessageA怎么投递组合键弄透呢?
VK_A = 65 // Keys.A
WM_CHAR = 258
WM_KEYUP = 257
WM_KEYDOWN = 256
VK_CONTROL = 17
KEYEVENTF_KEYUP = 2
VK_SHIFT = 16
VK_MENU = 18 // Alt