qt 全局按键监听

#ifndef KEYCAPTURER_H
#define KEYCAPTURER_H

#include <QObject>

class KeyCapturer : public QObject
{
    Q_OBJECT

  public:
    virtual ~KeyCapturer();
    static KeyCapturer *&instance()
    {
        static KeyCapturer *s = nullptr;
        if (s == nullptr)
        {
            s = new KeyCapturer();
        }
        return s;
    }

  public:
    void setkeyValue(int key);

  protected:
    KeyCapturer();

  signals:
    void getKey(int);

  private:
};

#endif // KEYCAPTURER_H
#include "keycapturer.h"

KeyCapturer::KeyCapturer()
{
}

KeyCapturer::~KeyCapturer()
{
}


void KeyCapturer::setkeyValue(int key)
{
    emit getKey(key);
}
keymonitor的头文件和实现文件如下
#include "keymonitor.h"
#include <QtDebug>
#include "keycapturer.h"

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

HMODULE WINAPI ModuleFromAddress(PVOID pv);
static HHOOK hHook;

LRESULT KeyboardHookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    KBDLLHOOKSTRUCT *Key_Info = (KBDLLHOOKSTRUCT *)lParam;
    if (HC_ACTION == nCode)
    {
        if (WM_KEYDOWN == wParam || WM_SYSKEYDOWN == wParam) //如果按键为按下状态
        {
            if (Key_Info->vkCode <= 107 && Key_Info->vkCode >= 65)
            {
                qDebug() << Key_Info->vkCode;
                if (KeyCapturer::instance())
                {
                    KeyCapturer::instance()->setkeyValue(Key_Info->vkCode);
                }
            }
        }
    }
    return CallNextHookEx(hHook, nCode, wParam, lParam);
}

HMODULE ModuleFromAddress(PVOID pv)
{
    MEMORY_BASIC_INFORMATION mbi;
    if (VirtualQuery(pv, &mbi, sizeof(mbi)) != 0)
    {
        return (HMODULE)mbi.AllocationBase;
    }
    else
    {
        return NULL;
    }
}

int startHook()
{
    hHook = SetWindowsHookExW(WH_KEYBOARD_LL, KeyboardHookProc, ModuleFromAddress((PVOID)KeyboardHookProc), 0);
    int error = GetLastError();
    return error;
}

bool stopHook()
{
    return UnhookWindowsHookEx(hHook);
}
#ifndef KEYMONITOR_H
#define KEYMONITOR_H


#include <Windows.h>
#include <DbgHelp.h>

int startHook();

bool stopHook();

#endif // KEYMONITOR_H

在主界面加入信号连接即可

    connect(KeyCapturer::instance(), &KeyCapturer::getKey, [=](int key)
            {
                qDebug() << "startHook==" << QString::number(key);
                HomeUtil::getInstance()->setTime();
                switch (key)
                {
                    case Qt::Key_F:
                       
                        return true;
                    case Qt::Key_H:
                        
                        return true;
                    default:
                        break;
                }
            });
    startHook();

猜你喜欢

转载自blog.csdn.net/fl2502923/article/details/110915405