Holy cow, I wrote a book!
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!)