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.
#include "windows.h"
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)
{
Q_UNUSED(eventType);
Q_UNUSED(result);
MSG* msg = static_cast<MSG*>(message);
if (msg->message == WM_HOTKEY)
{
QMessageBox::information(this, "OK", "Hotkey pressed!");
true;
}
return false;
}
For any questions that you might have please put a comment below.
Thanks Ahmad,
Your post is so helpful
I implemented this solution and it works fine, but now my menu bar isn’t working. I added qDebug() << *msg in the nativeEvent function and it seems like the nativeEvent receives all event calls but Qt doesn't get the events anymore. How can I fix this?
I see. Can you try the following solution please:
Replace the followig:
return false;
with this line:
return QMainWindow::nativeEvent(eventType, message, result);
Let me know if this helps.
Is it possible to make two global hotkeys in one program? 🙂
Yes, you should be able to.