Thursday, March 13, 2008

[C++] How to disable Alt+Tab (and other key combinations)

You might need at some stage to disable some key combinations. There are -as always- different ways to do it; the one that I find -arguably- the easiest is showed in the following snippet, which traps the ALT+TAB combo:


#define MY_HOTKEYID 100 //unique in your window
//...
//Lock ALT+TAB - might wanna do it in your form constructor
bool isMyKeyComboTrapped = RegisterHotKey(GetSafeHwnd(), MY_HOTKEYID, MOD_ALT, VK_TAB);
ASSERT(isMyKeyComboTrapped!= FALSE); // just in case
//...
//...
//Unlock ALT+TAB - might wanna do it in your form destructor
isMyKeyComboTrapped = UnregisterHotKey(GetSafeHwnd(), MY_HOTKEYID);
ASSERT(isMyKeyComboTrapped!= TRUE); // just in case


What you're doing here is basically register a key combo without providing any handler for the WM_HOTKEY message fired when the Alt+Tab combination is pressed. You can use this trick to lock other key combos; use this msdn link as reference: RegisterHotKey reference. This method can't be used to trap the infamous Ctrl+Alt+Del combination in order to disable Task Manager; for this you can use the method described in this other post: How to Disable Task Manager.

Have a nice Patrick's Day!

6 comments:

Anonymous said...

Simple and Clear!

Rajavanya Subramaniyan said...

Gr8 site...

I strongly suggest you get wordpress with a custom domain name for as low as 5.99$ from name.com

Whats ur feed address?? I want to subscribe ur feeds

Anonymous said...

I looked at Technorati and it hasn't been updated for 2 weeks. Just FYI

I wonder if in a GUI program it wouldn't be better to keep those key combos active, and just "bail out" in the EventHandler. Of course I haven't done C++ GUIs at all.

Unknown said...

Raj:

thanks. You can subscribe to the feed from the Subscribe to: Posts link at the bottom of the page. Anyway here's the link: http://dotnetbutchering.blogspot.com/feeds/posts/default

5.99$ sounds like a good deal. We'll have a look, thanks for pointing out.

Unknown said...

Sam:

thanks, we'll check technocrati out.

You're right, that would be the best way to do it, giving you the chance to add some handling code in future if you need to. But -hey- look at the headline at the top, it says "When there's no time for best practices".

It's just a few more lines of code anyway, we'll probably arrange another post about how to handle key combination after registering them.

Anonymous said...

Good tutorial. Very simple and straight forward.