Mega Code Archive

 
Categories / Delphi / Examples
 

Register your hotkeys

Title: Register your hotkeys Question: Do you need to activate your app using a system-wide hotkey ? Answer: Here is a little known function from the WinAPI (but nonetheless usefule) - RegisterHotKey, which defines a hot key for use in your application: function RegisterHotKey(hWnd: HWND; id: Integer; fsModifiers, vk: UINT): BOOL; stdcall; It's parameters are: hWnd Identifies the window that will receive WM_HOTKEY messages generated by the hot key. If this parameter is NULL, WM_HOTKEY messages are posted to the message queue of the calling thread, and you have to write a WM_HOTKEY message handler (you receive the msg in the message queue of the calling thread). It is usually nil or aForm.Handle. id Specifies the identifier of the hot key. No other hot key in the calling thread should have the same identifier. An application must specify a value in the range 0x0000 through 0xBFFF. A shared dynamic-link library (DLL) must specify a value in the range 0xC000 through 0xFFFF (the range returned by the GlobalAddAtom function). To avoid conflicts with hot-key identifiers defined by other shared DLLs, a DLL should use the GlobalAddAtom function to obtain the hot-key identifier. fsModifiers Specifies keys that must be pressed in combination with the key specified by the nVirtKey parameter in order to generate the WM_HOTKEY message. The fsModifiers parameter can be a combination of the following values: MOD_ALT, MOD_CONTROL and MOD_SHIFT (guess what they indicate :). vk Specifies the virtual-key code of the hot key. Result: If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. This might happen if the key-combinations have already been registered by another thread or if you try to associate a hot key with a window created by another thread. What do you have to do to use it in Delphi: Just call it, something like this: RegisterHotKey(Handle,123,mod_control,vk_f7); and don't forget your message handler: ... = class(TForm) ... protected procedure WMHotKey(var Message: TMessage); message WM_HOTKEY; Usually in the event handler you activate your application (Application.Restore; Application.BringToFront; etc.) and initiate something. Of course, in the Windows.pas unit, where it is declared (the virtual-key codes are there too), you can find its doppelganger: function UnregisterHotKey(hWnd: HWND; id: Integer): BOOL; stdcall; Bogdan Grigorescu - BogdanG@gmail.com BG Remote Programming Group