Sunday, December 6, 2009

Win32 Programming Quick Start Tutorial

To write win32 programs good idea is to use Visual Studio. It is indeed a good IDE with syntax highlighting, compiler, linker along with other features. I wrote and tested all programs in Visual Studio 2008 Professional. You can get this software from here. After downloading extract it and install.

You have to write programs creating new win32 projects. If you don’t know how to create project follow here.

WinMain Function
Win32 programs are different from ANSI C programs. There are lots of information about GUI to maintain with. Though WinAPI is strong & featureful they are bit lowlevel. They don’t have a main function. Instead they have winMain which have 4 parameters. Also return type is different. Here is the syntax:

int WINAPI WinMain(HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine,
                   int nCmdShow);

Short Description of Parameters
hInstance
      Handle to the current instance of the application.
hPrevInstance
      Handle to the previous instance of the application.
lpCmdLine
      Command line String.
nCmdShow
      Specifies how the window is to be shown. This parameter can be one of the following values.
      SW_HIDE
            Hides the window and activates another window.
      SW_MAXIMIZE
            Maximizes the specified window.
      SW_MINIMIZE
            Minimizes the specified window and activates the next top-level window in the Z order.
      SW_RESTORE
            Activates and displays the window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when restoring a minimized window.
      SW_SHOW
            Activates the window and displays it in its current size and position.
      etc..

CALLBACK Function (Windows Procedure)
To handle messages from Operating System a windows procedure is used. Actually we can give it any name and specify in the WNDCLASS class property. In our case it is WndProc.

Syntax:

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

Here is a tested program that will help you to start with. The program is well-documented.


// win32_tutorial_01.cpp

#include <windows.h>
#include <stdlib.h>
#include <string.h>
#include <tchar.h>

// Global variables

// The main window class name.
static TCHAR szWindowClass[] = _T("win32app");

// The string that appears in the application's title bar.
static TCHAR szTitle[] = _T("SA OS Win32 Tutorial");

HINSTANCE hInst;

// Forward declarations of functions included in this code module:
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

int WINAPI WinMain(HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine,
                   int nCmdShow)
{
// A class used to store general information about this application
    WNDCLASSEX wcex;

    wcex.cbSize = sizeof(WNDCLASSEX);
    wcex.style          = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc    = WndProc;
    wcex.cbClsExtra     = 0;
    wcex.cbWndExtra     = 0;
    wcex.hInstance      = hInstance;
    wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
    wcex.hCursor        = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
    wcex.lpszMenuName   = NULL;
    wcex.lpszClassName  = szWindowClass;
    wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_APPLICATION));

    // On registration failure show error and exit
    if (!RegisterClassEx(&wcex))
    {
        MessageBox(NULL,
            _T("Call to RegisterClassEx failed!"),
            _T("Win32 Tutorial"),
            NULL);

        return 1;
    }

    hInst = hInstance; // Store instance handle in our global variable

    // The parameters to CreateWindow explained:
    // szWindowClass: the name of the application
    // szTitle: the text that appears in the title bar
    // WS_OVERLAPPEDWINDOW: the type of window to create
    // CW_USEDEFAULT, CW_USEDEFAULT: initial position (x, y)
    // 500, 100: initial size (width, length)
    // NULL: the parent of this window
    // NULL: this application dows not have a menu bar
    // hInstance: the first parameter from WinMain
    // NULL: not used in this application
    HWND hWnd = CreateWindow(
        szWindowClass,
        szTitle,
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT,
        300, 280,
        NULL,
        NULL,
        hInstance,
        NULL
    );

    if (!hWnd)
    {
        MessageBox(NULL,
            _T("Call to CreateWindow failed!"),
            _T("Win32 Guided Tour"),
            NULL);

        return 1;
    }

    // The parameters to ShowWindow explained:
    // hWnd: the value returned from CreateWindow
    // nCmdShow: the fourth parameter from WinMain
    ShowWindow(hWnd, nCmdShow);
    UpdateWindow(hWnd);

    // Main message loop:
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return (int) msg.wParam;
}

//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_PAINT    - Paint the main window
//  WM_DESTROY  - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    PAINTSTRUCT ps;
    HDC hdc;
    char *inst = "Welcome to win32 programming.";

    switch (message)
    {
    case WM_PAINT:
        hdc = BeginPaint(hWnd, &ps);

        // Here your application is laid out.
        // For this introduction, we just print out "Hello, World!"
        // in the top left corner.
        TextOutA(hdc, 25, 85, inst, strlen(inst));
        // End application-specific layout section.

        EndPaint(hWnd, &ps);
        break;

    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
        break;
    }

    return 0;
}


Press Ctrl + Shift + B to Build the program and then Ctrl + F5 to run the program. Download project files from here in case you cannot build and test the code yourself successfully.


Some Basics
And _T() macro is used to set L before a string to represent Unicode string. The purpose of TEXT() macro is also the same.

"P" means "pointer"
"W" means "wide"
"L" means "LONG"
"STR" means "string"
"C" means "const"

Hence,
    PWSTR means "pointer of wide string", that is, unsigned short* (or wchar_t*)
    LPSTR means "long pointer of string", that is, char*
    WCHAR means "wide char", that is, unsigned short (or wchar_t)
    LPCSTR means "const pointer of string", that is, const char* (Value assigned once cannot be altered at all)

When you are done with this program, check these links to complete your knowledge.

          WinMain on msdn
          WindowProc on msdn
          Windows Data Types

MSDN is the main source of all WinAPI programming references. Hence, match in contents is acknowledged here. When you need to understand how a winAPI function works or detail info on that go to msdn and perform a search providing the exact function name. Have fun with Windows OS.

Continue to next tips & tricks.

No comments:

Post a Comment