您好,登錄后才能下訂單哦!
創(chuàng)建一個(gè)安全的C++鼠標(biāo)鉤子程序需要使用低級(jí)別的API函數(shù)
#include <iostream>
#include <windows.h>
// 定義一個(gè)全局變量來存儲(chǔ)鼠標(biāo)鉤子的句柄
HHOOK g_hMouseHook = NULL;
// 鼠標(biāo)鉤子回調(diào)函數(shù)
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;
}
}
// 調(diào)用默認(rèn)的鼠標(biāo)鉤子處理程序
return CallNextHookEx(g_hMouseHook, nCode, wParam, lParam);
}
// 安裝鼠標(biāo)鉤子
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;
}
// 卸載鼠標(biāo)鉤子
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;
}
這個(gè)程序使用SetWindowsHookEx
函數(shù)安裝一個(gè)低級(jí)鼠標(biāo)鉤子,當(dāng)鼠標(biāo)移動(dòng)或點(diǎn)擊時(shí),回調(diào)函數(shù)MouseHookProc
會(huì)被調(diào)用。在這個(gè)函數(shù)中,我們處理了鼠標(biāo)移動(dòng)、左鍵點(diǎn)擊、右鍵點(diǎn)擊和中鍵點(diǎn)擊事件,并將它們的位置輸出到控制臺(tái)。
請(qǐng)注意,這個(gè)程序需要在Windows操作系統(tǒng)上運(yùn)行,并且需要包含windows.h
頭文件。此外,這個(gè)程序僅適用于C++編譯器,并且需要在Visual Studio或其他支持C++的IDE中編譯和運(yùn)行。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。