First of all, this method can only be used in Windows because it makes use of the RegisterHotKey function which is a Win32 API function. So if you want to trigger a function in your Qt application even when your application is out of focus or minimized or even hidden then follow the steps below one by one:
1. Include the required header files in your code.
2. Add required libraries to your qmake project (.PRO file)
LIBS += -lUser32
3. Call RegisterHotKey function when your program starts. (Note that in this example I am trying to use ALT+CTRL+M as the global hotkey to be used by my program.)
if(!RegisterHotKey(HWND(winId()), 0, MOD_ALT | MOD_CONTROL, 0x4D))
QMessageBox::warning(this, “Warning”, “Can’t register hotkey ALT+CTRL+M”);
4. Override the nativeEvent function in your MainWindow app.
To do this first add the following code to your MainWindow class:
bool nativeEvent(const QByteArray &eventType, void *message, long *result);
And write the function body like this:
bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, long *result)
MSG *msg = static_cast<MSG*>(message);
if(msg->message == WM_HOTKEY)
QMessageBox::information(this, “OK”, “Hotkey pressed!”);
For any questions that you might have please put a comment below.