Archive

Posts Tagged ‘WM_HOTKEY’

How to register a Hotkey for your application?

July 2, 2008 6 comments

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.

// 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
BEGIN_MESSAGE_MAP(..., ...)
   ON_MESSAGE(WM_HOTKEY, HotKeyHandler)
   ON_WM_DESTROY()
END_MESSAGE_MAP()

// Toggle visibility
LRESULT CYourDialog::HotKeyHandler(WPARAM wParam, LPARAM lParam)
{
   if( IsWindowVisible() )
   {
     ShowWindow( SW_HIDE );
   }
   else
   {
     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! 🙂