If you are an embedded software programmer, you may be unfamiliar with the general techniques of event-driven programming in Windows. The purpose of this section is to outline the fundamentals of the Windows programming model and the related Win32 API. If you are an experienced Windows programmer, you may want to skip this section.
Windows is an event-driven operating system. An event may be a keystroke, a tap on the screen, or a command for a window to repaint itself. Every time an event takes place, the operating system sends a message to the relevant process. Essentially, a Windows-based program receives messages, interprets those messages, and takes an appropriate action.
A basic Windows-based program has three primary elements: a window, a message pump, which is also called a message loop, and a message processor. This section describes how these work together.
Although windows are commonly thought of in terms of visual display, they can be defined as non-visible. For example, if you are programming an application with no user interface, you will need a non-visible window to process messages. Each window has a window handle, or hwnd, associated with a message processor that handles messages for the window. Additionally, a window handle is used any time you need to call a function that requires hwnd as a parameter.
A message pump is a simple loop that runs continuously while the application runs, receiving messages and dispatching them to the appropriate message processor. When events occur that generate messages, the operating system places the messages in a message queue. Each queue has a message pump that takes the messages one at a time and dispatches them to the appropriate message processor for handling. Although a simple application will have a single queue, a multithreaded application may have a queue for each thread. The message pump continues running until it receives a message to terminate the application.
A simple Windows-based program has two primary functions: a message processor, usually called a WndProc, and WinMain, which provides an entry point to the program. The WndProc function processes messages for a particular window. Although there are many Windows messages, only a few, such as WM_PAINT and WM_CREATE, must be processed by the application. In general, an application processes those messages that are relevant to its operation and passes the remaining messages back to the operating system for default processing. The primary purpose of WinMain is to host the principal message pump for the application. It can also handle application initialization and shutdown procedures.