#include<Windows.h>
#include<iostream>
std::string get_time()
{
SYSTEMTIME sys;
GetLocalTime(&sys);
char time[1024] = { 0 };
sprintf_s(time, "[%4d/%02d/%02d %02d:%02d:%02d]", sys.wYear, sys.wMonth, sys.wDay, sys.wHour, sys.wMinute, sys.wSecond);
return std::string(time);
}
LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
KBDLLHOOKSTRUCT* ks = (KBDLLHOOKSTRUCT*)lParam;
char data[1024];
DWORD code = ks->vkCode;
std::string t = get_time();
char state[20];
if (wParam == WM_KEYDOWN)
{
strcpy_s(state, "按下");
}
else if (wParam == WM_KEYUP)
{
strcpy_s(state, "放开");
}
sprintf_s(data, "%s 键代码:%d %s", t.c_str(), code, state);
std::cout << data << std::endl;
return 1;
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
int main()
{
HINSTANCE hInst = GetModuleHandle(NULL);
HHOOK g_Hook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardProc, hInst, 0);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnhookWindowsHookEx(g_Hook);
return 0;
}
|