winapi - 什么时候创建消息队列?

标签 winapi

考虑以下代码:

unsigned int __stdcall func( LPVOID ) {
    LRESULT result = ::PostThreadMessage( ::GetCurrentThreadId(), 0, 0, 0 );
    return 0;
}

int wmain() {
    _beginthreadex( NULL, 0, func, NULL, 0, NULL );
    ...
}

为什么::PostThreadMessage会成功?我认为它应该失败,因为那一刻不应该创建消息队列

最佳答案

因为您正在当前线程上调用 PostThreadMessage(),所以系统能够按需创建消息队列。如果您正在调用 PostThreadMessage() 并传递调用线程以外的线程的 ID,那么如果该线程没有消息队列,它将失败。

例如,考虑以下代码变体:

unsigned int __stdcall func( LPVOID ) {
    return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
    unsigned int threadID;
    _beginthreadex( NULL, 0, func, NULL, 0, &threadID );
    LRESULT result = ::PostThreadMessage( threadID, 0, 0, 0 );
    DWORD error = ::GetLastError();
    return 0;
}

因为我们现在正试图从主线程向工作线程发送消息,result 返回 0(即错误),而 error 是设置为 ERROR_INVALID_THREAD_ID,如 documentation for PostThreadMessage() 所述.

If the function fails, the return value is zero. To get extended error information, call GetLastError. GetLastError returns ERROR_INVALID_THREAD_ID if idThread is not a valid thread identifier, or if the thread specified by idThread does not have a message queue.

关于winapi - 什么时候创建消息队列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6677633/

相关文章:

c++ - 文件关闭通知

winapi - Win32 API 特有的功能?

c++ - 如何更改复选框属性? C++/VS

multithreading - Win32 : ReadFileEx() on STD_IN_HANDLE blocks, 为什么?

c++ - 如何仅 Hook Windows API 上的键盘焦点

c++ - 在C++中编写控制台的问题

c# - 获取任务栏中所有窗口的句柄

控制台图形帮助!

winapi - Win32 控制台——退格到最后一行

c++ - 它是 Winapi 的 WIC(Windows 镜像组件)和 DirectX 部分吗?