溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

編寫安全的C++鼠標(biāo)鉤子程序

發(fā)布時(shí)間:2024-11-07 13:11:24 來源:億速云 閱讀:78 作者:小樊 欄目:編程語言

創(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)行。

向AI問一下細(xì)節(jié)

免責(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)容。

c++
AI