创建一个安全的C++鼠标钩子程序需要使用低级别的API函数
#include <iostream>
#include <windows.h>
// 定义一个全局变量来存储鼠标钩子的句柄
HHOOK g_hMouseHook = NULL;
// 鼠标钩子回调函数
LRESULT CALLBACK MouseHookProc(int nCode, WPARAM wParam, LPARAM lParam) {
if (nCode >= 0) {
switch (wParam) {
case WM_MOUSEMOVE:
std::cout << "Mouse moved to (" << LOWORD(lParam) << ", " << HIWORD(lParam) << ")" << std::endl;
break;
case WM_LBUTTONDOWN:
std::cout << "Left button clicked at (" << LOWORD(lParam) << ", " << HIWORD(lParam) << ")" << std::endl;
break;
case WM_RBUTTONDOWN:
std::cout << "Right button clicked at (" << LOWORD(lParam) << ", " << HIWORD(lParam) << ")" << std::endl;
break;
case WM_MBUTTONDOWN:
std::cout << "Middle button clicked at (" << LOWORD(lParam) << ", " << HIWORD(lParam) << ")" << std::endl;
break;
}
}
// 调用默认的鼠标钩子处理程序
return CallNextHookEx(g_hMouseHook, nCode, wParam, lParam);
}
// 安装鼠标钩子
BOOL InstallMouseHook() {
g_hMouseHook = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc, GetModuleHandle(NULL), 0);
if (g_hMouseHook == NULL) {
std::cerr << "Failed to install mouse hook. Error code: " << GetLastError() << std::endl;
return FALSE;
}
std::cout << "Mouse hook installed successfully." << std::endl;
return TRUE;
}
// 卸载鼠标钩子
void UninstallMouseHook() {
if (g_hMouseHook != NULL) {
UnhookWindowsHookEx(g_hMouseHook);
g_hMouseHook = NULL;
std::cout << "Mouse hook uninstalled successfully." << std::endl;
} else {
std::cerr << "Mouse hook is not installed." << std::endl;
}
}
int main() {
if (InstallMouseHook()) {
std::cout << "Press any key to uninstall mouse hook and exit..." << std::endl;
std::cin.get();
UninstallMouseHook();
}
return 0;
}
这个程序使用SetWindowsHookEx
函数安装一个低级鼠标钩子,当鼠标移动或点击时,回调函数MouseHookProc
会被调用。在这个函数中,我们处理了鼠标移动、左键点击、右键点击和中键点击事件,并将它们的位置输出到控制台。
请注意,这个程序需要在Windows操作系统上运行,并且需要包含windows.h
头文件。此外,这个程序仅适用于C++编译器,并且需要在Visual Studio或其他支持C++的IDE中编译和运行。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。