Windows message Loop confusion - windows

I have a GUI window in WTL that runs inside a thread inside a CMessageLoop instance which has been added to the application instance and runs. Now, inside a button handler within the main GUI I create a new window. Once I click that button and create the window and try to post the quit message to the main GUI loop. The code:
Main window, has its own thread:
CMessageLoop theLoop;
_MyppModule.AddMessageLoop(&theLoop);
if(m_pMyDlg == NULL) {
m_pMyDlg = new CMyDlg();
if(!IsWindow(*m_pMyDlg))
{
m_pMyDlg->Create(NULL);
m_pMyDlg->ShowWindow(SW_SHOW);
nRet = theLoop.Run();
_MyppModule.RemoveMessageLoop();
}
}
Button handler & child window creation:
LRESULT CMyDlg::OnButtonClicked(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
ChildWindowDlg childDlg;
childDlg.Create(m_hWnd);
childDlg.ShowWindow(SW_SHOW);
CMessageLoop _loop;
);
_loop.Run();
::DestroyWindow(childDlg);
return S_OK;
}
Now, if I click the Close button in my MyDlg window the button's handler will get called, inside it I do ::PostQuitMessage but that never reaches the theLoop messageloop from the first code snippet.
This happens after I exit the second loop, so _loop gets destroyed and the child dialog is destroyed.
What is happening here?

You have two message loops here, the child's one is nested. On the other hand, the message queue is one per thread, and is pumped by the most inner message loop (with GetMessage). So, WM_QUIT message gets retrieved by the inner message loop inside CMyDlg::OnButtonClicked.

The second code snippet is totally unnatural. If your goal is to have a window popped up, then closed and and then you want to complete execution of your button click handler, then modal dialog is what you need:
LRESULT CMyDlg::OnButtonClicked(WORD wNotifyCode, WORD wID, HWND hWndCtl,
BOOL& bHandled)
{
ChildWindowDlg childDlg; // Add constructor parameters if needed
// Additional initlaization calls might go here
const INT_PTR nResult = childDlg.DoModal(m_hWnd); // DoModal handles it all
if(nResult == IDOK) { ... } // Hey's we even have result coming from `EndDialog`
return 0; // No S_OK here
}
No message loops, no PostQuitMessage, no separate window creation/destruction calls needed. This is what modal dialogs are for.
If you don't want to block "calling" window, and the idea is to have both master and slave windows running side by side (or, one is a part of another, anyway both to be responsive at the same time), then you don't want to block your message handler. The handler will create window and set it up (.Create, .ShowWindow) and then exit from OnButtonClicked function.
Both windows are created, both are alive and have their message sent to them by top level message loop. This is the correct approach, you don't normally need more than one message loop per thread. Sometimes it might make sense for specific operations, but this is really rare. Windows are passive instances. They respond to messages with their message handlers. A thread message loop serves all thread windows, because what it does is DispatchMessage API call, which in turn looks for target window, takes its WndProc and calls it handing message details in.

Related

Calling ShowWindow(SW_SHOW) on ATL modeless dialog not bringing window to front

