Lesson 2 - Creating a basic window
In this lesson you will be introduced to the event-driven programming model. You will learn how Windows uses messages to communicate with applications, how event based programming works, what callback functions are, and while doing this create a basic windows application.

Before you begin
If you do not have the platform SDK help files (WinAPI docs), download the win32.hlp file. Though old, it is a valuable resource. Or you can download the Platform SDK form msdn.
Begin
Add the following code to main.cpp:
main.cpp1 /* DrawLite - Windows Programming Tutorial 2 * by Pravin Paratey (March 08, 2007) 3 * 4 * Source released under 5 * Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 6 * http://creativecommons.org/licenses/by-nc-nd/3.0/ 7 */ 8 9 #include <windows.h> 10 11 LRESULT CALLBACK MainWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); 12 13 int WINAPI 14 WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmdLine, int nCmdShow) 15 { 16 MSG msg; 17 HWND hwnd; 18 WNDCLASSEX wcx; 19 20 wcx.cbSize = sizeof(WNDCLASSEX); // Must always be sizeof(WNDCLASSEX) 21 wcx.style = CS_DBLCLKS; // Class styles 22 wcx.lpfnWndProc = MainWndProc; // Pointer to callback procedure 23 wcx.cbClsExtra = 0; // Extra bytes to allocate following the wndclassex structure 24 wcx.cbWndExtra = 0; // Extra bytes to allocate following an instance of the structure 25 wcx.hInstance = hInst; // Instance of the application 26 wcx.hIcon = LoadIcon(NULL, IDI_APPLICATION); // Class Icon 27 wcx.hCursor = LoadCursor(NULL, IDC_ARROW); // Class cursor 28 wcx.hbrBackground = (HBRUSH) (COLOR_WINDOW); // Background brush 29 wcx.lpszMenuName = NULL; // Menu Resource 30 wcx.lpszClassName = "DrawLite"; // Name of this class 31 wcx.hIconSm = LoadIcon(NULL, IDI_APPLICATION); // Small icon for this class 32 33 // Register this window class with MS-Windows 34 if (!RegisterClassEx(&wcx)) 35 return 0; 36 37 hwnd = CreateWindowEx(0, //Extended window style 38 "DrawLite", // Window class name 39 "Lesson 2 - A simple win32 application", // Window title 40 WS_OVERLAPPEDWINDOW, // Window style 41 CW_USEDEFAULT, CW_USEDEFAULT, // (x,y) pos of the window 42 500, 400, // Width and height of the window 43 HWND_DESKTOP, // HWND of the parent window (can be null also) 44 NULL, // Handle to menu 45 hInst, // Handle to application instance 46 NULL); // Pointer to window creation data 47 48 // Check if window creation was successful 49 if (!hwnd) 50 return 0; 51 // Make the window visible 52 ShowWindow(hwnd,SW_SHOW); 53 54 // Process messages coming to this window 55 while (GetMessage(&msg,NULL,0,0)) 56 { 57 TranslateMessage(&msg); 58 DispatchMessage(&msg); 59 } 60 61 return msg.wParam; 62 } 63 64 LRESULT CALLBACK MainWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) 65 { 66 switch(msg) 67 { 68 case WM_DESTROY: // User closed the window 69 PostQuitMessage(0); 70 break; 71 default: 72 return DefWindowProc(hwnd, msg, wParam, lParam); 73 } 74 return 0; 75 }
Phew. That was long! Press F9 to compile and run. You have a basic window on your screen!
Breaking it up
Event driven programming model
Every time windows has to communicate with your application, it sends messages to your application. Once all initializations have been done and the window shown on screen, all your application has to do is poll for windows messages.
The lines up to 54 create and show the window and the lines 57-61 poll for messages.
The GetMessage() function gets the next message to be processed from the message queue. GetMessage() returns a non-zero value for every message other than WM_QUIT. This means that the while loop continues until it is time to quit.
TranslateMessage() translates virtual key messages to character messages.
DispatchMessage() dispatches the message to a window procedure. This means that for messages coming to our window, the MainWndProc() is called by Windows through DispatchMessage().
How does Windows know which function to call? Well, we tell Windows during WNDCLASSEX initialization [line 24].
WNDCLASSEX structure
Every window that you create has an associated WNDCLASSEX structure. The WNDCLASSEX structure provides all the information necessary for Windows to do perform window related functions like drawing its icon, cursor, menu, calling the callback function which will receive messages and so on.
The WNDCLASSEX structure is defined as,
typedef struct _WNDCLASSEX { UINT cbSize; // This must always be set to sizeof(WNDCLASSEX) UINT style; // This specifies the class styles. Take a look at // your SDK documentation for the values this member can take. WNDPROC lpfnWndProc; // Pointer to the WndProc which will handle this windows messages. int cbClsExtra; // Number of extra bytes to allocate at the end of the WNDCLASSEX structure. int cbWndExtra; // Number of extra bytes to allocate at the end of the window instance. HANDLE hInstance; // Identifies the instance that the window procedure of this class is within. HICON hIcon; // Handle to the icon associated with windows of this class. HCURSOR hCursor; // Handle to the cursor for windows of this class. HBRUSH hbrBackground; // Identifies the class background brush. LPCTSTR lpszMenuName; // Identifies the menu for windows of this class. LPCTSTR lpszClassName; // Pointer to a NULL terminated string or an atom specifying the class of this structure. HICON hIconSm; // Handle to the small icon associated with this class. } WNDCLASSEX;
Registering your window class
After you've created your window class, you need to tell Windows about it. This is done by registering the class with windows. The function call is RegisterClassEx(..). Once this is done, you can create instances of this window by calling CreateWindowEx(..) with the proper arguments.
Creating the window
A window is created by calling the CreateWindowEx(..) defined as,
HWND CreateWindowEx( DWORD dwExStyle, // extended window style LPCTSTR lpClassName, // pointer to registered class name LPCTSTR lpWindowName, // pointer to window name DWORD dwStyle, // window style int x, // horizontal position of window int y, // vertical position of window int nWidth, // window width int nHeight, // window height HWND hWndParent, // handle to parent or owner window HMENU hMenu, // handle to menu, or child-window identifier HINSTANCE hInstance, // handle to application instance LPVOID lpParam // pointer to window-creation data );
Lines 39-48 create the window. If the creation was successful a non-zero handle is returned by CreateWindowEx after which ShowWindow() shows the window on the screen.
Tip: Refer to your documentation
It is a good idea to keep referring to these functions in your SDK docs while reading this tutorial.

Callback functions
A callback function is the one that receives the messages sent to your application. This is where you do something about the message. We provide a pointer to this function while defining the window class [line 18].
Callback functions have to be defined as,
LRESULT CALLBACK function-name( HWND hwnd, // Handle of window which received this message UINT msg, // The message WPARAM wParam, // Extra information LPARAM lParam // Extra information );
- HWND hwnd
- The handle of the window is specified so that you know which window to act upon. This is necessary because you may have created more than one instance of the window.
- UINT msg
- This contains the message sent.
- WPARAM wParam and WPARAM lParam
- wParam and lParam are used to pass extra info about the message. For example a WM_LBUTTONDOWN (left mouse button down) message will have the x and y co-ordinates as the upper and lower word of lParam and wParam will tell if any modifier keys (ctrl, alt, shift) have been pressed.
MainWndProc
66 LRESULT CALLBACK MainWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) 67 { 68 switch (msg) 69 { 70 ...
The switch statement lets us select which message was sent. There are over 200 messages that windows can send your application. To read about them, just search for WM_ in your SDK docs.

WM_DESTROY
69 ... 70 case WM_DESTROY: // User closed the window 71 PostQuitMessage(0); 72 break; 73 ...
The WM_DESTROY message is sent to your application when the user teminates the application either by clicking the X at the upper right corner, pressing Alt+F4, or quits the application by other means.
PostQuitMessage() causes GetMessage(..) [line 57] to return false and thus breaking out of the while loop and exiting the application. The argument to PostQuitMessage is the return value to the system.
DefWindowProc(..)
What about the other 200 or so messages? Surely you, the programmer, aren't going to write code for all the 200 messages. Fortunately, Windows provides the DefWindowProc(..) function which handles all the messages. For the purposes of displaying a simple window, your MainWndProc could very well have consisted of,
LRESULT CALLBACK MainWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { return DefWindowProc(hwnd, msg, wParam, lParam); }
What this means is that every time you want to do something about a message, add the case switch for the message and write the code which does something about it. All messages that you don't want to handle should be passed to the DefWindowProc(). This is what we have done in our code.
72 ... 73 default: // Call the default window handler 74 return DefWindowProc(hwnd,msg,wParam,lParam); 75 ...
C++ is about classes
Before we go any further, let's organize that code into a classes. This helps us manage our code better. Add a new file to the project and name it MainWindow.h. Add the following code to it:
MainWindow.h1 /* DrawLite - Windows Programming Tutorial 2 * by Pravin Paratey (March 08, 2007) 3 * 4 * Source released under 5 * Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 6 * http://creativecommons.org/licenses/by-nc-nd/3.0/ 7 */ 8 9 #include <windows.h> 10 11 class MainWindow 12 { 13 public: 14 MainWindow(HINSTANCE hInstance); 15 ~MainWindow(); 16 static LRESULT CALLBACK MainWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); 17 bool Run(int nCmdShow); 18 19 private: 20 WNDCLASSEX m_wndClass; 21 static HINSTANCE m_hInstance; 22 HWND m_hwnd; 23 static char m_szClassName[]; 24 };
Next, add another file called MainWindow.cpp with the following code:
MainWindow.cpp1 /* DrawLite - Windows Programming Tutorial 2 * by Pravin Paratey (March 08, 2007) 3 * 4 * Source released under 5 * Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 6 * http://creativecommons.org/licenses/by-nc-nd/3.0/ 7 */ 8 9 #include <windows.h> 10 #include "MainWindow.h" 11 12 char MainWindow::m_szClassName[] = "DrawLite"; 13 14 MainWindow::MainWindow(HINSTANCE hInstance) 15 { 16 m_hInstance = hInstance; // Save Instance handle 17 18 m_wndClass.cbSize = sizeof(WNDCLASSEX); // Must always be sizeof(WNDCLASSEX) 19 m_wndClass.style = CS_DBLCLKS; // Class styles 20 m_wndClass.lpfnWndProc = MainWndProc; // Pointer to callback procedure 21 m_wndClass.cbClsExtra = 0; // Extra bytes to allocate following the wndclassex structure 22 m_wndClass.cbWndExtra = 0; // Extra bytes to allocate following an instance of the structure 23 m_wndClass.hInstance = hInstance; // Instance of the application 24 m_wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); // Class Icon 25 m_wndClass.hCursor = LoadCursor(NULL, IDC_ARROW); // Class cursor 26 m_wndClass.hbrBackground = (HBRUSH) (COLOR_WINDOW); // Background brush 27 m_wndClass.lpszMenuName = NULL; // Menu Resource 28 m_wndClass.lpszClassName = m_szClassName; // Name of this class 29 m_wndClass.hIconSm = LoadIcon(NULL, IDI_APPLICATION); // Small icon for this class 30 } 31 32 MainWindow::~MainWindow() 33 { 34 } 35 36 LRESULT CALLBACK MainWindow::MainWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) 37 { 38 switch (msg) 39 { 40 case WM_DESTROY: 41 PostQuitMessage (0); 42 break; 43 default: 44 return DefWindowProc (hwnd, msg, wParam, lParam); 45 } 46 47 return 0; 48 } 49 50 bool MainWindow::Run(int nCmdShow) 51 { 52 if(!RegisterClassEx(&m_wndClass)) 53 return false; 54 m_hwnd = CreateWindowEx( 55 0, 56 m_szClassName, 57 "Draw Lite", 58 WS_OVERLAPPEDWINDOW, 59 CW_USEDEFAULT, 60 CW_USEDEFAULT, 61 500, 62 400, 63 NULL, 64 NULL, 65 m_hInstance, 66 NULL 67 ); 68 if(!m_hwnd) 69 return false; 70 ShowWindow(m_hwnd, nCmdShow); 71 return true; 72 }
Next change main.cpp to look like so:
main.cpp1 /* DrawLite - Windows Programming Tutorial 2 * by Pravin Paratey (March 08, 2007) 3 * 4 * Source released under 5 * Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 6 * http://creativecommons.org/licenses/by-nc-nd/3.0/ 7 */ 8 9 #include <windows.h> 10 #include "MainWindow.h" 11 12 int WINAPI 13 WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmdLine, int nCmdShow) 14 { 15 MSG msg; 16 17 MainWindow *winMain = new MainWindow(hInst); 18 if(!winMain->Run(nCmdShow)) 19 { 20 delete winMain; 21 return 1; // error 22 } 23 24 // Run the message loop. It will run until GetMessage() returns 0 25 while (GetMessage (&msg, NULL, 0, 0)) 26 { 27 // Translate virtual-key messages into character messages 28 TranslateMessage(&msg); 29 // Send message to WindowProcedure 30 DispatchMessage(&msg); 31 } 32 33 delete winMain; 34 35 return msg.wParam; 36 }
Adding Functionality
Lets pop up a message box which will display the co-ordinates of the point where the left mouse button was pressed. To do this you will have to handle the WM_LBUTTONDOWN message.
Add this code to MainWindow.cpp at line 44
MainWindow.cpp41 ... 42 PostQuitMessage(0); 43 break; 44 case WM_LBUTTONDOWN: 45 char str[256]; 46 POINT pt; 47 pt.x = LOWORD(lParam); 48 pt.y = HIWORD(lParam); 49 wsprintf(str,"Co-ordinates are\nX=%i and Y=%i",pt.x,pt.y); 50 MessageBox(hwnd, str, "Left Button Clicked", MB_OK); 51 break; 52 default: 53 ...
Press F9. This is what you should see when you click anywhere inside the window.

Exercise
Try this exercise. Pop up a message every time a key is pressed on the keyboard. Hint: Handle the WM_CHAR message. Remember to refer to your SDK docs.
If you could manage that, give yourself a pat on the back. You now understand the basics of event-driven programming - the mechanism which Windows uses to communicate with your application. You have crossed one of the more difficult hurdles in learning windows programming.
Don't worry if you could not do the exercise or if things are still a bit hazy. These concepts will be used in every single lesson after this and it will soon become second nature to you.