Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to differentiate between hotkeys with registerHotKey()



  • Hey there,
    I am trying to setup multiple global hotkeys for my application using RegisterHotKey() from "windows.h".
    So far I have successfully added hotkeys using the tutorial on this site: amin-ahmadi.com.

    Now I do not find anything about how to differentiate between multiple hotkeys using the eventfilter() method.
    My code looks like this:

    menu.h

    #ifndef MENU_H
    #define MENU_H
    
    #include <QWidget>
    #include "windows.h"
    
    QT_BEGIN_NAMESPACE
    namespace Ui { class Menu; }
    QT_END_NAMESPACE
    
    class Menu : public QWidget
    {
        Q_OBJECT
    
    public:
        Menu(QWidget *parent = nullptr);
        ~Menu();
    
    protected:
        bool nativeEvent(const QByteArray &eventType, void *message, long *result); // From guide by amin-ahmadi.com
    
    private:
        Ui::Menu *ui;
        HWND desktop;
    
    };
    #endif // MENU_H
    

    menu.cpp

    #include "menu.h"
    #include "ui_menu.h"
    
    #include "windows.h"
    #include "QDebug"
    
    
    Menu::Menu(QWidget *parent)
        : QWidget(parent)
        , ui(new Ui::Menu)
    {
        ui->setupUi(this);
    
        if (!RegisterHotKey((HWND)Menu::winId(), 100, MOD_ALT | MOD_SHIFT, 'D'))
        {
            qDebug() << "Can't register hotkey ALT+SHIFT+D";
        }
    
        if (!RegisterHotKey((HWND)Menu::winId(), 100, MOD_ALT | MOD_SHIFT, 'S'))
        {
            qDebug() << "Can't register hotkey ALT+SHIFT+S";
        }
    
    }
    
    Menu::~Menu()
    {
        delete ui;
    }
    
    bool Menu::nativeEvent(const QByteArray& eventType, void* message, long* result)
    {
        Q_UNUSED(eventType);
        Q_UNUSED(result);
        MSG* msg = static_cast<MSG*>(message);
        if (msg->message == WM_HOTKEY)
        {
            qDebug() << "Hotkey pressed!";
            true;
        }
        return false;
    }
    

    No matter which of the one I press I receive the "Hotkey pressed!" message in the debugger. How can I now differentiate between the two hotkeys being pressed.
    Thank you for your insight!


  • Lifetime Qt Champion

    Don't see any relation to Qt here but you should read the msdn documentation.


Log in to reply