Qt has never provided good support for the underlying system, such as serial port communication and global hotkeys that we often use. Since Qt may not be supported for some reason, we can only write code and call system-related APIs.
Note: This is Windows.These codes only support windows. At the same time, it also indicates that there must be other platforms to write.
To call the Windows API in Qt, you only need to add # include <windows. h> to the header file you need. However, it should be noted that Qt only supports win32 APIs, and does not support such APIs as MFC.
To use global hotkeys in Qt, the best way is to overload the winEventFilter function in QApplication. This function is used to respond to Windows system information. Its function prototype is virtual bool winEventFilter (MSG * msg, long * result ). When an element in the messageMSG structure of the msg pointer is of the WM_HOTKEY type, the hotkey is triggered by the user. The entire process is similar to the Message response mechanism in VC, but it is changed to Qt.
If you want to add your own Global hotkeys, you only need to use the RegisterHotKey function. Its function prototype is:
- BOOL RegisterHotKey( HWND hWnd, int id, UINT fsModifiers, UINT vk );
The HWND type is the window handle type in Windows. In Qt, QWidget and its subclass can be obtained using the winId () function.
The second parameter is an atomic operation type, which uses ATOM GlobalAddAtom (LPCTSTRLpString) Function. This is also a Win32API. You can obtain a unique value based on a string parameter. After use, you must use the GlobalDeleteAtom function to delete the entire ATOM. Its function prototype is
- ATOM GlobalDeleteAtom( ATOM nAtom )
The next two parameters are modifier keys and common keys. For example, if we want to register the key combination Ctrl + F4, fsModifiers is MOD_CONTROL, and vk is VK_F4.
If the registration is successful, true is returned. Otherwise, false is returned.
Note: after use, you must use the UnregisterHotKey function to log out. Otherwise, you may no longer be able to register this hot key! Unless it is restarted. Its function prototype is:
- BOOL UnregisterHotKey(HWND hWnd, int id )
OK. The hotkey registration is complete. After pressing the hot key, we will receive a msg in the winEventFilter function of QApplication. This msg, as mentioned earlier, needs to know whether one of its elements is WM_HOTKEY. If yes, it indicates that we have received the hotkey information for Windows. In the MSG structure, we may also need to understand two elements: wParam and lParam. WParam is the id used to register the hot key, that is, the ATOM ). LParam is our hotkey. It is actually a 32-bit type. The first 16 digits represent normal keys, and the last 16 digits represent modifier keys.
So far, Qt uses the Global hotkey in Windows. If you are interested, you can try it yourself and modify or directly write a copy of the code.