DEV Community

podboq
podboq

Posted on

PostMessage: worker thread post message to UI thread

Synopsis

PostMessage is one function of Windows API,worker thread can post message to UI thread via PostMessage

BOOL PostMessage(
HWND hWnd, //target window hand
UINT Msg, //message type, case in callback WndProc
WPARAM wParam, //true message
LPARAM lParam //true message
);

Demo code

#include <windows.h>

#define WM_RESULT (WM_USER + 1)

static HWND g_hWnd = NULL;
static HWND g_hStatic = NULL;

DWORD WINAPI WorkerThread(LPVOID)
{
    int sum = 0;
    for (int i = 1; i <= 100; ++i)
    {
        sum += i;
    }
    Sleep(1000);
    PostMessage(g_hWnd, WM_RESULT, (WPARAM)sum, 0);
    return 0;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wp, LPARAM lp)
{
    switch (msg)
    {
    case WM_CREATE:
    {
        g_hStatic = CreateWindowA("STATIC", "RESULT:waiting...", WS_CHILD | WS_VISIBLE, 20, 70, 260, 24, hWnd, NULL, NULL, NULL);
        CreateThread(NULL, 0, WorkerThread, NULL, 0, NULL);
    }
    break;

    case WM_COMMAND:
        if (LOWORD(wp) == 1)
        {
            CreateThread(NULL, 0, WorkerThread, NULL, 0, NULL);
        }
        break;

    case WM_RESULT:
    {
        char buf[64];
        wsprintfA(buf, "RESULT:%d", (int)wp);
        SetWindowTextA(g_hStatic, buf);
    }
    break;

    case WM_DESTROY:
        PostQuitMessage(0);
        break;

    default:
        return DefWindowProcA(hWnd, msg, wp, lp);
    }
    return 0;
}

int WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR, int nCmdShow)
{
    WNDCLASSA wc = {0};
    wc.lpszClassName = "PostMsgDemo";
    wc.hInstance = hInst;
    wc.lpfnWndProc = WndProc;
    wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);
    RegisterClassA(&wc);

    g_hWnd = CreateWindowA("PostMsgDemo", "PostMessage Demo", WS_OVERLAPPEDWINDOW & ~WS_THICKFRAME, 400, 300, 320, 180, NULL, NULL, hInst, NULL);
    ShowWindow(g_hWnd, nCmdShow);
    UpdateWindow(g_hWnd);

    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return (int)msg.wParam;
}
Enter fullscreen mode Exit fullscreen mode

Complie and Run

cl /nologo PostMessage.cpp /link user32.lib kernel32.lib /subsystem:windows

Analysis

DispatchMessage is the really point where WndProc be called

while(GetMessage(&msg,NULL,0,0)){} This loop never finish on its own.This loop hangs here after program startup,processes message when they come,and just hangs when free.When you click the x in the top right corner to send WM_QUIT,and GetMessage returns False,this loop exits.I feel this loop hangs around like a trigger

Top comments (0)