When SetFocus Doesn't
So we were recently debugging a little problem in Flight Simulator that occurred when we were transferring focus between child windows using SetFocus. The problem was that SetFocus was returning NULL (which, according to the docs is an error condition), but a subsequent call to GetLastError returned 0 (everything is fine and dandy). A call to GetFocus confirmed that the focus hadn't changed.
After much debugging we figured it out. The target window was being hooked via a WH_CBT hook which was returning TRUE in response to a HCBT_SETFOCUS - i.e. the hook was telling the OS not to transfer focus. It would have been nice to have received some sort of useful error like ERROR_HOOK_JUST_MESSED_WITH_YOU.
Lesson learnt. Window hooks can mess with you when you least expect it.
After figuring that out I pinged Raymond Chen about the issue and this is what he had to say:
The reason you don't get a userful error is that the window manager doesn't even know that an error occurred. You called SetFocus. The window manager dispatched it to a hook. The hook returned the code "It's taken care of, no worries," and the window manager says "Okay, well then that's that." With a hook, a program can modify or even replace certain parts of the window manager. Of course, with that power comes great responsibility. If a hook wants to make SetFocus fail then it's the hook's responsibility to set an error code.
0 TrackBacks
Listed below are links to blogs that reference this entry: When SetFocus Doesn't.
TrackBack URL for this entry: http://www.steve-lacey.com/cgi-bin/mt/mt-bar.cgi/451



Thanks for posting this, Steve. I ran into the very same problem while debugging Flight Sim this afternoon, and your blog entry probably saved me a bunch of time. (I happened to Google for "SetFocus doesn't" and found your page as the first result.)