Home > Articles > Programming > Windows Programming

Programming Paradigm

📄 Contents

  1. 1 Hello Windows!
  2. 2 Encapsulation
The following chapter is excerpted from C++ In Action: Industrial-Strength Programming Techniques (Addison Wesley, 2001).

Learn how to write your own Windows program! In the main procedure, your program will create a window of a particular class and enter the message processing loop. Then you can encapsulate your API to combine all of your arguments in one place.

A Windows program, like any other interactive program, is for the most part input-driven. However, the input of a Windows program is conveniently predigested by the operating system. When a user presses a key or moves the mouse, Windows intercepts the event, preprocesses it, and dispatches it to the appropriate user program. The program gets all its messages from Windows. It may do something about them or not—in the latter case it lets Windows do the "right" thing (the default processing).

When a Windows program starts, it registers a window class with the system (it's not a C11 class). Through this "class data structure" it gives the system, among other things, a pointer to a callback function called the window procedure. Windows will call this procedure whenever it wants to pass a message to the program and to notify it of interesting events. The name "callback" means just this: don't call Windows, Windows will call you back.

The program also gets a peek at every message in the message loop before it gets dispatched to the appropriate window procedure. In most cases, the message loop just forwards the message back to Windows to do the dispatching (see Figure 15.1).

Windows is a multitasking operating system—there may be many programs running at the same time. So how does Windows know which program should get a particular message? Mouse messages, for instance, are usually dispatched to the application that created the window over which the mouse cursor is positioned at a given moment (unless an application "captures" the mouse).

Most Windows programs create one or more windows on the screen. At any given time, one of these windows has the focus and is considered active (its title bar is usually highlighted). Keyboard messages are sent to the window that has the focus.

Figure 15.1 Input-driven Windows paradigm

Events such as resizing, maximizing, minimizing, covering, or uncovering a window are handled by Windows, although the concerned program that owns the window also gets a chance to process messages for these events. There are dozens and dozens of types of messages that can be sent to a Windows program. Each program handles the ones that it's interested in and lets Windows deal with the others.

Windows programs use Windows services to output text or graphics to the screen. Windows not only provides a high-level graphical interface, but it separates the program from the actual graphical hardware. In this sense Windows graphics are, to a large extent, device independent.

It is very easy for a Windows program to use standard Windows controls. Menus are easy to create; so are message boxes. Dialog boxes are more general—they can be designed by a programmer using a dialog editor, and icons can be created using an icon editor. List boxes, edit controls, scroll bars, buttons, radio buttons, check boxes, and so on, are all examples of built-in, ready-to-use controls that make Windows programs so attractive and usable.

All this functionality is available to the programmer through the Windows API. It is a (very large) set of C functions, typedefs, structures, and macros whose declarations are included (directly or indirectly) in <windows.h>, and whose code is linked to the program through a set of libraries and DLLs (dynamic-link libraries).

In this chapter we will be using the Code Co-op project named windows. Margin notes give the script numbers to unpack.

15.1 Hello Windows!

Our first Windows program will do nothing more than create a window with the title bar "Hello Windows!" However, it is definitely more complicated than Kernighan and Ritchie's "Hello World!" and our first "Hello!" C11 program. What we are getting here is much more than the simple old-fashioned teletype output. We are creating a window that can be moved around, resized, minimized, maximized, overlapped by other windows, and so on. It also has a standard system menu in the upper left corner. So let's not complain too much!

In Windows, the main procedure is called WinMain. It must use the WINAPI calling convention and the system calls it with the following parameters:

  • HINSTANCE hInst—The handle to the current instance of the program.

  • HINSTANCE hPrevInst—Obsolete in Win32, this is kept for compatibility with Win16.

  • LPSTR cmdParam—A string with the command-line arguments.

  • int cmdShow—A flag that says whether to show the main window or not.

Notice the strange type names. You'll have to get used to them—Windows is full of typedefs. In fact, you will rarely see an int or a char in the description of the Windows API. For now, it's enough to know that LPSTR is in fact a typedef for a char * (the abbreviation stands for Long Pointer to STRing, where string is a null-terminated array, and "long pointer" is a fossil left over from the times of 16-bit Windows).

In what follows, I will prefix all Windows API functions with a double colon. A double colon simply means that it's a globally defined function (not a member of any class or namespace). It is somehow redundant, but it makes the code more readable. The classes WinClassMaker, WinMaker, and Window will be defined in a moment.

int WINAPI WinMain
 (HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR cmdParam, int cmdShow)
 char className [] = "Winnie";
 WinClassMaker winClass (WinProcedure, className, hInst);
 winClass.Register ();
 WinMaker maker (className, hInst);
 Window win = maker.Create ("Hello Windows!");
 win.Display (cmdShow);

 // Message loop
 MSG msg;
 int status;
 while ((status = ::GetMessage (& msg, 0, 0, 0)) != 0)
   if (status == -1)
    return -1;
   ::DispatchMessage (& msg);
 return msg.wParam;

First, the program creates a window class and registers it. Then it creates a window with the caption "Hello Windows!" and displays it (or not, depending on the flag it is given). Finally, it enters the message loop that waits for a message from Windows (the ::GetMessage API) and then lets the system dispatch it. The message will come back to our program when Windows calls the Window procedure, WinProcedure. For the time being we don't have to worry about the details of the message loop. The program normally terminates when ::GetMessage returns zero. The wParam of the last message contains the return code of our program.

The ::GetMessage function is an interesting example of three-state logic. It is defined to return the type BOOL, which is a typedef for int, not bool (in fact, there was no bool in C11, not to mention C, when Windows was first released). The documentation, however, specifies three types of returns: nonzero, zero, and –1 (I am not making this up!). Here's the actual excerpt from the Help file:

If the function retrieves a message other than WM_QUIT, the return value is nonzero.

If the function retrieves the WM_QUIT message, the return value is zero.

If there is an error, the return value is –1.

We introduce the class WinClassMaker to encapsulate the WNDCLASSEX data structure and the ::RegisterClass API.

class WinClassMaker
 WinClassMaker (WNDPROC WinProcedure,
         char const * className,
         HINSTANCE hInst);
 void Register ()
  if (::RegisterClassEx (&_class) == 0)
   throw "RegisterClass failed";

In the constructor of WinClassMaker we initialize all parameters to some sensible default values. For instance, we set the default for the mouse cursor to an arrow, and the brush (used by Windows to paint the window's background) to the default window color. We will translate most Windows errors into exceptions. For the time being I will use literal strings as exception objects—they can be caught by the following catch clause:

catch (char const * msg)

Later we'll switch to a more sophisticated mechanism (see page 397).

When registering a class, we have to provide the pointer to the window procedure, the name of the class, and the handle to the instance that owns the class.

 (WNDPROC WinProcedure,
  char const * className,
 _class.lpfnWndProc = WinProcedure;// Mandatory
 _class.hInstance = hInst;     // Mandatory
 _class.lpszClassName = className; // Mandatory
 _class.cbSize = sizeof (WNDCLASSEX);
 _class.hCursor = ::LoadCursor (0, IDC_ARROW);
 _class.hbrBackground = reinterpret_cast<HBRUSH>
             (COLOR_WINDOW + 1);
 _class.style = 0;
 _class.cbClsExtra = 0;
 _class.cbWndExtra = 0;
 _class.hIcon = 0;
 _class.hIconSm = 0;
 _class.lpszMenuName = 0;

Notice some of the ugly tricks we have to do. The hbrBackground data member of WNDCLASSEX is defined as HBRUSH. However, you can initialize it using one of the standard color constants defined by Windows, COLOR_WINDOW in our case. That requires an explicit type cast. Unfortunately, one of the color constants, COLOR_SCROLLBAR, is defined to be zero, so it would be confused by Windows with a null brush. That's why you are required to add the spurious one to the color constant when passing it to WNDCLASSEX. Windows is full of such "clever hacks."

The class WinMaker initializes and stores all the parameters describing a particular window.

class WinMaker
 WinMaker (char const * className, HINSTANCE hInst);
 HWND Create (char const * title);
 HINSTANCE  _hInst;   // Program instance
 char const *_className; // Name of Window class
 DWORD    _style;   // Window style
 DWORD    _exStyle;  // Window extended style
 int     _x;     // Horizontal position
 int     _y;     // Vertical position
 int     _width;   // Window width
 int     _height;   // Window height
 HWND    _hWndParent; // Parent or owner
 HMENU    _hMenu;   // Menu or child-window ID
 void    *_data;    // window-creation data

The constructor of WinMaker takes the name of its window class and the handle to program instance. The class name is necessary for Windows to find the window procedure for this window. The rest of the parameters are given some reasonable default values. For instance, we let the system decide the initial position and size of our window. The style, WS_OVERLAPPEDWINDOW, is the most common style for top-level windows. It includes a title bar with a system menu on the left and the minimize, maximize, and close buttons on the right. It also provides for a "thick" border that can be dragged with the mouse to resize the window.

WinMaker::WinMaker (char const * className,
          HINSTANCE hInst)
  _exStyle (0),
  _className (className),
  _x (CW_USEDEFAULT),   // Horizontal position
  _y (0),         // Vertical position
  _width (CW_USEDEFAULT), // Window width
  _height (0),      // Window height
  _hWndParent (0),    // Parent or owner window
  _hMenu (0),       // Menu or child-window identifier
  _data (0),       // Window-creation data
  _hInst (hInst)

All these parameters are passed to the ::CreateWindowEx API that creates the window (but doesn't display it yet).

HWND WinMaker::Create (char const * title)
 HWND hwnd = ::CreateWindowEx (

 if (hwnd == 0)
  throw "Window Creation Failed";
 return hwnd;

Create takes a window title which will appear in the title bar and returns a handle to the successfully created window. We will conveniently encapsulate this handle in a class called Window. Other than storing a handle to a particular window, this class will later provide an interface to a multitude of Windows APIs that operate on that window.

class Window
 Window (HWND h = 0) : _h (h) { }
 void Display (int cmdShow)
  assert (_h != 0);
  ::ShowWindow (_h, cmdShow);
  ::UpdateWindow (_h);
 HWND _h;

To make the window visible, we have to call ::ShowWindow with the appropriate parameter, which specifies whether the window should be initially minimized, maximized, or the default size. ::UpdateWindow causes the contents of the window to be refreshed.

The window procedure must have the following signature, which is hard-coded into Windows:

 (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);

Notice the calling convention and the types of parameters and the return value. These are all typedefs defined in windows.h. CALLBACK is a predefined language-independent calling convention (what order the parameters are pushed on the stack, and so on). LRESULT is a type of return value. HWND is a handle to a window, UINT is an unsigned integer that identifies the message, and WPARAM and LPARAM are the types of the two parameters that are passed with every message.

WinProcedure is called by Windows every time it wants to pass a message to our program (see Figure 15.2). The window handle identifies the window that is supposed to respond to this message. Remember that the same window procedure may service several instances of the same window class. Each instance will have its own window with a different handle, but they will all go through the same procedure.

Figure 15.2 The relationship between instances of the same program, their windows, and the program's window class and procedure

The message is just a number. Symbolic names for these numbers are defined in windows.h. For instance, the message that tells the window to repaint itself is defined as

#define WM_PAINT    0x000F

Every message is accompanied by two parameters whose meaning depends on the kind of message. (In the case of WM_PAINT, the parameters are meaningless.)

To learn more about window procedures and various messages, study the Help files that come with your compiler.

Here's our minimalist implementation of the window procedure.

 (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
 switch (message)
  ::PostQuitMessage (0);
  return 0;

 return ::DefWindowProc (hwnd, message, wParam, lParam );

It doesn't do much in this particular program. It only handles one message, WM_DESTROY, that is sent to the window when it is being destroyed. At that point the window has already been closed—all we have to do is terminate WinMain. We do it by posting the final quit message. We also pass the return code through it—zero in our case. This message will terminate the message loop and control will be returned to WinMain.

Figure 15.3 shows the window created by our little application—complete with sizing borders; minimize, maximize, and close buttons; a Windows default icon, and a system menu that can be opened by clicking on the icon.

To make the project more structured, we will distribute the source code between multiple files.

Figure 15.3 The output of Hello Windows!

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020