8 out of 16 rated this helpful - Rate this topic

Module 1. Your First Windows Program

In this module, we will write a minimal Windows program. All it does is create and show a blank window. This first program contains about 50 lines of code, not counting blank lines and comments. It will be our starting point; later we'll add graphics, text, user input, and other features.

 

Screen shot of the example program

Screen shot of the example program

 

Here is the complete code for the program:


#ifndef UNICODE
#define UNICODE
#endif 

#include <windows.h>

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow)
{
    // Register the window class.
    const wchar_t CLASS_NAME[]  = L"Sample Window Class";
    
    WNDCLASS wc = { };

    wc.lpfnWndProc   = WindowProc;
    wc.hInstance     = hInstance;
    wc.lpszClassName = CLASS_NAME;

    RegisterClass(&wc);

    // Create the window.

    HWND hwnd = CreateWindowEx(
        0,                              // Optional window styles.
        CLASS_NAME,                     // Window class
        L"Learn to Program Windows",    // Window text
        WS_OVERLAPPEDWINDOW,            // Window style

        // Size and position
        CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,

        NULL,       // Parent window    
        NULL,       // Menu
        hInstance,  // Instance handle
        NULL        // Additional application data
        );

    if (hwnd == NULL)
    {
        return 0;
    }

    ShowWindow(hwnd, nCmdShow);

    // Run the message loop.

    MSG msg = { };
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return 0;
}

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;

    case WM_PAINT:
        {
            PAINTSTRUCT ps;
            HDC hdc = BeginPaint(hwnd, &ps);

            FillRect(hdc, &ps.rcPaint, (HBRUSH) (COLOR_WINDOW+1));

            EndPaint(hwnd, &ps);
        }
        return 0;

    }
    return DefWindowProc(hwnd, uMsg, wParam, lParam);
}


You can download the complete Visual Studio project from Windows Hello World Sample.

It may be useful to give a brief outline of what this code does. Later topics will examine the code in detail.

  1. wWinMain is the program entry point. When the program starts, it registers some information about the behavior of the application window. One of the most important items is the address of a function, named WindowProc in this example. This function defines the behavior of the window—its appearance, how it interacts with the user, and so forth.
  2. Next, the program creates the window and receives a handle that uniquely identifies the window.
  3. If the window is created successfully, the program enters a while loop. The program remains in this loop until the user closes the window and exits the application.

Notice that the progam does not explicitly call the WindowProc function, even though we said this is where most of the application logic is defined. Windows communicates with your program by passing it a series of messages. The code inside the while loop drives this process. Each time the program calls the DispatchMessage function, it indirectly causes Windows to invoke the WindowProc function, once for each message.

In This Section

Related Topics

Learn to Program for Windows in C++
Windows Hello World Sample

 

 

Send comments about this topic to Microsoft

Build date: 10/5/2010

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
wWinMain Never accessed.
Had to add:
#pragma comment(linker, "/SUBSYSTEM:WINDOWS")
After the includes, for it to work.
Using Microsoft Visual C++ 2010 Express.

This is because you diden't create a win32 project. This example is almost identical to the designer generated Win32 project in vs 2010 express. This example however is just more direct, with less error checking, and less structure. (note im talking C structure not so much about C++ structure :) )
Why so buggy?
Why is the first example all buggy and messed up with VS2010? Doesn't inspire me to continue
Why so buggy?
Why is the first example all buggy and messed up with VS2010? Doesn't inspire me to continue
Icon should be included in WNDCLASS struct
The window will not load a default icon and will just fall back to whichever was used last.

wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
Compiling error
I had to
#define UNICODE

before including <windows.h> to get the code to compile in VS2010.


Visual Studio project conversion
If you use VS 2010 to open this project, you will be prompted to use the conversion wizard to update it.$0 Note that since the project is distributed in a 'zip' file, you should not attempt to open the project from the 'zip', because it will not be writable.$0 Unzip the file first, then open it from that location.
(Netbeans + mingw) linker error
Hi,
For this example I used Netbeans 6.8 + mingw compiler (bundled with Qt 2010.02.1 Kit) and got the linker error: <undefined reference to `WinMain@16'>.  To make it work I had to make two changes in wWinMain function: 1) change function name to "WinMain", and 2) replace "PWSTR" with "LPSTR". The application ran, however in the window name there was "L" instead of "Sample Window Class".
Could anyone share how to fix this error?
Best Regards,
CM
I have to kill the procedure from the Task Manager Procedure List
I built these code using Visual C++ 2010 Express Edition in Windows 7.
But I find I have to kill the procedure form the Task Manager Procedure When the program is running and I want to quit.
If I do not do so and just close the window. The Visual C++ 2010 is unable to write the executable file.
I wonder why the procedure can not quit normally.
--------------------
I have find the answer.
I attemp these code not using copy paste style. I typed every line after I read these code without reference msdn line by line.
There is a mistake when I typing my code:
I wrongly typed "GetMessage(&msg,hwnd,0,0)" when I should type "GetMessage(&msg, NULL, 0, 0)".
Maybe this cause the WM_DESTROY message is ignored.
Might happen to you.
I was unable to get the code just by cutting and pasting. I had to change my wWinMain function to WinMain. I am not sure why.
Compiling Errors - Missing UNICODE and Directory Path(s)

As mentioned in the previous post,

#ifndef UNICODE
#define UNICODE
#endif

are missing from the downloadable file for this lesson and need to be added before it will compile.

I also had problems with converting this Solution to use with Visual C++ 2010.  There seemed to be problems with the "default" directories when converting the Project file.  (I also recently loaded Windows SDK 7 from ISO image 7.1 which may have done something to the directory paths...)

As a last attempt I was finally able to get the program to compile by opening "HelloWorld.sln" as a new project from existing code with the menu sequence

File
New
Project From Existing Code...

and I had to give it a new name.

Now for Module 2.

ed