gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 13:51:10 27 4
gpt4 key购买 nike

我是 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;
}

最佳答案

不要调用 DestroyWindow()。该消息告诉您您的窗口已被销毁。调用 PostQuitMessage(0) 退出应用程序。

关于c++ - 如何防止 Win32 应用程序在主窗口关闭后在后台运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9571349/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com