代码改变世界

简单发送线程消息

2012-11-02 09:34  龙成  阅读(161)  评论(0编辑  收藏  举报
 1 //Win32Test.cpp : 定义控制台应用程序的入口点。
 2 #include "stdafx.h"
 3 #include <iostream>
 4 #include <windows.h>
 5 #include <vector>
 6 #include <string>
 7 #include <process.h>
 8 using namespace std;
 9 
10 enum MyMsg
11 {
12     MY_MSG1=WM_USER + 100,
13     MY_MSG2,
14     MY_MSG3,
15 };
16 
17 unsigned __stdcall MyFunc(LPVOID p)
18 {
19     MSG msg;
20     PeekMessage(&msg,NULL,WM_USER,WM_USER,PM_REMOVE);
21     while(true)
22     {
23         if(GetMessage(&msg,NULL,0,0))
24         {
25             char * pInfo = (char *)msg.wParam;
26             switch(msg.message)
27             {
28             case MY_MSG1:
29                 
30                 cout << "MSG1:" << pInfo << endl;
31                 break;
32             case MY_MSG2:
33                 cout << "MSG2:" << pInfo << endl;
34                 break;
35             case MY_MSG3:
36                 cout << "MSG3:" << pInfo << endl;
37                 break;
38             default:
39                 cout << "未定义消息" << endl;
40                 break;
41             }
42         }
43     }
44     return 0;
45 }
46 
47 int _tmain(int argc, _TCHAR* argv[])
48 {
49     HANDLE hThread;
50     unsigned int nID;
51     hThread = (HANDLE)_beginthreadex(NULL, 0, &MyFunc, NULL, 0, &nID );
52     Sleep(1000);
53     char *pInfo = "。。。。消息3.。。。";
54     PostThreadMessage(nID,MY_MSG3,(WPARAM)pInfo,0);
55     Sleep(1000);
56     pInfo = "。。。。消息1.。。。";
57     PostThreadMessage(nID,MY_MSG1,(WPARAM)pInfo,0);
58     Sleep(1000);
59     pInfo = "。。。。消息2.。。。";
60     PostThreadMessage(nID,MY_MSG2,(WPARAM)pInfo,0);
61     Sleep(1000);
62     return 0;
63 }