Wednesday, September 7, 2011

Win32 API - Part II

Creating the Window

HWND hwnd;
hwnd = CreateWindowEx(
     WS_EX_CLIENTEDGE,
     g_szClassName,
     "The title of my window",
     WS_OVERLAPPEDWINDOW,
     CW_USEDEFAULT, CW_USEDEFAULT, 240, 120,
     NULL, NULL, hInstance, NULL); 

 WS_EX_CLIENTEDGE - extended windows style

g_szClassName - tells the system what kind of window to create. We want to create window from the class we just registered. 

CW_USEDEFAULT, CW_USEDEFAULT, 240, 120, - X, Y co-ordinates and width and height of window
 
In windows, the windows on your screen are arranged in a heirarchy of parent and child
windows.  When you see a button on a window, the button is the Child and it is contained
within. the window that is it's Parent.
  
The Message Loop
Pretty much everything that your program does passes through this point of control 
while(GetMessage(&Msg, NULL, 0, 0) > 0)
{
    TranslateMessage(&Msg);
    DispatchMessage(&Msg);
}
return Msg.wParam; 
 
GetMessage() gets a message from your application's message queue. 
Any time the user moves the mouse, types on the keyboard, clicks on your window's menu, 
or does any number of other things, messages are generated by the system and entered into your 
program's message queue 
By calling GetMessage() you are requesting the next available message to be removed from the queue 
and returned to you for processing.
 
Window Procedure
This is where all the messages that are sent to our window get processed.
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch(msg)
    {
        case WM_CLOSE:
            DestroyWindow(hwnd);
        break;
        case WM_DESTROY:
            PostQuitMessage(0);
        break;
        default:
            return DefWindowProc(hwnd, msg, wParam, lParam);
    }
    return 0;
} 
Window procedure is called for each message. HWND parameter is the handle of your window.
HWND will be different for each window depending on which window it is.
WM_CLOSE is sent when the user presses the Close Button, but its good to handle this event, since this 
is the perfect spot to do cleanup checks.
DestroyWindow() the system sends the WM_DESTROY message to the window getting destroyed 
Since we want the program to exit, we call PostQuitMessage()
 

 
 

No comments:

Post a Comment