c++ 写个完整的案例:捕获鼠标键盘在全局桌面的操作,写个鼠标键盘hook
时间: 2024-10-23 15:21:22 浏览: 29
在 C++ 中,创建全局桌面级别的鼠标键盘事件钩子(Hook)功能通常需要依赖底层 WinAPI,因为标准库并不直接支持这类操作。以下是一个简单的示例,展示了如何使用 Windows API 来捕获鼠标和键盘事件。请注意,这个示例需要在有权限访问系统级事件的环境下运行,并且通常用于开发者工具或特定的安全控制应用,而不是一般的应用程序。
```cpp
#include <windows.h>
#include <iostream>
LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam) {
MOUSEHOOKSTRUCT* mouseStruct = (MOUSEHOOKSTRUCT*)lParam;
if (nCode >= 0 && wParam == WM_MOUSEMOVE) {
std::cout << "Mouse moved at (" << mouseStruct->x << ", " << mouseStruct->y << ")" << std::endl;
}
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
RAWINPUT* rawInput = (RAWINPUT*)lParam;
if (nCode >= 0 && wParam == WM_KEYDOWN) {
char keyChar = ToAscii(rawInput->header.key.vKey, NULL, NULL, &wParam, 0);
std::cout << "Key down: " << static_cast<char>(keyChar) << std::endl;
}
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
int main() {
HHOOK mouseHook = SetWindowsHookEx(WH_MOUSE_LL, MouseProc, (HINSTANCE)NULL, GetCurrentThreadId());
if (!mouseHook) {
std::cerr << "Failed to set mouse hook." << std::endl;
return 1;
}
HHOOK keyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardProc, (HINSTANCE)NULL, GetCurrentThreadId());
if (!keyboardHook) {
UnhookWindowsHookEx(mouseHook);
std::cerr << "Failed to set keyboard hook." << std::endl;
return 1;
}
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnhookWindowsHookEx(mouseHook);
UnhookWindowsHookEx(keyboardHook);
return 0;
}
阅读全文