Home > MFC, Windows API > How to register a Hotkey for your application?

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.

// 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! 🙂

  1. August 17, 2008 at 3:06 pm


  2. ost.
    August 17, 2008 at 4:53 am

    ok. 10x for ur answer 🙂

  3. August 16, 2008 at 8:20 am

    Seems like it’s not neccessary, but we’re just following the rules.

  4. ost.
    August 16, 2008 at 7:21 am

    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?

  5. August 4, 2008 at 8:36 am

    Thank you!

  6. August 3, 2008 at 12:14 am

    Very nice!!

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: