How to prevent a Win32 application from starting in the background after closing the main window?

I am starting to use the Win32 API, but I have experience with C ++. For training purposes, I created, following the links, tutorials and examples, a very simple Win32 application.

The problem is that after closing the main window, its process is still running in the background. How can I prevent this? In my WndProc function, I have a WM_DESTROY case with DestroyWindow, but it doesn't seem to do the trick. Code below:

#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; } 
+4
source share
2 answers

Do not call DestroyWindow() . The message says that your window has already been destroyed. Call PostQuitMessage(0) to exit the application.

+9
source

In your WndProc add a case for WM_CLOSE and call PostQuitMessage.

 LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { case WM_CLOSE: PostQuitMessage(0); break; // other cases } 

When the user clicks the close button (or from the sys menu), Windows will display the WM_CLOSE message. This will exit the main Windows message handler. This, in turn, will ensure that your application runs correctly.

+2
source

Source: https://habr.com/ru/post/1399836/


All Articles