Reputation: 626
I have a modeless dialog box running in a separate thread. I want to update this dialog box from my main program. I tried with creating custom message UPDATE = 0x8001 (in this range WM_APP - 0xBFFF) and associated handler for that message and calling postthreadmessage(). But that is not working. My code look like this.
int _tmain(int argc, _TCHAR* argv[])
{
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), SW_SHOW))
{
std::cout<<"Fatal Error: MFC initialization failed\n";
}
else
{
std::thread th2(ModelessThreadFunc);
DWORD thid = GetThreadId(th2.native_handle());
std::cout<<PostThreadMessage(thid,UPDATE,0,0);
th2.join();
}
return 0;
}
int ModelessThreadFunc()
{
dialog *dial = new dialog;
assert(dial->Create(dialog::IDD));
dial->ShowWindow(SW_SHOWNORMAL);
MSG msg;
while((::GetMessage(&msg, NULL, 0,0) != 0))
{
::peekmessage(&msg,NULL,0x8000,0x8002,0x0001);
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
return 0;
}
Can anyone explain problem with above logic? My aim is to update dialog box outside its thread. Any more ideas are welcome. Thank you.
Upvotes: 0
Views: 443
Reputation: 10415
PostThreadMessage is documented to fail if the destination thread creates any windows. You should PostMessage to the dialog HWND. You might also need to use AfxBeginThread instead of std::thread because you need the MFC message pump that is built in to CWinThread.
In general, the approach you are taking is not recommended. All GUI should be in the main thread, and secondary threads used for time-consuming operations. This avoids many awkward problems.
Upvotes: 1