In my demo kinda app
case WM_CLOSE:
DestroyWindow(hndl);
return 0;
and
case WM_CLOSE:
PostQuitMessage(0);
return 0;
do the same. What's different behind the curtains when calling each? Is DestroyWindow more direct, where as PostQuitMessage has to go through the getmessage loop returning false?
DestroyWindow destroys the window (surprise) and posts a WM_DESTROY (you'll also get a WM_NCDESTROY) to the message queue. This is the default behaviour of WM_CLOSE. However, just because a window was destroyed does not mean the message loop should end. This can be the case for having a specific window that ends the application when closed and others that do nothing to the application when closed (e.g., an options page).
PostQuitMessage posts a WM_QUIT to the message queue, often causing the message loop to end. For example, GetMessage will return 0 when it pulls a WM_QUIT out. This would usually be called in the WM_DESTROY handler for your main window. This is not default behaviour; you have to do it yourself.
Neither snippet is correct. The first one will do what the default window procedure already does when it processes the WM_CLOSE message so is superfluous. But doesn't otherwise make the application quit, it should keep running and you'd normally have to force the debugger to stop with Debug + Stop Debugging. If you run it without a debugger then you'll leave the process running but without a window so you can't tell it is still running. Use Taskmgr.exe, Processes tab to see those zombie processes.
The second snippet will terminate the app but will not clean up properly since you don't pass the WM_CLOSE message to the default window procedure. The window doesn't get destroyed. Albeit that the operating system will clean up for you so it does all come to a good end, just without any bonus points for elegance.
The proper way to do it is to quit when your main window is destroyed. You'll know about it from the WM_DESTROY notification that's sent when that happens:
case WM_DESTROY:
PostQuitMessage(0);
return 0;
PostQuitMessage doesn't necessarily mean the end of application. It simply posts WM_QUIT to the message loop and allows you to exit from the message loop, so in most cases, this means the end of the application. However, in a multithread application, if you have the message loop for each thread created, PostQuitMessage only closes that thread.
As a side note, if you ever need more lines of code to execute after the message loop (such as further clean-up), PostQuitMessage is a better way to go, because DestroyWindow destroys the window without going through the message loop, ignoring whatever clean-up codes remaining after the message loop. Some may call it a not-so-good coding practice, but sometimes you can't avoid situations like that.
Related
I'm looking for some feedback on an issue that I can workaround, but want to understand better. I have some multithreaded code where a worker thread uses the Win32 API PostMessage function to post a message to the main UI thread in order to update a TreeView. Some of the posted messages sometimes fail to ever appear via the UI thread's message pump, despite my logging showing that the PostMessage returned successfully.
I've already found numerous explanations of how this could happen if I'd done something funky in my message pump, due to the presence of a modal message pump in certain circumstances, but I'm not doing anything funky.
I think (but would like confirmed) that my problem is due to calling PostMessage too early in the UI thread's lifetime. My WinMain calls CreateWindowEx to create its main window, and the WM_CREATE handler for that window indirectly launches the background threads that will, fairly quickly, call PostMessage using the main windows's HWND, possibly even before the WM_CREATE handler finishes, very likely before WinMain's message pump is started.
Is it possible/likely that some messages in this situation would be lost, even though PostMessage returned success? In testing, I've determined that adding a small delay (Sleep(50)) in the worker thread before it calls PostMessage is enough to prevent any message loss. However, I'm not convinced that this is solving the underlying problem so would like to know if I need to keep digging.
EDIT:
There's only one message loop in all my code and it's not doing anything unusual beyond calling the usual TranslateAccelerator etc:
// Enter the message loop
while (GetMessage (&msg, NULL, 0, 0)) {
if (!TranslateMDISysAccel(hwndClient, &msg) && !TranslateAccelerator (hwndFrame, hAccel, &msg)) {
TranslateMessage (&msg) ;
DispatchMessage (&msg) ;
}
}
I've already found numerous explanations of how this could happen if I'd done something funky in my message pump, due to the presence of a modal message pump in certain circumstances, but I'm not doing anything funky.
Modal loops don't throw away window messages, unless they are coded wrong and don't pass unknown messages to TranslateMessage()/DispatchMessage() like they should.
I think (but would like confirmed) that my problem is due to calling PostMessage too early in the UI thread's lifetime.
If that were the case, PostMessage() would simply fail, but you have already ruled that out. As soon as a thread calls any user32.dll function, the message queue is created and can begin receiving messages, even if the queue is not polled right away.
Is it possible/likely that some messages in this situation would be lost, even though PostMessage returned success?
No. Something else is going on. Either your message loop is filtering messages incorrectly, or a malformed modal loop is discarding messages, or you are simply posting to the wrong HWND. Hard to say as you did not show any of your code.
In testing, I've determined that adding a small delay (Sleep(50)) in the worker thread before it calls PostMessage is enough to prevent any message loss.
What is your main thread normally doing during those 50ms? Sounds like something in your UI code is receiving and discarding your posted messages during that time.
On the other hand, how do the threads know which HWND to post to? Is your WM_CREATE handler passing its hwnd parameter to the threads, or are the threads relying on the HWND returned by CreateWindowEx()? In the latter case, PostMessage() should fail if called before CreateWindowEx() exits. Unless your receiving HWND variable is initially uninitialized and contains a random non-null value that PostMessage() interprets as a valid HWND elsewhere on the system.
I noticed that some messages in WinAPI can be retrieved only in the "main message loop" with PeekMessage() (like WM_QUIT), others can only be retrieved in the user defined winProc() function (like WM_CLOSE and WM_SIZE), and some messages like WM_MOUSEMOVE are retrieved with both.
What's the difference? How do I know where the WM message is going to be sent to?
Messages that were posted with a NULL window handle can only be retrieved in the message loop. Necessarily so, DispatchMessage() can't do its job. This is quite rare.
But yes, WM_QUIT, note how PostQuitMessage() does not take a window handle. That's rather inevitable, when you call PostQuitMessage() you (usually) don't have any window left so only a NULL window handle is sensible. Of course its real intention is to make GetMessage() return FALSE and thus terminate the message loop.
The only other case I can think of are messages generated with PostThreadMessage(). Note how this is a pretty dangerous function, it should never be used to post messages to a thread that ever displays any window. Such messages fall in the bit-bucket when another message loop pumps. Like the one that allows the user to move/resize a window. Or the one that keeps MessageBox() modal. It is only useful in process and thread interop marshaling.
So just ignore this, it is a corner-case.
I am novice with Win32, and I have been pursuing a problem (if it can be called a problem at all) with Windows blocking your program's flow during the event when a user grabs the window title bar and moves it around the screen.
I have no legitimate reason to solve this problem, except that it bothers me. A few possibilities include removing the frame altogether, but it seems an inconvenient hack. Some games (single player) do not find this a problem at all. I have read however, that multiplayer games might experience problems when the program freezes as it expects continuous flow of information and can be overwhelmed after such a delay.
I have tried adding this to my WindowProc
switch (uMsg)
{
case WM_SYSCOMMAND:
if (wParam == SC_CLOSE)
PostQuitMessage(0);
return 0;
...
...
default:
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
return 0;
And this seems a quick hack, except that when I mousedown over the close icon I can pull the mouse away and let go without closing the program, and during that time, when the close icon is held down, the program once again is blocked.
Furthermore, I do not know how to manually include the code necessary to move the window when the user clicks the titlebar and drags the mouse. For starters I do not know which uMsg's and wParam's to handle.
My question is then, how do I disallow blocking during the case when the user clicks down the exit button (or minimize/maximize buttons) while still handling the case when the mouse is clicked and released over the button, and how do I allow the user to move/drag the window without it blocking the program (or what message is sent when the title bar is clicked without it being a button or menu)?
I am creating the window with WS_SYSMENU | WS_MINIMIZEBOX.
I still want the program to respond to minimize, maximize, and exit commands.
If multi-threading can fix it, then that is interesting, but I wonder if I can get it to work on single-core processors. And I have read about hooks, but the MSDN page is still hard for me to interpret.
Why Is My App Freezing?—An Introduction to Message Loops & Threads
This phenomenon is not isolated to any particular message. It's a fundamental property of the Windows message loop: when one message is being processed, no other message can be processed at the same time. It's not exactly implemented this way, but you can think of it as a queue, where your app pulls the messages out of the queue to process in the reverse order that they are inserted.
Therefore, spending too long processing any message is going to suspend the processing of other messages, effectively freezing your application (because it cannot process any input). The only way to solve this problem is the obvious one: don't spend too long processing any one message.
Often that will mean delegating the processing to a background thread. You will still need to handle all messages on the main thread, and the background worker threads need to report back to the main method when they are finished. All interaction with the GUI needs to happen on a single thread, and that is almost always the main thread in your application (which is why it is often called the UI thread).
(And to answer an objection raised in your question, yes, you can operate multiple threads on single processor machines. You won't necessarily see any performance improvements, but it will make the UI more responsive. The logic here is that a thread can only do one thing at a time, but a processor can switch between threads extremely rapidly, effectively simulating doing more than one thing at a time.)
More useful information is available here in this MSDN article: Preventing Hangs in Windows Applications
Special Cases: Modal Event Processing Loops
Certain window operations on Windows are modal operations. Modal is a common word in computing that basically refers to locking the user into a particular mode where they cannot do anything else until they change (i.e. get out of that) modes. Whenever a modal operation is begun, a separate new message processing loop is spun up and message handling happens there (instead of your main message loop) for the duration of the mode. Common examples of these modal operations are drag-and-drop, window resizing, and message boxes.
Considering the example here of window resizing, your window receives a WM_NCLBUTTONDOWN message, which you pass to DefWindowProc for default processing. DefWindowProc figures out that the user intends to start a move or resize operation, and entered a moving/sizing message loop located somewhere deep in the bowels of Windows' own code. Thus, your application's message loop is no longer running because you've entered into a new moving/sizing mode.
Windows runs this moving/sizing loop as long as the user is interactively moving/sizing the window. It does this so that it can intercept mouse messages and process them accordingly. When the moving/sizing operation completes (e.g., when the user releases the mouse button or presses the Esc key), control will return to your application code.
It is worth pointing out that you are notified that this mode change has occurred via the WM_ENTERSIZEMOVE message; the corresponding WM_EXITSIZEMOVE message indicates that the modal event-processing loop has exited. That allows you to create a timer that will continue to generate WM_TIMER messages that your application can process. The actual details of how this is implemented are relatively unimportant, but the quick explanation is that DefWindowProc continues to dispatch WM_TIMER messages to your application inside of its own modal event processing loop. Use the SetTimer function to create a timer in response to the WM_ENTERSIZEMOVE message, and the KillTimer function to destroy it in response to the WM_EXITSIZEMOVE message.
I only point that out for completeness, though. In the majority of Windows apps that I've written, I've never needed to do that.
So, What Is Wrong With My Code?
Aside from all of that, the behavior you describe in the question are unusual. If you create a new, blank Win32 application using the Visual Studio template, I doubt you will be able to replicate this behavior. Without seeing the rest of your window procedure, I can't tell if you're blocking on any messages (as discussed above), but the part I can see in the question is wrong. You must always call DefWindowProc for messages that you do not explicitly process yourself.
In this case, you might be fooled into thinking that you're doing that, but WM_SYSCOMMAND can have lots of different values for its wParam. You only handle one of those, SC_CLOSE. All of the rest of them just get ignored because you return 0. That includes all of the window moving and resizing functionality (e.g. SC_MOVE, SC_SIZE, SC_MINIMIZE, SC_RESTORE, SC_MAXIMIZE, etc. etc.).
And there's really no good reason to handle WM_SYSCOMMAND yourself; just let DefWindowProc take care of it for you. The only time you need to handle WM_SYSCOMMAND is when you've added custom items to the window menu, and even then, you should pass every command that you do not recognize on to DefWindowProc.
A basic window procedure should look like this:
LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch(uMsg)
{
case WM_CLOSE:
DestroyWindow(hWnd);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
It is also possible that your message loop is wrong. The idiomatic Win32 message loop (located near the bottom of your WinMain function) looks like this:
BOOL ret;
MSG msg;
while ((ret = GetMessage(&msg, nullptr, 0, 0)) != 0)
{
if (ret != -1)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
// An error occurred! Handle it and bail out.
MessageBox(nullptr, L"Unexpected Error", nullptr, MB_OK | MB_ICONERROR);
return 1;
}
}
You do not need hooks of any kind. The MSDN documentation on these is very good, but you're right: they're complicated. Stay away until you have a better understanding of the Win32 programming model. It is a rare case indeed where you need the functionality provided by a hook.
If multi-threading can fix it, then that is interesting but I wonder
if I can get it to work on single-core processors. And I have read
about hooks, but the MSDN page is still hard for me to interpret.
You can use multiple threads on a single-core processor. Performance would be better on multi-core systems, but that shouldn't prevent you from writing multithreaded applications. Anyway, go for it.
By printing all messages sent to WindowProc it appears WM_NCLBUTTONDOWN is sent last before the block occurs. You could check the mouse location after this event occurs, but it seems an inconvenient way to solve a simple problem.
I have an external application that calls my application and is supposed to end it when the job is done. The log from this external application claims it uses WM_CLOSE on my app.
How can I intercept the WM_CLOSE message in my application to do some cleanup operations? I tried at_exit() and wrapping it in a class, but I think I have the wrong approach.
The official solution for console applications is HandlerRoutine, a callback set by SetConsoleCtrlHandler. Windows will call your handler with a CTRL_CLOSE_EVENT argument in case of a WM_CLOSE exit.
When you're using a class method with SetConsoleCtrlHandler, it must be a static method - Windows won't provide you with a this pointer.
You could just handle WM_CLOSE in your message loop to do whatever cleanup is necessary, or even abort the close (by returning 1 instead of 0). See e.g. this: http://cboard.cprogramming.com/windows-programming/141438-handling-wm_close-wm_destroy.html#post1056273
Edit: for console applications, this may be of interest: http://support.microsoft.com/kb/178893
You must create hidden window using winapi, and handle WM_CLOSE message in its message loop. Is your app using any gui elements?
The easiest way I think is to call PeekMessage from time to time.
BOOL IsCloseEventReceived()
{
MSG msg;
return PeekMessage(&msg, NULL, WM_CLOSE, WM_CLOSE, PM_NOREMOVE);
}
This function should work to check if a WM_CLOSE message has been posted. It's not blocking, and you'll need to call it on a regular basis.
I might be wrong, but I think you don't need a hidden window to handle messages, a message queue is attached to your process the first time you call a messages-related function, like PeekMessage. However if you receive a WM_CLOSE message prior to your first call of this function it might be lost.
I was wondering what the difference between the WM_QUIT, WM_CLOSE, and WM_DESTROY messages in a windows program, essentially: when are they sent, and do they have any automatic effects besides what's defined by the program?
They are totally different.
WM_CLOSE is sent to the window when it is being closed - when its "X" button is clicked, or "Close" is chosen from the window's menu, or Alt-F4 is pressed while the window has focus, etc. If you catch this message, this is your decision how to treat it - ignore it, or really close the window. By default, WM_CLOSE passed to DefWindowProc() causes the window to be destroyed.
WM_DESTROY is sent to the window when it starts to be destroyed. In this stage, in opposition to WM_CLOSE, you cannot stop the process, you can only make any necessary cleanup. When you catch WM_DESTROY, none of its child windows have been destroyed yet.
WM_NCDESTROY is sent to the window when it is finishing being destroyed. All of its child windows have been destroyed by this time.
WM_QUIT is not related to any window (the hwnd got from GetMessage() is NULL, and no window procedure is called). This message indicates that the message loop should be stopped and the application should exit. When GetMessage() reads WM_QUIT, it returns 0 to indicate that. Take a look at a typical message loop snippet - the loop is continued while GetMessage() returns non-zero.
WM_QUIT can be sent by the PostQuitMessage() function. This function is usually called when the main window receives WM_DESTROY (see a typical window procedure snippet).
First of all, the WM_CLOSE and WM_DESTROY messages are associated with particular windows whereas the WM_QUIT message is applicable to the whole application (well thread) and the message is never received through a window procedure (WndProc routine), but only through the GetMessage or PeekMessage functions.
In your WndProc routine the DefWindowProc function takes care of the default behavoir of these messages. The WM_CLOSE messages requests that the application should close and the default behavoir for this is to call the DestroyWindow function. Its when this DestroyWindow function is called that the WM_DESTROY message is sent. Notice that the WM_CLOSE is only a message requesting that you close (like WM_QUIT) - you don't actually have to exit/quit. But the WM_DESTROY message tells you that your window IS being closed and destroyed so you must cleanup any resources, handles etc.
Just so it doesn't get lost in the comments... don't forget about WM_CANCEL. When you click the close (x) button on an MFC dialog, it will certainly send WM_CLOSE. The default OnClose() function will then call the default (base class) OnCancel() function.
However, if you simply type the ESC key, this will lead to the closure of the dialog, but (as far as I can tell) without generating the WM_CLOSE event - it goes directly to the WM_CANCEL/OnCancel() mechanism.
I hereby invite the community to elaborate on this... or edit that elaboration into the accepted answer.
At first let's discuss WM_QUIT - the difference from another messages that this is not associated with window. It is used by application. For example this can be handled by non-visible standalone OLE server (.exe, but not in-proc as .dll)
WM_CLOSE - per msdn: "An application can prompt the user for confirmation, prior to destroying a window" - it is used as notification about intention to close (you can reject this intention).
WM_DESTROY - is a fact that window is closing and all resources must(!) be deallocated.
I know this is old, but just trying to provide a clearer answer for anyone.
// What causes each message?
WM_CLOSE: // Pressed Close Button (X) / Alt+F4 / "Close" in context menu
WM_DESTROY: // Called DestroyWindow(hwnd)
WM_QUIT: // Called PostQuitMessage(exit)
// What do they do by default?
case WM_CLOSE: DestroyWindow(hwnd); return 0; // pressed close? destroy window.
case WM_DESTROY: PostQuitMessage(0); return 0; // destroyed window? quit message loop.
// WM_QUIT isn't associated with a window, so isn't sent to the window procedure
So WM_CLOSE is just so we can request to destroy the window. However you might want it to show a popup in your game asking if you're sure. (and if you want to save first)
And WM_DESTROY doesn't actually post the quit message by default, since you could have multiple windows. That's just the usual event we quit after. You could have WM_CLOSE call PostQuitMessage(exit) and destroy your window(s) after the message loop if you wanted.
If you wanted a custom close button in your game, it should do what WM_CLOSE does.
Also there is the function CloseWindow(hwnd), however it simply minimizes the window.
Hope this helps anyone.