多线程实现消息通信
在测试学习线程创建及通信过程中,测试多种方式,感觉此种较为简单易懂实用
#include <stdio.h> #include <windows.h> struct info { HWND hWnd; DWORD dwThreadId; char* thing; }; DWORD WINAPI ThreadFun(LPVOID lpParam);// Main Thread DWORD WINAPI Thread1(LPVOID lpParam); // Sub Thread int main() { info Info; char th[] = "somthing"; Info.hWnd = GetActiveWindow();//GetSafeHwnd(); // get current HWND Info.thing = th; DWORD dwThreadID; HANDLE hThread = CreateThread(NULL,0, ThreadFun,&Info, NULL,&dwThreadID); Info.dwThreadId = dwThreadID; WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); HANDLE hCurrentProc = GetCurrentProcess(); printf("%08X %08X\n", hThread, hCurrentProc); return 0; } DWORD WINAPI ThreadFun(LPVOID lpParam) { info* Info = (info*)lpParam;//传递的消息结构体 printf("Thread Start!!!!!\n"); printf("ThreadID %d\n", Info->dwThreadId);// MSG msg; info mInfo; mInfo.dwThreadId = GetCurrentThreadId(); HANDLE hThread1 = CreateThread(NULL,0, Thread1, &mInfo, NULL, NULL); printf("SomeThing %s\n", Info->thing); //主线程实现消息检测循环,当接收退出信息退出循环 while(1) { PeekMessage(&msg, NULL, 0, 0, PM_REMOVE); if(msg.message == WM_QUIT) { printf("\nGet message(Quit) from Thread1\n\n"); CloseHandle(hThread1); break; } } printf("Thread Over!\n"); return 0; } //子线程 DWORD WINAPI Thread1(LPVOID lpParam) { info* Info = (info*)lpParam; printf("\n\tThread1 Start!!!!!\n"); printf("\tThis ThreadID(%d) is MainThreadID!!!!!\n", Info->dwThreadId); printf("\tThread1ID %d\n", GetCurrentThreadId()); int ret = PostThreadMessage(Info->dwThreadId, WM_QUIT, NULL, NULL); if(ret == ERROR_INVALID_THREAD_ID) printf("\tpostthreadmessage Fail!!!!!\n"); else printf("\tret: 0x%08x\n", ret); return 0; }
时间: 2024-09-29 23:56:00