I have a modeless dialog which I am showing and hiding programmatically from a worker thread. The problem is that the CWindow::ShowWindow(SW_SHOW) function is sometimes bringing the dialog to the front, and sometimes not.
Task: Show/Hide a simple logging & control window for an ATL COM object (dll) that runs in a separate thread. The COM object isn't a control: it is being used to wrap processing code for use in Excel VBA.
I've created a CMyDialog class derived from the CAxDialogImpl template. Then I'm using the CWorkerThread template for the worker thread. This is the Execute block (ie the function that runs in the worker thread).
HRESULT CLogProcessor::Execute(DWORD_PTR dwParam, HANDLE hObject)
{
m_bRunning = true; //Winging it as this isn't thread-safe, but I don't think that's the issue.
if (m_pDlg == 0)
{
m_pDlg = new CMyDialog(); //My dialog class
m_pDlg->SetStopEvent(m_hStopEvent); //Save the handle of the stop event in the Dialog class
m_pDlg->Create(NULL); //Create with no parent
m_pDlg->ShowWindow(SW_SHOW); //Show the window
}
//Loop here until told to stop by the Stop Event being signalled in the calling thread
while (WaitForSingleObject(m_hStopEvent, 0) == WAIT_TIMEOUT) //Polling Stop Event
{
//Have to keep the message loop going!
MSG uMsg;
while (PeekMessage(&uMsg, m_pDlg->m_hWnd, 0, 0, PM_REMOVE))
{
TranslateMessage(&uMsg);
DispatchMessage(&uMsg);
}
//The thread uses a protected "stack" of string messages to write to my logging window
string strMsg;
while (m_MsgStack.PopFront(strMsg))
{
std::wstring ws = std::wstring(strMsg.begin(), strMsg.end());
CWindow eb(m_pDlg->GetDlgItem(IDC_EDIT1));
eb.SendMessage(EM_REPLACESEL, 0, (LPARAM)ws.c_str());
}
}
//Stop event has been signalled so clear up the dialog
m_pDlg->DestroyWindow();
delete m_pDlg;
m_pDlg = 0;
m_bRunning = false;
return S_OK;
}
My Log object has two functions, StartLog() and StopLog() which are called by the COM object which is doing the main work of data processing.
void CLogProcessor::StartLog()
{
if (!m_bRunning)
{
::SetEvent(m_hStartEvent);
}
}
void CLogProcessor::StopLog()
{
if (m_bRunning)
{
::SetEvent(m_hStopEvent);
}
}
This works fine. I run VBA code in an Excel spreadsheet with buttons that call (via the COM object) StartLog() and StopLog(). The first time the Log Dialog appears all is good: it is activated and comes to the front. Firing StopLog() closes the dialog and it disappears. But the second time I call StartLog() the dialog window appears but it is not at the front, but behind other windows. I have tried a CWindow::BringWindowToTop() and/or SetFocus() call straight after the ShowWindow() but it makes no difference.
Another interesting feature is that my dialog has a system menu and so an 'X' to close it in the top-right hand corner. In the Dialog's message map, I am handling the WM_CLOSE message:
BEGIN_MSG_MAP(CMyDialog)
... Other entries
MESSAGE_HANDLER(WM_CLOSE, OnClose)
...
CHAIN_MSG_MAP(CAxDialogImpl<CMyDialog>)
END_MSG_MAP()
With OnClose() setting the Stop Event handle (previously passed to the Dialog object). Ie doing pretty much the same as the StopLog() function.
LRESULT CMyDialog::OnClose(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
::SetEvent(m_hStopEvent);
return 0;
}
If I close the log dialog with the mouse click, it goes away as before. BUT the next time I call StartLog() the dialog does what it is supposed to do and comes to the front, which is the action I want. So I replaced the StopLog() code with a SendMessage(WM_CLOSE) to my dialog: it closed the window, but again it did not reappear on top. Another difference is that using the Close X on the dialog means that the Dialog has the focus when it is closed. Closing it from the Excel button means that the Excel window has the focus.
I realize this is rather a long question, and thanks very much if you have soldiered down to the end! I'd been keen for any solution / insight.
Update: I didn't solve the problem as stated, just re-worked the code to use a modal Dialog box in the worker thread. When I am done with the dialog, I PostMessage(WM_CLOSE) from the main thread: the dialog ends and the worker thread finishes (having set an event to say it is done, so that the thread is not destroyed before the Dialog is cleaned up).
The dialog polls the stack of strings to display in response to a WM_USER+xxx message, posted from the main thread using PostMessage();
I still have the same issue that the dialog doesnt appear on top the second time I run the worker thread, but this time adding a ShowWindow(SW_SHOW) in the OnInitDialog() handler seems to bring the dialog to the top when it appears.
It also means I don't need my own message loop.

How to keep UI responsive when consuming items produced by background thread producer?

