PostThreadMessage和GetMessage

来源:互联网 发布:windows phone 10安卓 编辑:程序博客网 时间:2024/06/06 18:23


关于PostThreadMessage和GetMessage的一些使用记录

1.PostThreadMessage有时会失败,报1444错误(Invalid thread identifier. ) 其实这不一定是线程不存在的原因,也有可能是线程不存在消息队列(message queue)造成的。 事实上,并不是每个thread都有message queue,那如何让thread具有呢? 答案是,至少调用message相关的function一次,比如GetMessage,PeekMessage。
2.如果是post动态分配的memory给另外一个thread,要注意内存的正确释放。
3.PostThreadMessage不能够post WM_COPYDATE之类的同步消息,否则会报错
4.最好不要使用PostThreadMessage post message给一个窗口,使用PostMessage替代。
5.发现如果是主线程创建一个消息队列来接受,然后自己给自己发信息就行不通了,具体原因还不知道
6.GetMessage函数未必会成功,返回值可能返回的-1,未必是0,所以在GetMessage时,最好在外面多加一层while循环
7. GetMessage消息队列是线性的,必须处理完了一个消息才会处理下一个消息

#include "stdafx.h"#include <windows.h>#include <iostream>using namespace std;const int MAX_INFO_SIZE = 20;HANDLE hStartEvent;#define UM_MSG1 WM_USER+1#define UM_MSG2 WM_USER+2static UINT WrkThrd(LPVOID lpParam){    DWORD dwThreadID =*(DWORD *)lpParam;    MSG msg;    PeekMessage(&msg, NULL, UM_MSG1, UM_MSG2, PM_NOREMOVE);      if(!SetEvent(hStartEvent)) //set thread start event     {        printf("set start event failed,errno:%d\n",::GetLastError());        return 1;    }    char * pInfo = NULL;    while(GetMessage(&msg,0,0,0)) //get msg from message queue    {        switch(msg.message)        {        case UM_MSG1:            pInfo = (char *)msg.wParam;            printf("recv %s\n",pInfo);            delete[] pInfo;            PostThreadMessage(GetCurrentThreadId(), UM_MSG2, 0,0);            Sleep(5000);            break;        case UM_MSG2:            printf("recv UM_MSG2\n");            break;        }    }    return 0;}int _tmain(int argc, _TCHAR* argv[]){    MSG msg;    hStartEvent = ::CreateEvent(0,FALSE,FALSE,0);    hStartEvent = ::CreateEvent(0,FALSE,FALSE,0); //create thread start event    if(hStartEvent == 0)    {        printf("create start event failed,errno:%d\n",::GetLastError());        return 1;    }    DWORD threadID = GetCurrentThreadId();    DWORD threadsubID;    HANDLE hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)WrkThrd, &threadID, 0, &threadsubID);    if (!hThread)    {        printf("start thread failed,errno:%d\n",::GetLastError());        CloseHandle(hStartEvent);    }    ::WaitForSingleObject(hStartEvent,INFINITE);    int count = 0;    while(true)    {        char* pInfo = new char[MAX_INFO_SIZE]; //create dynamic msg        sprintf(pInfo, "msg_%d",++count);        if(!PostThreadMessage(threadsubID, UM_MSG1, (WPARAM)pInfo,0))//post thread msg        {            printf("post message failed,errno:%d\n",::GetLastError());            delete[] pInfo;        }        Sleep(2000);    }    return 0;}
0 0
原创粉丝点击