1 #include <Windows.h>
2
3 //Forward declarations
4 bool InitMainWindow(HINSTANCE, int);
5 LRESULT CALLBACK MsgProc(HWND, UINT, WPARAM, LPARAM);
6
7 //Constants
8 const int WIDTH = 800;
9 const int HEIGHT = 600;
10
11 HWND hwnd = NULL;
12
13 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
14 {
15 //Initialize the window
16 if (!InitMainWindow(hInstance, nCmdShow))
17 {
18 return 1;
19 }
20
21 //Main message loop
22 MSG msg = {0};
23 while (WM_QUIT != msg.message)
24 {
25 if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
26 {
27 TranslateMessage(&msg);
28 DispatchMessage(&msg);
29 }
30 }
31
32 return static_cast<int>(msg.wParam);
33 }
34
35 bool InitMainWindow(HINSTANCE hInstance, int nCmdShow)
36 {
37 WNDCLASSEX wcex;
38 wcex.cbSize = sizeof(wcex);
39 wcex.style = CS_HREDRAW | CS_VREDRAW;
40 wcex.cbClsExtra = 0;
41 wcex.cbWndExtra = 0;
42 wcex.lpfnWndProc = MsgProc;
43 wcex.hInstance = hInstance;
44 wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
45 wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
46 wcex.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
47 wcex.lpszClassName = "Basic Win32 Window";
48 wcex.lpszMenuName = NULL;
49 wcex.hIconSm = LoadIcon(NULL, IDI_WINLOGO);
50
51 //Register window class
52 if (!RegisterClassEx(&wcex))
53 {
54 return false;
55 }
56
57 //Create window
58 hwnd = CreateWindow(
59 "Basic Win32 Window",
60 "Win32 Window",
61 WS_OVERLAPPED | WS_SYSMENU | WS_CAPTION,
62 GetSystemMetrics(SM_CXSCREEN) / 2 - WIDTH / 2,
63 GetSystemMetrics(SM_CYSCREEN) / 2 - HEIGHT / 2,
64 WIDTH,
65 HEIGHT,
66 (HWND)NULL,
67 (HMENU)NULL,
68 hInstance,
69 (LPVOID*)NULL);
70
71 if (!hwnd)
72 {
73 return false;
74 }
75
76 ShowWindow(hwnd, nCmdShow);
77
78 return true;
79 }
80
81 LRESULT CALLBACK MsgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
82 {
83 switch (msg)
84 {
85 case WM_DESTROY:
86 PostQuitMessage(0);
87 return 0;
88
89 case WM_CHAR:
90 switch (wParam)
91 {
92 case VK_ESCAPE:
93 PostQuitMessage(0);
94 return 0;
95 }
96 return 0;
97 }
98
99 return DefWindowProc(hwnd, msg, wParam, lParam);
100 }