I've offloaded a long-running, synchronous, operation to a background thread. It takes a while to get going, but eventually it starts producing items very nicely.
The question is then how to consume then - while maintaining a responsive UI (i.e. responding to Paint and UserInput messages).
One lock-free example sets up a while loop; we consume items while they are items to consume:
// You call this function when the consumer receives the
// signal raised by WakeConsumer().
void ConsumeWork()
{
Thing item;
while ((item = InterlockedGetItemOffTheSharedList(sharedList)) != nil)
{
ConsumeTheThing(item);
}
}
The problem is that the background thread, once it gets going, can produce the items very quickly. This means that my while loop will never have a chance to stop. That means it will never go back to the message queue to respond to pending paint and mouse input events.
I've turned my asynchronous multi-threaded application in a synchronous wait as it sits inside:
while (StuffToDo)
{
Consume(item);
}
Posting Messages
Another idea is to have the background thread PostMessage a message to the main thread every time an item is available:
ProduceItemsThreadMethod()
{
Preamble();
while (StuffToProduce())
{
Thing item = new Item();
SetupTheItem(item);
InterlockedAddItemToTheSharedList(item);
PostMessage(hwndMainThreadListener, WM_ItemReady, 0, 0);
}
}
The problem with this is that any posted message is always higher priority than any:
paint messages
mouse move messages
So as long as there is posted messages available, my application will not be responding to paint and input messages.
while GetMessage(out msg)
{
DispatchMessage(out msg);
}
Every call to GetMessage will return a fresh WM_ItemReady message. My Windows message processing will be flooded with ItemReady messages - preventing me from processing paints until all the items have been added.
I've turned my asynchronous multi-threaded application in a synchronous wait.
Limiting the number of posted messages doesn't help
The above is actually worse than the first variation, because we flood the main thread with posted messages. What we want to do is only post a message if the main thread hasn't dealt with the previous message we posted. We can create a flag that is used to indicate if we've already posted a message, and if the main thread still hasn't processed it
ProduceItemsThreadMethod()
{
Preamble();
while (StuffToProduce())
{
Thing item = new Item();
SetupTheItem(item);
InterlockedAddItemToTheSharedList(item);
//Only post a message if the main thread has a message waiting
int oldFlagValue = Interlocked.Exchange(g_ItemsReady, 1);
if (oldFlagValue == 0)
PostMessage(hwndMainThreadListener, WM_ItemReady, 0, 0);
}
}
And in the main thread we clear the "ItemsReady" flag when we've processed the queued items:
void ConsumeWork()
{
Thing item;
while ((item = InterlockedGetItemOffTheSharedList(sharedList)) != nil)
{
ConsumeTheThing(item);
}
Interlocked.Exchange(g_ItemsReady, 0); //tell the thread it can post messages to us again
}
The problem again is that the thread can fill the list faster than we can consume it; so we never get a change to fall out of the ConsumeWork() function in order to handle user input.
As soon as ConsumeWork returns, the background producer thread generates a new WM_ItemReady message. The very next time i call GetMessage
while GetMessage(out msg)
{
DispatchMessage(out msg);
}
it will be a WM_itemReady message. I will be stuck in a loop.
I've turned my asynchronous multi-threaded application in a synchronous wait.
Limiting ourselves to a count of items doesn't help
We could try forcing a break out of the while loop after, say, processing 100 items:
void ConsumeWork()
{
int itemsProcessed = 0;
Thing item;
while ((item = InterlockedGetItemOffTheSharedList(sharedList)) != nil)
{
ConsumeTheThing(item);
itemsProcessed += 1;
if (itemsProcessed >= 250)
break;
}
Interlocked.Exchange(g_ItemsReady, 0); //tell the thread it can post messages to us again
}
This suffers from the same problem as the previous incarnation. Although we will leave the while loop, the very next message we will recieve will again be the WM_ItemReady:
while (GetMessage(...) != 0)
{
TranslateMessge(...);
DispatchMessage(...);
}
that's because WM_PAINT messages will only appear if there are no other messages. And the thread is itching to create a new WM_ItemReady message and post it in my queue.
Pumping the message loop myself?
Some people cry a little inside when they see people manually pumping messages to fix unresponsive applications. So lets try manually pumping messages to fix unresponsive applications!
void ConsumeWork()
{
Thing item;
while ((item = InterlockedGetItemOffTheSharedList(sharedList)) != nil)
{
ConsumeTheThing(item);
ManuallyPumpPaintAndInputEvents();
}
Interlocked.Exchange(g_ItemsReady, 0); //tell the thread it can post messages to us again
}
I won't go into the details of that function, because it leads to the re-entrancy problem. If the user of my library happens to try to close the window they're on, destroying my helper class with it, i will suddenly come back to execution inside a class that has been destroyed:
ConsumeTheThing(item);
ManuallyPumpPaintAndInputEvents(); //processes WM_LBUTTONDOWN messages will closes the window which destroys me
InterlockedGetItemOffTheSharedList(sharedList) //sharedList no longer exist BOOM
Down and down I go
I keep going in circles trying to solve the problem of how to maintain a responsive UI when using background threads. I've tinkered with four solutions in this question, and three others before asking it.
I can't be the first person to have used the Producer-Consumer model in a user interface.
How do you maintain a responsive UI?
If only i could post a message with priority lower than Paint, Input, and Timer :(

Disable cursor changing to SizeWE for some items in Win32 header

I need to prevent resizing of some items in a Win32 header control. No problem to process the HDN_BEGINTRACK notification message and cancel it - the problem is in the cursor indicating that the item can be resized. For instance, if the first item can't be resized, I see this:
, but I'd prefer to see this:
I can ignore the cursor change by suppressing the WM_SETCURSOR message, but the problem is how to know the header item WM_SETCURSOR is generated for. I can detect the item under the mouse pointer in WM_MOUSEMOVE using the HDM_HITTEST message, but WM_MOUSEMOVE is sent to window procedure only after WM_SETCURSOR. I analyzed all notification messages for the Win32 header control, and it seems, it does not have an equivalent of the MouseEnter event that is sent to the window procedure before WM_SETCURSOR.
Any ideas how to solve this problem?
You need to sub-class the header control if you haven't already.
In the sub-class, intercept the WM_SETCURSOR message, and use GetMessagePos() to get the coordinates of the mouse. These are in screen coordinates, so you need to convert them to client coordinates for the header control hit test.
// in the window sub-class
if (uMsg == WM_SETCURSOR)
{
DWORD dwPos = GetMessagePos();
HDHITTESTINFO hti;
hti.pt.x = GET_X_LPARAM(dwPos);
hti.pt.y = GET_Y_LPARAM(dwPos);
ScreenToClient(hWnd, &hti.pt);
SendMessage(hWnd, HDM_HITTEST, 0, reinterpret_cast<LPARAM>(&hti));
if (...) // test for items we want to block
{
SetCursor(LoadCursor(0, IDC_ARROW));
return TRUE;
}
// pass through to regular WndProc
}

EN_UPDATE does not send to the subclassed edit box procedure

I have subclassed Edit control window procedure and then found out it no longer
sent the EN_UPDATE.
Am I missing something , and could somebody suggest me a workaround on this one?
LRESULT CALLBACK EditBoxProc_textbox3( HWND hwnd, UINT message , WPARAM wParam, LPARAM lParam )
{
int previous_position = 0 ;
WCHAR previous_text [1024];
WCHAR current_text [1024];
switch (message)
{
case WM_CREATE:
previous_text[0] = L'\0';
current_text[0] = L'\0';
break;
case EN_SETFOCUS:
// :TODO: read the current text of the textbox3 and update textbox2
// text according to it. //
Edit_Enable(hwndTextBox2,FALSE);
break;
case EN_UPDATE:
MessageBox(NULL,L"EN_UPDATE", lpszAppName,MB_OK);
GetWindowText( hwndTextBox3, current_text ,1024);
if( is_valid_textbox3(current_text))
{
wcscpy(previous_text,current_text);
previous_position = LOWORD(Edit_GetSel(hwndTextBox3));
update_textbox2(NULL);
}else
{
SetWindowText(hwndTextBox3, previous_text );
Edit_SetSel(hwndTextBox3,previous_position, previous_position);
}
break;
case EN_KILLFOCUS:
Edit_Enable(hwndTextBox2,TRUE);
break;
default:
break;
}
return CallWindowProc(edit_old_wndproc_textbox3,hwnd,message,\
wParam,lParam);
}
and then found out it no longer sent the EN_UPDATE
It never sent EN_UPDATE in the first place. It is a notification message that's actually sent as a WM_COMMAND message. And it is sent to the parent of the Edit control, not the control itself. Same goes for EN_SET/KILLFOCUS.
The design philosophy here is that an Edit control can simply be put on, say, a dialog. And the custom code that makes the dialog behave in a certain way is written in the parent window's procedure with no requirement to subclass the control. Which is fine but it makes it difficult to create a customized edit control that can have its own behavior. Or in other words, it makes it hard to componentize an edit control. The EN_SET/KILLFOCUS notifications are not a problem, you can simple detect their corresponding WM_SET/KILLFOCUS messages. But you'll hit the wall on EN_UPDATE, the control doesn't send any message like that to itself. Only the parent window can detect it.
Componentizing an edit control is pretty desirable and actively pursued by object-oriented class libraries like Winforms and Qt. They have a class wrapper for the control (TextBox, QLineEdit) that has a virtual method that can be overridden (OnTextChanged, changeEvent) so that the control can be customized into a derived class with its own behavior. And generate an event (aka signal) that anybody can subscribe to, not just the parent (TextChanged, textChanged). To make that work, the parent window needs to participate. When it gets the WM_COMMAND message, it must echo the notification back to the child control. Either by sending a special message back or by calling a virtual method on the child class.
You can of course implement this yourself as well, albeit that you are liable of reinventing such a class library. Consider using an existing one instead.

Keep rendering a 3D window during modal dialogs/opening main menu?

(I use Ogre3D for the rendering but the question should be generic.)
The problem: most 3D aplications use a cycle which iterates rendering a frame and checking for messages and processing them. However if a dialog is opened (MessageBox or similar), it blocks the execution of the thread and is running it's own message cycle, but it obviously does not call the 3D rendering function in it.
What is the preferred, or "best" way of keeping rendering the 3D scene even when dialogs are open? The normal applications do not suffer from this problem, because their re-rendering is handled by WM_PAINT messages and similar, and since modal dialogs do have internal message loop, the window proc get's called when needed and everything looks fine. In my 3D project however, "when needed" is all the time, because the window has to be updated, even without WM_PAINT messages.
The simple solution that comes to mind is to register a timer for the time when dialogs are open, and render 3D scene from the WindowProc, but is it really the best? Seems very dirty...
I don't know that this is the best way, but I think it will work.
Add a handler for WM_ENTERIDLE that uses PeekMessage to do something like:
case WM_ENTERIDLE:
while (!PeekMessage())
{
DoYourRendering();
}
return 0;
I would suggest having the code post a custom message to itself when entering the modal operation. You can then render the current frame when the modal loop dispatches the message, and then post another message to keep a rendering loop running. Once the modal operation finishes, you can stop posting messages to yourself and go back to your normal rendering logic. For menus, you can catch the WM_ENTERMENULOOP and WM_EXITMENULOOP messages to detect when the modal menu message loop begins and ends.
For example:
const UINT WM_RENDER_FRAME = WM_USER+100:
.
BOOL m_InModalOp = FALSE;
.
case WM_ENTERMENULOOP:
m_InModalOp = TRUE;
PostMessage(hwnd, WM_RENDER_FRAME, 0, 0);
break;
case WM_EXITMENULOOP:
m_InModalOp = FALSE;
break;
case WM_RENDER_FRAME:
if (m_InModalOp)
{
// render a frame...
PostMessage(hwnd, WM_RENDER_FRAME, 0, 0);
}
break;
.
m_InModalOp = TRUE;
PostMessage(hwnd, WM_RENDER_FRAME, 0, 0);
MessageBox(...);
m_InModalOp = FALSE;

Resources