Reputation: 148
I have been following a tutorial for directx programming, and It starts off with learning how to program a window.
So far I have this and it creates a blank window:
#if _WIN32_WINNT < 0x0500
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0500
#endif
#define _UNICODE
#define UNICODE
#include <windows.h>
#include <windowsx.h>
#include <iostream>
using namespace std;
LRESULT CALLBACK WindowProc(HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow){
HWND hWnd;
WNDCLASSEX wc;
ZeroMemory(&wc, sizeof(WNDCLASSEX));
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
wc.lpszClassName = L"WindowClass1";
RegisterClassEx(&wc);
hWnd = CreateWindowEx(NULL,
L"WindowCLass1",
L"Window Program",
WS_OVERLAPPEDWINDOW,
300,
300,
500,
400,
NULL,
NULL,
hInstance,
NULL);
ShowWindow(hWnd, nCmdShow);
//ShowWindow( GetConsoleWindow(), SW_HIDE );
MSG msg;
while(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WindowProc(HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam)
{
switch(message)
{
case WM_DESTROY:
{
//ShowWindow( GetConsoleWindow(), SW_RESTORE );
PostQuitMessage(0);
return 0;
}break;
}
return DefWindowProc (hWnd, message, wParam, lParam);
}
So far I understand it, up until the getmessage loop. I know that it receives a windows msg and translates it to a readable one and sends it to be processed by the window proc function. But, I don't understand how the window proc function doesn't end the program, and how after entering on input the program doesn't simply close. If code is executed from top to bottom, and the winmain ends before the windowproc, why is a command processed by windowproc to the be all and end all and it returns to the getmessage?
Upvotes: 0
Views: 1082
Reputation: 283793
Your message loop calls DispatchMessage
. That calls your window procedure. Then your window procedure returns, DispatchMessage
also returns, and your loop loops.
Well, that's how posted messages work. For messages sent from other threads, it's GetMessage
(or a handful of other wait functions that don't appear in your code, but might be used during default message handling) that calls the window procedure. It actually has a loop of its own, calling window procedures until it finds a posted message. Then it returns so you can inspect the message and call DispatchMessage
.
Also, a lot of different window procedures can be called by GetMessage
and DispatchMessage
, depending on to which window the message was sent or posted. Your window procedure gets called for windows associated with the window class you registered, so basically all messages sent to your main window.
Upvotes: 3