April 20th, 2009

The dangers of destroying a window while it is processing a sent message

Commenter BryanK wonders why weird things happen if you destroy a window while it is processing the WM_ACTIVATEAPP message. He suspects that it’s similar to the problems you encounter when you destroy a window in response to the WM_KILLFOCUS message.

Although I haven’t studied the WM_ACTIVATEAPP situation, I wouldn’t be surprised if the problem is indeed entirely analogous. It just follows from general programming principles: After all, you are destroying the active window. The WM_ACTIVATEAPP message is sent as part of the activation change, and the documentation says that the message is sent “when a window belonging to a different application than the active window is about to be activated.” Notice: “about to be” activated. That other window hasn’t been activated yet; you’re still the active window.

Destroying the active window means that the window manager has to find a new active window. You’re triggering an activation change while another activation change is in progress; no wonder things get all messed up.

I am now going to make a gross generalization. There may be exceptions to this rule, but it’s a good place to start: Destroying yourself is (generally speaking) not an acceptable response to a sent message. The code that sent you the message is doing so because it wants to ask you a question (if it cares about the return value) or because it’s informing you of something that is happening right now as part of a larger operation. (After all, if the code didn’t mind if you received the information after the fact, it would have posted the message instead of sent it.)

And (generally speaking) it’s bad form to perform an operation that changes a system’s state while it’s notifying you that that very state change is in progress. When the state change is in progress, the state is unstable. (If it were stable, then the state change would either not yet have begun or already have finished!)

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.