I'm a beginner to the Win32 API, but I am intermediately experienced with C++. For learning purposes, I created, according to references, tutorials, and examples, a very simple Win32 application.
The problem is, after the main window is closed, its process still runs in the background. How can I prevent this? In my WndProc function, I do have a WM_DESTROY case with DestroyWindow, but it doesn't seem to be doing the trick. The code is 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;
}
Don't call DestroyWindow()
. The message is telling you that your window has already been destroyed. Call PostQuitMessage(0)
to quit the application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With