// 非常完美 显示和写入都有 时间也都正确
#include <iostream>
#include <fstream>
#include <windows.h>
// 钩子回调函数
LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
KBDLLHOOKSTRUCT* pKeyboardStruct = reinterpret_cast<KBDLLHOOKSTRUCT*>(lParam);
static bool isPressed[256] = { false }; // 用于跟踪按键是否被按下
static ULONGLONG lastPressTime[256] = { 0 }; // 上一次按键按下的时间戳
std::ofstream outputFile("keyboard_log.txt", std::ios_base::app); // 打开文件以追加模式
//std::ofstream outputFile("keyboard_log.txt", std::ios_base::out | std::ios_base::trunc); // 打开文件并清空内容
if (nCode == HC_ACTION) {
switch (wParam) {
case WM_KEYDOWN:
if (!isPressed[pKeyboardStruct->vkCode]) {
isPressed[pKeyboardStruct->vkCode] = true;
lastPressTime[pKeyboardStruct->vkCode] = GetTickCount64(); // 记录按键按下的时间戳
std::cout << lastPressTime[pKeyboardStruct->vkCode] <<" " << (char)pKeyboardStruct->vkCode << " 按下" << std::endl;
outputFile << lastPressTime[pKeyboardStruct->vkCode] << " " << (char)pKeyboardStruct->vkCode << " 按下" << std::endl;
}
break;
case WM_KEYUP:
if (isPressed[pKeyboardStruct->vkCode]) {
isPressed[pKeyboardStruct->vkCode] = false;
ULONGLONG ls = GetTickCount64(); // 记录按键按下的时间戳
ULONGLONG pressDuration = ls - lastPressTime[pKeyboardStruct->vkCode];
std::cout << ls<<" "<<(char)pKeyboardStruct->vkCode << " 弹起 " << pressDuration << "ms" << std::endl;
outputFile << ls << " " << (char)pKeyboardStruct->vkCode << " 弹起 " << pressDuration << "ms" << std::endl;
outputFile.close(); // 关闭文件
}
break;
}
}
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
int main() {
// 在程序开始时清空文件内容
std::ofstream outputFile("keyboard_log.txt", std::ios_base::out | std::ios_base::trunc);
if (!outputFile.is_open()) {
std::cerr << "Failed to open the file for clearing!" << std::endl;
return 1;
}
outputFile.close(); // 关闭文件,确保内容被清空
HHOOK hHook = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, GetModuleHandle(NULL), 0);
if (hHook == NULL) {
std::cerr << "Failed to set hook!" << std::endl;
return 1;
}
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnhookWindowsHookEx(hHook);
return 0;
}```
按键录制+文件写入
最新推荐文章于 2024-08-31 22:41:09 发布