用到win32 api:
1、SetWindowsHookEx设置挂钩,记录按键消息
2、keybd_event模拟按键操作
使用:运行程序后,按F9开始记录,再按F9停止记录并回放操作
#include <windows.h>
#include <iostream>
#include <vector>
HHOOK g_hHook;
struct KeyMsgInfo {
WPARAM wParam;
DWORD vkCode;
};
std::vector<KeyMsgInfo> oMsgList;
bool bRecording = false;
void PressKey(WORD key, DWORD time = 50)
{
keybd_event(key, 0, 0, 0);
Sleep(time);
keybd_event(key, 0, KEYEVENTF_KEYUP, 0);
}
LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
if (nCode >= 0 && wParam == WM_KEYDOWN)
{
KBDLLHOOKSTRUCT* pkbhs = (KBDLLHOOKSTRUCT*)lParam;
if (bRecording)
oMsgList.push_back({ wParam, pkbhs->vkCode });
if (pkbhs->vkCode == VK_F9)
{
bRecording = !bRecording;
if (bRecording)
{
oMsgList.clear();
std::cout << "开始记录……" << std::endl;
}
else
{
std::cout << "开始回放……" << std::endl;
for (auto& item : oMsgList)
{
PressKey(item.vkCode);
}
}
}
if (pkbhs->vkCode == VK_F11)
{
PostQuitMessage(0);
}
}
return CallNextHookEx(g_hHook, nCode, wParam, lParam);
}
int main()
{
HINSTANCE hInstance = GetModuleHandle(NULL);
g_hHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardProc, hInstance, 0);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnhookWindowsHookEx(g_hHook);
return 0;
}