MFC Send message to MAIN thread (rather than a win

2019-08-14 02:12发布

问题:

I'm writing a GUI application for Windows using MFC and C++.

So I need to send messages to my MAIN thread from my worker thread to tell it to update my GUI. However I'm not sure how to send a message to the actual MAIN thread rather than a Window. As it is I can see it is in the MAIN thread when it receives the message but I am not sure if this is guaranteed or just luck.

In worker:

PostMessage( *myTestToolDlg, WM_YOU_HAVE_DATA,UPDATE_GUI, 0 );

In application window:

LRESULT CTestToolDlg::OnData(WPARAM wp, LPARAM )

Does this somehow mean that?

回答1:

You can get your main thread's thread id by using something like threadId = GetCurrentThreadId(); in the main thread, and then send a message to it by calling PostThreadMessage(threadId, ...) from your worker thread.

However, as Hans Passant said -> here <-, you should avoid using PostThreadMessage to send messages to UI threads, and should better send messages to its window.