非 GUI 线程中的消息循环:
#include "stdafx.h"
#include <Windows.h>
#include <thread>
#include <iostream>
using namespace std;
void ThreadFunction()
{
MSG msg;
BOOL result;
for (;;)
{
result = GetMessage(&msg, nullptr, 0, 0);
if (result <= 0)
{
break;
}
cout << msg.message << " " << msg.wParam << " " << msg.lParam << endl;
//TranslateMessage(&msg);
//DispatchMessage(&msg);
}
}
int main()
{
thread t(ThreadFunction);
HANDLE h = t.native_handle();
DWORD dw = GetThreadId(h);
PostThreadMessage(dw, WM_APP + 1, 1, 2);
PostThreadMessage(dw, WM_APP + 2, 10, 20);
PostThreadMessage(dw, WM_QUIT, 10, 20);
t.join();
return 0;
}
更新:
根据评论,此代码未在 gcc 中编译。试图在 VC++ 中重现这一点,我发现该程序在 x64 中不起作用。这个更新的解决方案有望解决这两个问题:
#include "stdafx.h"
#include <Windows.h>
#include <thread>
#include <iostream>
using namespace std;
DWORD threadID{};
void ThreadFunction(HANDLE event_handle)
{
MSG msg;
BOOL result;
threadID = GetCurrentThreadId();
SetEvent(event_handle);
for (;;)
{
result = GetMessage(&msg, nullptr, 0, 0);
if (result <= 0)
{
break;
}
cout << msg.message << " " << msg.wParam << " " << msg.lParam << endl;
}
}
int main()
{
HANDLE e = CreateEvent(nullptr, FALSE, FALSE, nullptr);
thread t(ThreadFunction, e);
WaitForSingleObject(e, INFINITE);
CloseHandle(e);
PostThreadMessage(threadID, WM_APP + 1, 1, 2);
PostThreadMessage(threadID, WM_APP + 2, 10, 20);
PostThreadMessage(threadID, WM_QUIT, 10, 20);
t.join();
return 0;
}