主窗口关闭后,如何防止Win32应用程序在后台运行?

Arc*_*des 4 c++ windows winapi visual-c++

我是Win32 API的初学者,但我对C++有中等经验.出于学习目的,我根据参考资料,教程和示例创建了一个非常简单的Win32应用程序.

问题是,在主窗口关闭后,其进程仍然在后台运行.我怎么能阻止这个?在我的WndProc函数中,我确实有一个带有DestroyWindow的WM_DESTROY案例,但它似乎没有做到这一点.代码如下:

#include <cstdio>
#include <cstdlib>

#ifdef UNICODE
#include <tchar.h>
#endif

#include <Windows.h>

HINSTANCE hinst;
HWND hwnd;

LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);

#ifdef UNICODE
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
#else
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
#endif
{
    MSG msg;
    WNDCLASSEX mainclass;
    BOOL bRet;
    UNREFERENCED_PARAMETER(lpCmdLine);

    mainclass.cbSize =          sizeof(WNDCLASSEX);
    mainclass.style =           CS_VREDRAW | CS_HREDRAW;
    mainclass.lpfnWndProc =     (WNDPROC) WndProc;
    mainclass.cbClsExtra =      NULL;
    mainclass.cbWndExtra =      NULL;
    mainclass.hInstance =       hInstance;
    mainclass.hIcon =           NULL;
    mainclass.hCursor =         LoadCursor(NULL, IDC_ARROW);
    mainclass.hbrBackground =   (HBRUSH) COLOR_WINDOW;
    mainclass.lpszMenuName =    NULL;
    mainclass.lpszClassName =   TEXT("MainWindowClass");
    mainclass.hIconSm =         NULL;

    if (!RegisterClassEx(&mainclass))
        return FALSE;

    hinst = hInstance;

    hwnd = CreateWindowEx(
        WS_EX_WINDOWEDGE,
        TEXT("MainWindowClass"),
        TEXT("Test Window"),
        WS_CAPTION | WS_VISIBLE | WS_SIZEBOX | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX,
        CW_USEDEFAULT,
        CW_USEDEFAULT,
        CW_USEDEFAULT,
        CW_USEDEFAULT,
        NULL,
        NULL,
        hinst,
        NULL);

    ShowWindow(hwnd, nCmdShow);
    UpdateWindow(hwnd);

    while ((bRet = GetMessage(&msg, NULL, 0, 0)) != 0)
    {
        if (bRet != -1)
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }
    return (int) msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    PAINTSTRUCT ps;
    switch(uMsg)
    {
    case WM_DESTROY:
        DestroyWindow(hwnd);
        break;
    case WM_PAINT:
        BeginPaint(hwnd, &ps);
        EndPaint(hwnd, &ps);
        break;
    default:
        return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

jco*_*der 9

不要打电话DestroyWindow().该消息告诉您窗口已被销毁.打电话PostQuitMessage(0)退出申请.