Qt Windows.h 后台按键监测

首先 pro:

LIBS +=User32.LIB


main.cpp:
#include "hooktest.h"
#include "ui_hooktest.h"
#include <QDebug>

LRESULT CALLBACK keyProc(int nCode, WPARAM wParam, LPARAM lParam);

HHOOK keyHook=NULL;
WPARAM lastkey=0;
QString lastStr;

int starthook();
HookTest::HookTest(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::HookTest)
{
    ui->setupUi(this);
        keyHook = SetWindowsHookEx(WH_KEYBOARD_LL, keyProc, GetModuleHandle(NULL), 0);

        MSG msg = { 0 };
        while (GetMessage(&msg, NULL, 0, 0)) {  //WM_QUIT消息 退出
        //将虚拟键消息转换为字符消息,虚拟键值                `
        //VK_UP,VK_DOWN
        TranslateMessage(&msg);
        //将消息分发给窗口处理函数
        DispatchMessage(&msg);
        }
}

HookTest::~HookTest()
{
    delete ui;
}

LRESULT CALLBACK keyProc(int nCode, WPARAM wParam, LPARAM lParam){
    PKBDLLHOOKSTRUCT key = (PKBDLLHOOKSTRUCT)lParam;
    qDebug()<<key->vkCode<<endl;
    return CallNextHookEx(keyHook, nCode, wParam, lParam);
}

posted @ 2021-01-22 23:21  千寻slimg  阅读(344)  评论(0编辑  收藏  举报