How to register a Hotkey for your application?

Now what’s a hotkey? An easy definition would be a key that remains hot throughout the lifetime of an application. Whenever you press a hotkey it does it’s work no matter where the focus is or where the input is directed to, etc.

Here is a screenshot and a sample application(Right click and save as exe), using this application you can register or unregister any combination of a given key (Here F12). So here when you press Ctrl + Alt + Shift + WinKey + F12 this dialog toggles it’s visibility state.

Screenshot for testing a hotkey

Screenshot for testing a hotkey

So here’s how we go about it.

[sourcecode language=’cpp’]// Make this a member variable of your class.
UINT m_UniqueIdentifier;

// Creates a unique identifier for your hotkey so that there is no hotkey id clashes.
// Call this probably from OnInitDialog
m_UniqueIdentifier = ::GlobalAddAtom( “Somename” );

::RegisterHotKey( m_hWnd, /*Your window handle*/
m_UniqueIdentifier, /*Unique identifier to uniquely identify this hotkey*/
MOD_ALT|MOD_CONTROL, /*Modifier keys*/
VK_F10 ); /*Virtual key code of any key*/

//Add these message map entries

// Toggle visibility
LRESULT CYourDialog::HotKeyHandler(WPARAM wParam, LPARAM lParam)
if( IsWindowVisible() )
ShowWindow( SW_HIDE );
ShowWindow( SW_SHOWNORMAL );
}// End if
}// End HotKeyHandler

void CYourDialog::OnDestroy()
//if you register you will have to unregister too.
UnregisterHotKey( m_hWnd, m_UniqueIdentifier );

A cleaner approach would be create a wrapper class around this hotkey. So that registration and unregistration can take place smoothly.

Even though unregistering may seem like not required but still IMO we should unregister a hotkey. Just following the rules! 🙂

6 thoughts on “How to register a Hotkey for your application?

  1. is it really necessary to unregister a hotkey. E.g my application need for it all time it work, but when it closes, it destroys the hotkey, it set, doesn’t it?

Appreciate your comments...