【发布时间】:2021-04-06 02:16:53
【问题描述】:
这是对 win32 初始代码的简单修改 - 从基本模板生成:
if (!InitInstance(hInstance,true)
{
return false;
}
std::thread{ [hInstance,main_thread= GetCurrentThreadId()] {
MSG msg{};
if (!InitInstance(hInstance,true)
{
return;
}
auto const current_thread{ GetCurrentThreadId() };
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_WIN32APP));
if (!AttachThreadInput(main_thread, current_thread, true))
return;
// Main message loop:
while (GetMessage(&msg, nullptr, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
AttachThreadInput(main_thread, current_thread, false);
} }.join();
创建并显示了两个窗口。但显然,发送到主线程中创建的窗口的消息不会被处理。缺什么?我在 msdn 文档和大量论坛帖子中找不到任何内容。我在论坛上只能找到很多关于SetFocus 和模态对话框的抱怨——这不是我想要的。
提前致谢。
【问题讨论】:
-
这段代码的目的是什么?你为什么要运行两个 UI 线程?为什么要将线程的输入处理机制附加在一起?
-
很少需要调用
AttachThreadInput。必要时,您已经知道它的作用。你不会打电话给它,然后问它做了什么。既然你在这里,那就是答案:AttachThreadInput is like taking two threads and pooling their money into a joint bank account, where both parties need to be present in order to withdraw any money. -
主窗口的消息没有被处理,因为主线程没有处理消息。 AttachThreadInput 之所以称为 AttachThreadInput,是因为它附加了输入状态。这不是“AttachThreadMessageProcessing”。
-
它以什么方式和具体附加什么?我需要准确而具体地了解该功能的作用;因为显然它不会做很多事情,而只会做一件事情。提供的链接没有回答我的问题。
AttachedTreadInput是做什么的?名称暗示要附加的输入是什么?我想要一个线程来处理在不同线程中创建的对象的消息队列。 -
就像函数名中所说的:它同步输入。文档说“两个线程接收到的键盘和鼠标事件都按照接收到的顺序进行处理。”如果用户在一个窗口中单击,按下一个键,然后在另一个窗口中单击,并按下第二个键,则在第一个窗口处理完第一个键事件之前,不会给第二个窗口提供第二个键事件。应用很少需要这样做。这在很大程度上是一个利基场景。 (这样做会使应用程序的响应减少,因为如果第一个窗口挂起,第二个窗口就会卡住。)
标签: c++ c winapi visual-c++