简体   繁体   English

MFC 向主线程(而不是窗口)发送消息?

[英]MFC Send message to MAIN thread (rather than a window)?

I'm writing a GUI application for Windows using MFC and C++.我正在使用 MFC 和 C++ 为 Windows 编写 GUI 应用程序。

So I need to send messages to my MAIN thread from my worker thread to tell it to update my GUI.所以我需要从我的工作线程向我的主线程发送消息,告诉它更新我的 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?这是否意味着什么?

You can get your main thread's thread id by using something like threadId = GetCurrentThreadId();您可以使用threadId = GetCurrentThreadId();类的东西来获取主线程的线程 ID threadId = GetCurrentThreadId(); in the main thread , and then send a message to it by calling PostThreadMessage(threadId, ...) from your worker thread .主线程中,然后通过从您的工作线程调用PostThreadMessage(threadId, ...)向其发送消息。

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.但是,正如 Hans Passant 所说 -> 此处<-,您应该避免使用PostThreadMessage向 UI 线程发送消息,而应该更好地向其窗口发送消息。

If you want to modify a ListBox or ListView directly, you can use SendDlgItemMessageA()如果你想直接修改一个ListBox或者ListView,可以使用SendDlgItemMessageA()

Example :例子 :

char const* pChar = "My text to be updated";

SendDlgItemMessageA(hWindow, IDC_LISTBOX, LB_DELETESTRING, 0, 0);

SendDlgItemMessageA(hWindow, IDC_LISTBOX, LB_INSERTSTRING, -1, (LPARAM)pChar);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM