1.选择目标窗口 获取窗口句柄
void KeyPresser::selectWindow() {SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, NULL, WinEventProc, 0, 0, WINEVENT_OUTOFCONTEXT);selectedWindowLabel->setText("请点击目标窗口...");
}void CALLBACK KeyPresser::WinEventProc(HWINEVENTHOOK hWinEventHook, DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime) {if (event == EVENT_SYSTEM_FOREGROUND) {wchar_t windowTitle[256];GetWindowText(hwnd, windowTitle, 256);if (KeyPresser::instance) {KeyPresser::instance->targetHwnd = hwnd;KeyPresser::instance->selectedWindowLabel->setText(QString::fromWCharArray(windowTitle));UnhookWinEvent(hWinEventHook);}}
}
2. 向目标窗口发送按键消息
void KeyPresser::pressKeys(int index) {if (targetHwnd) {int key = keyCombos[index]->currentData().toInt();DWORD dwVKFkeyData; // lParam 参数值WORD dwScanCode = MapVirtualKey(key, MAPVK_VK_TO_VSC); // 获取虚拟按键的键盘扫描码dwVKFkeyData = 1;dwVKFkeyData |= dwScanCode << 16;dwVKFkeyData |= 0 << 24;dwVKFkeyData |= 1 << 29;PostMessage(targetHwnd, WM_KEYDOWN, key, dwVKFkeyData);// 重置 dwVKFkeyData 以确保 WM_KEYUP 消息正确dwVKFkeyData = 1;dwVKFkeyData |= dwScanCode << 16;dwVKFkeyData |= 0 << 24;dwVKFkeyData |= 1 << 29;dwVKFkeyData |= 3 << 30;PostMessage(targetHwnd, WM_KEYUP, key, dwVKFkeyData);}
}
3. 成品展示
简介
- KeyPresser 是一款免费的自动化按键工具,它可以与窗口交互,并支持后台运行, 无需保持被控窗口在前台运行。用户可以选择要操作的目标窗口,并通过勾选复选框来控制要发送哪些按键消息。可以从组合框中选择所需的按键,并在编辑框中输入时间间隔以控制按键发送之间的延迟。程序提供“开始”和“停止”按钮来启动和终止按键发送过程。
成品下载
- https://www.progdomain.com/627/
- csdn渠道下载 https://download.csdn.net/download/wang161019/89927497
完整源代码下载
https://github.com/wang161113/KeyPresser