I'm just trying to learn a little bit of C++ and wrote a few lines that do nothing but open a window. I've added a Message Handler too and by clicking the [X] on my window it closes as its supposed to. As the next step I wanted the Program to terminate when the [X] is clicked but it does'nt do that. Here's my code:
#include <Windows.h>
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam){
switch (msg){
case WM_CLOSE:
PostQuitMessage(88);
break;
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE pPrevInstance, LPSTR lpCmdLine, int cCmdShow) {
const auto pClassName = "M3D";
WNDCLASSEX wc = { 0 };
wc.cbSize = sizeof(wc);
wc.style = CS_OWNDC;
wc.lpfnWndProc = DefWindowProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = nullptr;
wc.hCursor = nullptr;
wc.hIcon = nullptr;
wc.hCursor = nullptr;
wc.hbrBackground = nullptr;
wc.lpszMenuName = nullptr;
wc.lpszClassName = pClassName;
RegisterClassEx(&wc);
HWND hWnd = CreateWindowEx(0, pClassName, "Fenster M3D", WS_CAPTION | WS_MAXIMIZEBOX | WS_SYSMENU, 200, 200, 640, 480, nullptr, nullptr, hInstance, nullptr);
//Fenster aufrufen
ShowWindow(hWnd, SW_SHOW);
//
//message Pumpe
MSG msg;
while (GetMessage(&msg,nullptr,0,0) > 0){
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
Can anyone tell my whats wrong and why my PostQuitMessage() wont do its job? The other threads I've found werent really helping
The problem is on this assignment:
wc.lpfnWndProc = DefWindowProc;
You are telling the message loop to dispatch messages directly to DefWindowProc()
, so your custom WndProc()
is never used, so PostQuitMessage()
is never called. DefWindowProc()
does not call PostQuitMessage()
for any message that it processes.
Change that assignment to this instead:
wc.lpfnWndProc = WndProc;
Also, per the Closing the Window documentation on MSDN, DefWindowProc()
calls DestroyWindow()
when processing WM_CLOSE
, so you should call PostQuitMessage()
in reply to WM_DESTROY
instead:
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam){
switch (msg){
case WM_DESTROY:
PostQuitMessage(88);
break;
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}