Question

Like many applications, mine creates multiple windows. I do not know and cannot keep track of how many windows have been created, so I don't know when there are none.

My problem is that when all the windows are closed, unless I call PostQuitMessage somehow, the application keeps running with no windows open (obviously). I can't call PostQuitMessage in the message handler in response to the WM_DESTROY message because that will close all the windows when the first one is closed, even if there are twenty others still open.

My question is how do I know when to call PostQuitMessage(0) to actually terminate the application?

Était-ce utile?

La solution

Just keep a static variable with a count of the number of open windows. When a windows opens have it increment the counter; in the WM_DESTROY handler decrement it. When the count goes to zero, call PostQuitMessage.

Autres conseils

If, for some reason, you really can't count how many windows the application opens, you can still use EnumThreadWindows() and when there are no more windows, you PostQuitMessage(). If you have several threads, make sure you enumerate through those too.

From MSDN

BOOL WINAPI EnumThreadWindows(
  __in  DWORD dwThreadId,
  __in  WNDENUMPROC lpfn,
  __in  LPARAM lParam
);

Of course, the only clean way is keeping track of your windows and post the quitmessage if none is left.

A possible workaround would be using one of the window enumerating functions. You can count your windows using EnumWindows() which calls a callback where you can count all toplevel windows. If it reaches zero, call PostQuitMessage().

A static variable for the number of the windows? I have never seen such a Program. One the one hand child windows can open and close during the lifetime of the application. One the other hand the main window procedure has to close the application, if the user closes the main window. For to do this, we have to add PostQuitMessage(0) in the WM_DESTROY branch of the main window procedure. After this message, GetMessage() returns 0 and the message loop ends because of this (and the application ends too)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top