Wednesday, May 2, 2012

Capturing Hot Key on Windows with Qt

Generally I don't use windows, but at work I need to use windows sometime and on windows I required to create one utility application, which can be activated by hotkey like, Alt + Tab.

There is RegisterHotKey windows API, by calling it we can register special key combination as Hot Key. By winEvent event handler, we can respond to Hot Key event.

Following is my code, that register CTRL+SHIT+SPACE as Hot key and responds it in winEvent handler.
DefineWordWidget::DefineWordWidget(QWidget *parent) :
    QWidget(parent)
{
    RegisterHotKey(winId(), 100, MOD_CONTROL|MOD_SHIFT, VK_SPACE);
    mClipBoard = QApplication::clipboard();
}

bool DefineWordWidget::winEvent(MSG *message, long *result)
{   
    if( message->message == WM_HOTKEY) {
        QString originalText = mClipBoard->text();
        qDebug() << "ClipBoard:" << originalText;
        if( !originalText.isEmpty()) {
            //show widget if minimized
            this->setWindowState((this->windowState() & ~Qt::WindowMinimized)
                | Qt::WindowActive);
        }
        return true;
    }
    return false;
}

No comments:

Post a Comment