可以运行窗口应用程序没有消息循环

时间:2013-11-19 15:40:05

标签: c windows winapi message-queue

我有一个非常古老的应用程序,我很惊讶。此应用程序在没有消息循环的情 ( GetMessage PeekMessage )。

怎么可能?

Visual Studio编辑的示例:

HINSTANCE g_hInstance = NULL;

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);

BOOL InitInstance(HINSTANCE hInstance, int nCmdShow);

ATOM _RegisterClass(HINSTANCE hInstance);

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR    lpCmdLine,
                     int       nCmdShow)
{
    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(lpCmdLine);

    _RegisterClass(hInstance);

    InitInstance(hInstance, SW_NORMAL);

    return 0;
}

ATOM _RegisterClass(HINSTANCE hInstance)
{
    WNDCLASSEXA wcex = {0};
    wcex.cbSize = sizeof(WNDCLASSEX);
    wcex.style          = CS_SAVEBITS;
    wcex.lpfnWndProc    = WndProc;
    wcex.hInstance      = hInstance;
    wcex.lpszClassName  = "TEST_CLASS";

    ATOM a = 0;

    a =  RegisterClassExA(&wcex);

    return a;
}

BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
    HWND hWnd;

    g_hInstance = hInstance; // Store instance handle in our global variable

    hWnd = CreateWindowA("TEST_CLASS", "TEST_WINDOW", WS_OVERLAPPEDWINDOW,
        0, 0, 0, 0, NULL, NULL, hInstance, NULL);

    if (!hWnd)
    {
        return FALSE;
    }

     SendMessageW(hWnd, WM_USER, 111, 0);

    return TRUE;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    int wmId, wmEvent;
    PAINTSTRUCT ps;
    HDC hdc;

    switch (message)
    {
    case WM_CREATE:
        OutputDebugStringA("Create called.\n");
        break;

case WM_USER:
    {
        if (wParam == 111)
        {

            OutputDebugStringA("User called.\n");
        }
    }
            break;

    case WM_DESTROY:
        OutputDebugStringA("Destroy called.\n");
        break;

    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

DEBUG OUTPUT:

创建被叫。 用户叫。 毁灭叫。 程序'[2152] Test.exe:Native'已退出,代码为0(0x0)。

1 个答案:

答案 0 :(得分:2)

这是预期的行为。

CreateWindow调用SendMessageWM_NCCREATEWM_CREATE发送到正在创建的窗口。 SendMessage表现如下(引自MSDN):

  

如果指定的窗口是由调用线程创建的,则窗口过程将作为子例程立即调用。

您的程序调用{​​{1}},随后调用您的窗口过程(在CreateWindow上输出“Create called”)然后返回。它验证窗口句柄是否为非空(在这种情况下),并返回退出代码0而不是输入消息泵。
它不会输出“Destroy called”(正如您可能预期的那样)因为没有发生。窗口没有被销毁(好吧,最终它是,由操作系统),程序才会退出。

关于已修改的代码:
新代码在调用WM_CREATE时有所不同,后者再次直接调用窗口过程。因此,尽管没有消息泵,但仍会收到用户消息 似乎破坏信息现在也通过了,这无疑是有点令人惊讶的。不知道原因是什么。

请注意,窗口是使用“A”函数创建的,因此通常不建议调用“W”函数(即使它似乎在“工作”)。