• 多线程实现消息通信


    多线程实现消息通信

    在测试学习线程创建及通信过程中,测试多种方式,感觉此种较为简单易懂实用

    #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
    ", hThread, hCurrentProc);
        
        return 0;
    }
    
    DWORD  WINAPI ThreadFun(LPVOID lpParam)
    {
        info* Info = (info*)lpParam;//传递的消息结构体
        printf("Thread Start!!!!!
    ");
        
        printf("ThreadID %d
    ", Info->dwThreadId);//
        MSG msg;
        
        info mInfo;
        mInfo.dwThreadId = GetCurrentThreadId();
        
        HANDLE hThread1 = CreateThread(NULL,0, Thread1, &mInfo, NULL, NULL);
        printf("SomeThing %s
    ", Info->thing);
    
    //主线程实现消息检测循环,当接收退出信息退出循环
    while(1) { PeekMessage(&msg, NULL, 0, 0, PM_REMOVE); if(msg.message == WM_QUIT) { printf(" Get message(Quit) from Thread1 "); CloseHandle(hThread1); break; } } printf("Thread Over! "); return 0; } //子线程 DWORD WINAPI Thread1(LPVOID lpParam) { info* Info = (info*)lpParam; printf(" Thread1 Start!!!!! "); printf(" This ThreadID(%d) is MainThreadID!!!!! ", Info->dwThreadId); printf(" Thread1ID %d ", GetCurrentThreadId()); int ret = PostThreadMessage(Info->dwThreadId, WM_QUIT, NULL, NULL); if(ret == ERROR_INVALID_THREAD_ID) printf(" postthreadmessage Fail!!!!! "); else printf(" ret: 0x%08x ", ret); return 0; }
    ded3
  • 相关阅读:
    Stream 和 byte[] 之间的转换
    C# Process类_进程_应用程序域与上下文之间的关系
    C# Process类_进程管理器Demo
    C# attribute_特性
    SqlDataAdapter类
    SqlDataReader类
    SqlCommand类
    SqlConnection类
    DataTable类
    C# 语法技巧_三目运算_switch_case
  • 原文地址:https://www.cnblogs.com/dedeblog/p/6134395.html
Copyright © 2020-2023  润新知