window 键盘 hook 使用

#include "widget.h"
#include <QApplication>

HHOOK key_keep=NULL;
HWND window_hwhd=NULL;

LRESULT CALLBACK KeyboardProc( int nCode,  WPARAM wParam, LPARAM lParam )
{
    KBDLLHOOKSTRUCT *pkbhs=(KBDLLHOOKSTRUCT*)lParam;
    if(nCode == HC_ACTION){
        if(pkbhs->vkCode == VK_ESCAPE && GetAsyncKeyState(VK_CONTROL)& 0x8000 && GetAsyncKeyState(VK_SHIFT)&0x8000){
            qDebug() << "Ctrl+Shift+Esc";
        }else if(pkbhs->vkCode == VK_ESCAPE && GetAsyncKeyState(VK_CONTROL) & 0x8000){
            qDebug() << "Ctrl+Esc";
        }else if(pkbhs->vkCode == VK_TAB && pkbhs->flags & LLKHF_ALTDOWN){
            qDebug() << "Alt+Tab";
        }else if(pkbhs->vkCode == VK_ESCAPE && pkbhs->flags &LLKHF_ALTDOWN){
            qDebug() << "Alt+Esc";
        }else if(pkbhs->vkCode == VK_LWIN || pkbhs->vkCode == VK_RWIN){
            qDebug() << "LWIN/RWIN";
        }else if(pkbhs->vkCode == VK_F4 && pkbhs->flags & LLKHF_ALTDOWN){
            qDebug() << "Alt+F4";
        }
        qDebug() << QTime::currentTime().toString("hh:mm:ss zzz") << nCode << pkbhs->vkCode << pkbhs->time;
        return 1;//返回1表示截取消息不再传递,返回0表示不作处理,消息继续传递
    }
    return CallNextHookEx(key_keep, nCode, wParam, lParam);
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    window_hwhd=(HWND)w.winId();
    key_keep= SetWindowsHookEx(/*WH_KEYBOARD*/WH_KEYBOARD_LL,KeyboardProc,NULL,0/*GetCurrentThreadId()*/);

    return a.exec();
}

  

 

LIBS += -luser32

  

 

全局监听键盘事件,不管界面是否激活状态,都可以获取键盘输入

上一篇:工作流开源项目


下一篇:【Android 插件化】Hook 插件化框架 ( hook 插件化原理 | 插件包管理 )