您好,登錄后才能下訂單哦!
創建一個安全的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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。