C++ 第五十四篇——监控鼠标键盘

C++ 无DLL 全局鼠标键盘钩子,屏蔽键盘按键鼠标操作:https://blog.csdn.net/qq_42789677/article/details/120364014

 ConsoleApplication1.cpp

// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include<Windows.h>

#include <iostream>

std::string get_time() {
    SYSTEMTIME sys;
    GetLocalTime(&sys);
    char time[1024] = { 0 };
    sprintf_s(time, "[%4d/%02d/%02d %02d:%02d:%02d]", sys.wYear, sys.wMonth, sys.wDay, sys.wHour, sys.wMinute, sys.wSecond);
    return std::string(time);
}

LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
    KBDLLHOOKSTRUCT* ks = (KBDLLHOOKSTRUCT*)lParam; // 包含低级键盘输入事件信息
    char data[1024];
    DWORD code = ks->vkCode;
    std::string t = get_time();
    char state[20];
    if (wParam == WM_KEYDOWN) {
        strcpy_s(state, "按下");
    }
    else if (wParam == WM_KEYUP) {
        strcpy_s(state, "抬起");
    }
    sprintf_s(data, "%s 键代码: %d %s", t.c_str(), code, state);
    std::cout << data << std::endl;
    return CallNextHookEx(NULL, nCode, wParam, lParam);
}

LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam) {
    std::string t = get_time();
    char data[1024];
    MOUSEHOOKSTRUCT* ms = (MOUSEHOOKSTRUCT*)lParam;
    POINT pt = ms->pt;
    char state[20] = "未识别";
    if (wParam == WM_LBUTTONDOWN) {
        strcpy_s(state, "左键按下");
    }
    else if (wParam == WM_LBUTTONUP) {
        strcpy_s(state, "左键抬起");
    }
    else if (wParam == WM_MOUSEMOVE) {
        strcpy_s(state, "移动");
    }
    else if (wParam == WM_RBUTTONDOWN) {
        strcpy_s(state, "右键按下");
    }
    else if (wParam == WM_RBUTTONUP) {
        strcpy_s(state, "右键抬起");
    }
    sprintf_s(data, "%s 键代码: x:%d y:%d %s", t.c_str(), pt.x, pt.y, state);
    std::cout << data << std::endl;
    return CallNextHookEx(NULL, nCode, wParam, lParam);
}

int main()
{
    std::cout << "Hello World!\n";
    HINSTANCE hM = GetModuleHandle(NULL), hK = GetModuleHandle(NULL);
    HHOOK g_Hook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardProc, hK, 0);
    HHOOK g_Hook2 = SetWindowsHookEx(WH_MOUSE_LL, MouseProc, hM, 0);
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    UnhookWindowsHookEx(g_Hook);
    return 0;
}

// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单

// 入门使用技巧: 
//   1. 使用解决方案资源管理器窗口添加/管理文件
//   2. 使用团队资源管理器窗口连接到源代码管理
//   3. 使用输出窗口查看生成输出和其他消息
//   4. 使用错误列表窗口查看错误
//   5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
//   6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
View Code

 

可以监控到鼠标键盘的操作。

posted @ 2024-01-09 15:18  o云淡风轻o  阅读(156)  评论(0编辑  收藏  举报