Your browser doesn't support JavaScript mfc – Windows Programming

Common Controls

In addition to the standard controls, Windows provides an extended set of child controls known as common controls. These controls provide more advanced functionality than the standard controls and include controls such as tree views, list views, tab controls, progress bars, animation controls, and ComboBoxEx controls.

To use common controls in an MFC application, the header file afxcmn.h should be included. This header file automatically includes commctrl.h, which defines the Windows Common Controls API.

Older versions of MFC, such as Visual C++ 6.0, require the Common Controls library to be initialised before these controls can be created. This is normally achieved by calling the API function InitCommonControls() from the application’s CWinApp::InitInstance() member function. Modern versions of Visual Studio typically initialise the common controls automatically, although InitCommonControlsEx() can still be used when an application needs to initialise specific classes of common controls.

The prototype for the InitCommonControlsEx() API function is

BOOL InitCommonControlsEx(const INITCOMMONCONTROLSEX* lpInitCtrls);

where

lpInitCtrls – Points to an INITCOMMONCONTROLSEX structure that specifies which classes of common controls should be registered.

The function returns TRUE if the requested control classes were successfully initialised; otherwise, it returns FALSE.

The INITCOMMONCONTROLSEX structure is defined as follows:

typedef struct tagINITCOMMONCONTROLSEX{
    DWORD dwSize;
    DWORD dwICC;
} INITCOMMONCONTROLSEX, *LPINITCOMMONCONTROLSEX;

where

  • dwSize – Specifies the size of the structure, in bytes.
  • dwICC – Specifies which classes of common controls are to be initialised. One or more ICC_ flags can be combined using the bitwise OR (|) operator.

The following example initialises the standard Windows 95 common control classes:

INITCOMMONCONTROLSEX icc;
icc.dwSize = sizeof(INITCOMMONCONTROLSEX);
icc.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&icc);

Note: When writing MFC applications with Visual C++ 6.0, InitCommonControls() is sufficient for most applications and examples. InitCommonControlsEx() provides finer control over which common control classes are initialised and is the preferred function for modern Windows applications.

Common Controls List

Animation Control

The CAnimateCtrl class encapsulates the Windows Animation common control. An animation control displays simple frame-based animations stored in AVI (Audio Video Interleave) files. Unlike a media player, the control is intended only for short, silent animations and does not support sound playback or modern video formats such as MPEG or MP4.

Animation controls are commonly used to provide visual feedback while an application performs a lengthy operation. Typical examples include displaying a moving file, a magnifying glass, or another animated symbol while searching, copying files, or processing data. The animations supplied with Windows are often referred to as AVI clips and consist of a sequence of bitmap frames displayed in rapid succession.

Animation controls are particularly useful for indicating that an operation is in progress without requiring the application to implement its own animation routines. Although they were widely used in earlier versions of Windows, modern applications often replace AVI animations with animated images, progress indicators, or custom graphical effects. Nevertheless, the CAnimateCtrl class remains a simple and effective way of displaying lightweight animations in traditional Windows applications.

The animation control does not play AVI files like a full media player. Instead, it is intended for short, repetitive animations that provide status information or improve the user interface.

animate control

For further reading – https://docs.microsoft.com/en-us/windows/win32/controls/animation-control-reference

The following example demonstrates the flying folder avi animation


ComboBoxEx Control

The ComboBoxEx control is an extended version of the standard Windows combo box control. It provides all the norThe CComboBoxEx class encapsulates the Windows ComboBoxEx common control. A ComboBoxEx extends the standard combo box by allowing each list item to be displayed with an associated image, selected image, and indentation level. This enables applications to present information in a more visually appealing and organised manner than is possible with a standard CComboBox.

Like a standard combo box, a ComboBoxEx combines an edit control with a drop-down list, allowing the user to select an item from a predefined list or, depending on the control style, enter a value directly. The additional image support makes the control particularly useful for displaying objects such as files, folders, drives, printers, or other items that benefit from graphical identification.

Before items containing images can be added to a ComboBoxEx control, an image list must first be created and associated with the control using the SetImageList() member function. Individual items are then inserted using the InsertItem() member function and described using a COMBOBOXEXITEM structure. This structure specifies the item’s text, image index, selected image, indentation level, and other optional attributes.mal features of a combo box while adding additional functionality, most notably native support for images associated with list items.

Unlike a standard combo box, where each item consists only of text, a ComboBoxEx control allows each item in the drop-down list to contain:

  • A text label.
  • An image displayed beside the text.
  • A selected image that can be shown when the item is chosen.

The images are normally stored in an image list (HIMAGELIST) and are associated with individual items using the ComboBoxEx item structure.


For further reading https://docs.microsoft.com/en-us/windows/win32/controls/comboboxex-control-reference

The following example creates a comboboxex control with 3 items. Each item has an associated system bitmap image.


Date and Time Picker

The CDateTimeCtrl class encapsulates the Windows Date and Time Picker common control. A date and time picker allows the user to select or edit a date, a time, or both, using either the keyboard or a drop-down calendar. The control provides a convenient alternative to entering dates manually, reducing the likelihood of invalid or incorrectly formatted input.

The appearance of the control is determined by the window style specified when it is created. It can display the current date and time, a date only, a time only, or present a drop-down month calendar from which the user can select a date. The display format can also be customised to present dates and times in a variety of regional or application-specific formats.

When the user changes the selected date or time, the control sends a notification message to its parent window, allowing the application to respond immediately to the new selection. The selected value can also be retrieved at any time using the GetTime() member function.

data and time picker


For further reading https://docs.microsoft.com/en-us/windows/win32/controls/date-and-time-picker-control-reference

The following short program demonstrates the date-picker control. Changing the date or time causes the static box to be updated with the selected date.


Header Control

The CHeaderCtrl class encapsulates the Windows Header common control. A header control displays one or more column headings, each of which can contain text, an image, or both. Header controls are most commonly used in conjunction with list view controls to identify the contents of each column, although they can also be used independently wherever labelled columns are required.

Each column, known as a header item, is described by an HDITEM structure that specifies properties such as the displayed text, column width, alignment, image, and formatting options. Header items can be inserted, deleted, resized, and modified while the application is running.

A header control sends notification messages to its parent window whenever the user interacts with one of its items. These notifications include events such as clicking a column, double-clicking a column divider, beginning a resize operation, and changing the display order of columns. Applications typically respond to these notifications by sorting data, resizing columns, or updating the display.

header control picture


For further reading https://docs.microsoft.com/en-us/windows/win32/controls/header-control-reference

The following short program creates a simple window with 3 header controls. Clicking either will cause the title to be display in a static box.


Hot Key

The CHotKeyCtrl class encapsulates the Windows Hot Key common control. A hot key control allows the user to define a keyboard shortcut by pressing a combination of keys directly into the control. The control automatically interprets the key combination and displays it in a standard Windows format, making it easy for users to assign or modify keyboard shortcuts within an application.

A hot key consists of a virtual key code combined with one or more modifier keys such as Ctrl, Alt, Shift, or the Windows key. The control validates the key combination as it is entered and can restrict invalid or undesirable combinations through application-defined rules.

The selected hot key can be retrieved programmatically and stored for later use. Applications commonly register the selected key combination using the Windows RegisterHotKey() API function, allowing the shortcut to invoke commands even when the application window is not active.

Unlike a standard edit control, a hot key control does not accept arbitrary text input. Instead, it captures keyboard input and automatically formats the pressed key combination using the standard Windows notation, for example Ctrl+Alt+S or Shift+F5.

animate control

IP Address Control

The CIPAddressCtrl class encapsulates the Windows IP Address common control. It provides a specialised edit control for entering and displaying IPv4 addresses in the familiar dotted-decimal format.

Unlike a standard edit control, the IP Address control automatically divides the address into four separate numeric fields called octets. Each field accepts values only in the range 0 to 255, preventing invalid IP addresses from being entered. The control automatically moves the keyboard focus between fields as the user types, making address entry quick and intuitive.

Applications typically use the control wherever users must enter IP addresses, such as network configuration utilities, communication programs, router setup software, and server management tools.

The control validates each field as the user types, ensuring that only valid numeric values are entered. When the application needs the address, it simply retrieves the four octets and combines them into a single IP address.

Note: The IP Address control is not available through the MFC CIPAddressCtrl class in Visual C++ 6.0. The underlying Windows IP Address common control is available, but it must be created and accessed directly using the Windows API rather than through an MFC wrapper.

animate control

Listview

The CListCtrl class encapsulates the Windows List View common control. A list view displays a collection of items in a variety of layouts, allowing the user to select, sort, and manipulate data. Unlike a standard list box, a list view can display multiple columns, icons, and additional information associated with each item.

A list view control supports four display styles: icon view, small icon view, list view, and report view. Icon and small icon views display items as icons with descriptive text, list view presents items in a single column, while report view organises information into rows and columns similar to a spreadsheet. Report view is the most commonly used style and is particularly suited to displaying tabular data.

Items are inserted into the control using the InsertItem() member function. When operating in report view, additional column headings are created using the InsertColumn() member function, while supplementary information for each row is added using the SetItemText() member function. Images may also be associated with items by attaching an image list to the control.

A list view control sends notification messages to its parent window whenever the user interacts with the control. These notifications include events such as selecting an item, activating an item by double-clicking, editing a label, or clicking a column heading. Applications can respond to these notifications to update the user interface, display additional information, or sort the displayed data.

listview control picture


For further reading https://docs.microsoft.com/en-us/windows/win32/controls/list-view-control-reference

The following example creates a simple listview with 4 items. Changing the selected value will copy the contents of the first column into the static box


Month Calendar Control

The CMonthCalCtrl class encapsulates the Windows Month Calendar common control. A month calendar control displays one or more months in a calendar format, allowing the user to select dates using the mouse or keyboard. It provides an intuitive graphical interface for date selection and is commonly used in scheduling, diary, booking, and planning applications.

Unlike the Date and Time Picker control, which combines a text box with an optional drop-down calendar, the Month Calendar control always displays the calendar. This makes it particularly suitable where the user needs to browse and compare dates over an extended period.

The appearance and behaviour of the control can be customised using a variety of window styles. For example, applications can display multiple months, show week numbers, prevent the selection of invalid dates, or highlight the current date.

When the user changes the selected date, the control sends notification messages to its parent window. These notifications enable the application to respond immediately by updating other controls, displaying information for the selected date, or performing additional processing.

calendar control picture


For further reading https://docs.microsoft.com/en-us/windows/win32/controls/month-calendar-control-reference

The following example creates a month calendar control and displays the currently selected date in a static label.


Pager Control

The CPagerCtrl class encapsulates the Windows Pager common control. A pager control provides a scrolling container for another child control when there is insufficient space to display the entire contents. Rather than displaying traditional scroll bars, the pager displays directional buttons that allow the user to scroll the contained control horizontally or vertically.

The pager control does not display data itself. Instead, it acts as a container for another child control, such as a toolbar, rebar, or other window. As the user clicks the pager’s navigation buttons, different portions of the child control are brought into view.

A pager control sends notification messages to its parent window whenever scrolling occurs or when the child control requires repositioning. Applications can respond to these notifications by adjusting the displayed content or updating the user interface.

Compatibility
This example requires MFC 7.0 (Visual Studio .NET 2002) or later. The CPagerCtrl class is not available in the MFC library supplied with Visual C++ 6.0 and earlier versions. Readers using VC6 will need to create the underlying Windows Pager control (SysPager) manually using the Win32 API, as no MFC wrapper class is provided.

The following example creates a pager control that hosts a toolbar containing several standard system buttons. When the window is resized, the pager automatically provides scrolling so that all toolbar buttons remain accessible.

page scroller control picture


For further reading https://docs.microsoft.com/en-us/windows/win32/controls/pager-control-reference

In the following example, a page controller encloses the toolbar.


Progress Bar

The CProgressCtrl class encapsulates the Windows Progress Bar common control. A progress bar provides a graphical indication of the progress of a lengthy operation by displaying a bar that gradually fills as the task advances. Progress bars are commonly used to indicate the status of operations such as file copying, software installation, data processing, and downloads.

A progress bar operates over a specified range of values, typically from 0 to 100. As the current position increases, a larger proportion of the bar is filled, giving the user a visual indication of how much of the operation has been completed. The control can be updated periodically as work progresses or incremented automatically by a fixed amount.

The appearance and behaviour of the progress bar can be customised using a variety of window styles. For example, the control may be displayed horizontally or vertically, and newer versions of Windows support additional features such as smooth filling and marquee animations.

Unlike many other common controls, a progress bar does not normally generate notification messages in response to user interaction, since it is intended to display information rather than accept input. Instead, the application updates the control programmatically as the associated task progresses.

progress bar control picture


For further reading https://docs.microsoft.com/en-us/windows/win32/controls/create-progress-bar-controls

In the example below, a timer function increments a progress bar control.


Rebar Control

The CReBar class encapsulates the Windows Rebar common control. A rebar acts as a container for one or more child controls, known as bands, which can be arranged horizontally or vertically within the window. Each band typically contains a toolbar, combo box, edit control, or another child window. Users can reposition, resize, or hide individual bands, allowing the application’s user interface to be customised.

Unlike a toolbar, which contains only buttons, a rebar can host many different types of controls simultaneously. This flexibility makes rebars particularly useful for creating sophisticated user interfaces similar to those found in Microsoft Office and Windows Explorer.

Before a control can be displayed within a rebar, it must first be created as a child window. The control is then inserted into the rebar using the AddBar() member function or by supplying a REBARBANDINFO structure that describes the band’s properties, including its size, style, and caption.

A rebar control sends notification messages to its parent window whenever a band is resized, repositioned, or otherwise modified. Applications can respond to these notifications to update the user interface or save the user’s preferred layout.

Rebars are commonly used to create customisable toolbars similar to those found in Microsoft Office and Windows Explorer.

mfc rebar control image


For further reading https://docs.microsoft.com/en-us/windows/win32/controls/rebar-controls

The following example creates a rebar containing a toolbar with standard system toolbar buttons.


Rich Edit Control

The CRichEditCtrl class encapsulates the Windows Rich Edit control. A Rich Edit control extends the functionality of the standard edit control by supporting formatted text, multiple fonts, colours, paragraph alignment, tab stops, and embedded objects. It also provides advanced editing features such as undo, redo, clipboard operations, text selection, and word wrapping.

Unlike the standard CEdit control, which stores plain text only, a Rich Edit control allows different portions of a document to have different formatting attributes. For example, individual words may be displayed in different fonts, sizes, colours, or styles such as bold, italic, and underline.

A Rich Edit control sends notification messages to its parent window whenever its contents or state changes. These notifications include events such as text modification, changes to the current selection, scrolling, and clipboard operations. Applications can respond to these notifications to update menus, toolbars, or other parts of the user interface.


For further reading https://docs.microsoft.com/en-us/windows/win32/controls/rich-edit-controls

The following example creates a Rich Edit control and a button. Clicking the button inserts a line of coloured, bold text into the control.


Status Bar

The CStatusBar class encapsulates the Windows Status Bar control. A status bar is typically displayed along the bottom edge of an application’s main window and is used to present status information, contextual help, progress information, or the current state of the application. Unlike a message box or dialog, a status bar provides continuous feedback without interrupting the user’s work.

A status bar is divided into one or more sections, known as panes. Each pane can display text, an icon, or another indicator. Applications commonly use different panes to display information such as the current document status, cursor position, keyboard state, or the current date and time.

Before a status bar can be displayed, it must be created using the Create() member function and configured with one or more panes using the SetIndicators() member function. The contents of each pane can then be updated at any time using the appropriate member functions.

Unlike many other controls, a status bar generally does not receive direct input from the user. Instead, it is updated programmatically by the application to reflect changes in its current state. For example, an application may display messages such as Ready, Loading file…, or Saving document…, or provide context-sensitive help describing the function of the currently selected menu item or toolbar button.

status bar control picture


For further reading https://docs.microsoft.com/en-us/windows/win32/controls/status-bar-reference

The following example creates a status bar with two panes. Clicking the button updates the text displayed in the first pane.


Tab Control

The CTabCtrl class encapsulates the Windows Tab common control. A tab control provides a series of labelled tabs that allow the user to switch between different pages of related information within the same window. Each tab typically represents a separate page containing its own controls or view, enabling large amounts of information to be organised without requiring multiple windows.

A tab control displays only the tab headings. It is the responsibility of the application to create, show, and hide the child windows associated with each tab when the user changes the current selection. In MFC, tab controls are frequently used to implement property sheets, configuration dialogs, and multi-page interfaces.

Tabs are inserted using the InsertItem() member function, with each tab described by a TCITEM structure containing properties such as the tab text, image, and application-defined data. The currently selected tab can be obtained or changed using the appropriate member functions.

When the user selects a different tab, the control sends notification messages to its parent window. The most commonly used notifications are TCN_SELCHANGING, sent before the selection changes, and TCN_SELCHANGE, sent after a new tab has been selected. Applications typically respond by hiding the controls belonging to the previous page and displaying those associated with the newly selected tab.

tab control picture


For further reading https://docs.microsoft.com/en-us/windows/win32/controls/tab-control-reference

The following example creates a tab control containing three tabs. Selecting a tab updates a static label to indicate the currently selected page.



Toolbar Control

The CToolBar class encapsulates the Windows Toolbar common control. A toolbar provides a row or column of buttons that give users quick access to frequently used commands. Each button typically displays an icon, although text labels, separators, drop-down buttons, and check buttons may also be used. Toolbars provide an efficient alternative to selecting commands from application menus.

A toolbar is normally positioned along the top edge of the application’s main window, although it may also be docked to other sides of the window or allowed to float in a separate frame. Each toolbar button is associated with a command identifier, enabling the application to respond when the user clicks the button.

Toolbar buttons usually obtain their images from an image list or bitmap resource. MFC also supports loading predefined toolbar resources created using the Visual Studio resource editor. Modern versions of Windows additionally provide support for high-colour image lists and alpha-blended icons.

When the user clicks a toolbar button, the control sends the corresponding command message to its parent window. Applications respond to these command messages in the same way as menu selections, allowing a single command handler to service both toolbar buttons and menu items.

page scroller control picture


The following example creates a toolbar containing the standard Windows New, Open, Save, Print, Copy, and Paste buttons.


Tooltip

The CToolTipCtrl class encapsulates the Windows Tooltip common control. A tooltip is a small pop-up window that displays a brief description of a control or user interface element when the user positions the mouse pointer over it. Tooltips provide context-sensitive help without occupying permanent screen space, making them particularly useful for toolbar buttons and controls whose purpose may not be immediately obvious.

A tooltip control does not display information by itself. Instead, it is associated with one or more existing child controls using the AddTool() member function. When the mouse pointer remains over a registered control for a short period, the tooltip is displayed automatically. The displayed text can be specified when the tool is registered or updated later while the application is running.

Tooltips can be configured to appear automatically, remain visible for a specified period, or display using different visual styles depending on the version of Windows. Modern versions of Windows also support multiline tooltips, balloon tooltips, and hyperlinks.

Unlike many common controls, a tooltip does not normally receive direct user input. Instead, it monitors mouse movement over registered controls and displays the appropriate text when required. In many MFC applications, mouse messages are forwarded to the tooltip control by calling the RelayEvent() member function from the application’s PreTranslateMessage() function.

tooltip dialog control picture


For further reading https://docs.microsoft.com/en-us/windows/win32/controls/tooltip-control-reference

The following example creates a push button and associates a tooltip with it.


Trackbar Control

The CSliderCtrl class encapsulates the Windows Trackbar common control. A trackbar, also known as a slider control, allows the user to select a value from a continuous or fixed range by dragging a movable thumb along a horizontal or vertical track. Trackbars provide a simple and intuitive method of adjusting numeric values without requiring the user to type them.

A trackbar consists of a track, a movable thumb, and optional tick marks that indicate individual positions along the range. Applications typically use trackbars to adjust settings such as volume, brightness, colour intensity, zoom level, or animation speed. The control can be configured to display tick marks, selection ranges, and labels depending on the application’s requirements.

Before the control can be used, the application specifies the minimum and maximum values using the SetRange() member function. The current position can then be obtained or modified programmatically using the appropriate member functions.

When the user moves the slider, the control sends WM_HSCROLL or WM_VSCROLL messages to its parent window, depending on whether the control is horizontal or vertical. The application can respond to these messages by retrieving the current slider position and updating other controls or application settings accordingly.

trackbar control picture


For further reading – https://docs.microsoft.com/en-us/windows/win32/controls/using-trackbar-controls

The following example creates a horizontal trackbar with a range of 0 to 100. As the slider is moved, the current value is displayed in a static label.


Tree-View Control

The CTreeCtrl class encapsulates the Windows Tree View common control. A tree view displays information in a hierarchical structure consisting of parent and child items. Each item may be expanded or collapsed to reveal or hide its subordinate items, making the control particularly suitable for displaying structured information such as directories, organisational charts, and document outlines.

Each item within a tree view is represented by an HTREEITEM handle and may contain text, an image, a selected image, and application-defined data. Images are typically supplied through an image list, allowing different icons to be displayed for folders, files, or other object types.

Items are inserted into the control using the InsertItem() member function. New items can be added as root items or as children of existing items, allowing the application to construct complex hierarchical structures dynamically. Items may also be removed, expanded, collapsed, or modified while the application is running.

When the user interacts with the control, the tree view sends notification messages to its parent window. These notifications include events such as selecting an item, expanding or collapsing a branch, editing a label, or beginning a drag-and-drop operation. Applications can respond to these notifications by displaying additional information, loading child items, or updating other parts of the user interface.

treeview control picture


For further reading – https://docs.microsoft.com/en-us/windows/win32/controls/tree-view-control-reference

The following example creates a tree view containing several items. Selecting an item displays its text in a static label.


Updown Control

The CSpinButtonCtrl class encapsulates the Windows Up-Down common control. An up-down control, also known as a spin button control, consists of a pair of arrow buttons that allow the user to increment or decrement a numeric value. The control is commonly attached to an edit control, enabling users to either type a value directly or adjust it using the arrow buttons.

An up-down control maintains a range of valid values together with the current position. Each click of the up or down arrow changes the current value by one step, although applications may customise this behaviour if required. By restricting the range of acceptable values, the control helps prevent invalid numeric input.

The control can operate independently or be associated with a buddy window, typically an edit control. When a buddy control is assigned, the displayed value is updated automatically as the user operates the spin buttons, providing a convenient mechanism for entering small numeric values.

When the user clicks one of the spin buttons, the control sends notification messages to its parent window indicating that the current position is about to change. The application can respond to these notifications by validating the new value, preventing invalid changes, or updating other controls within the user interface.

updown control picture


For further reading https://docs.microsoft.com/en-us/windows/win32/controls/up-down-control-reference

The following example creates an edit control and an up-down control. Clicking the arrows changes the displayed value between 0 and 100.


.

Mapping Modes

The mapping mode determines how Windows converts logical coordinates used by an application into device coordinates (pixel positions) on the output device. Logical coordinates represent the values specified by the program when drawing graphics or text, while device coordinates correspond to the actual pixel locations on the screen or printer.

The selected mapping mode defines:

  • How logical units are converted into device units (pixels or physical units).
  • The position of the coordinate system origin.
  • The orientation of the X-axis and Y-axis.
  • Whether the coordinate values increase or decrease relative to the origin.

By default, a Windows device context uses the MM_TEXT mapping mode. In this mode:

  • One logical unit is equal to one pixel.
  • The origin (0,0) is located at the upper-left corner of the client area.
  • The X-axis increases to the right.
  • The Y-axis increases downwards.

Windows provides eight predefined mapping modes, each suited to different drawing requirements. These are listed below

Mapping Mode Logical Unit x-axis and y-axis
MM_TEXT Pixel Positive x is to the right; positive y is down
MM_LOMETRIC 0.1 mm Positive x is to the right; positive y is up.
MM_HIMETRIC 0.01 mm Positive x is to the right; positive y is up.
MM_LOENGLISH 0.01 in Positive x is to the right; positive y is up.
MM_HIENGLISH 0.001 in Positive x is to the right; positive y is up.
MM_TWIPS 1/1440 in Positive x is to the right; positive y is up.
MM_ISOTROPIC user-specified user-specified
MM_ANISOTROPIC user-specified user-specified

To select a different mapping mode, use the CDC member function SetMapMode()

virtual int SetMapMode( int nMapMode );

where
nMapMode specifies the new mapping mode. The Return Value is the previous mapping mode.

Programmable Mapping Modes

Unlike the predefined mapping modes, MM_ISOTROPIC and MM_ANISOTROPIC allow the programmer to define how logical coordinates are mapped to device coordinates. Instead of using fixed measurement units such as pixels or millimetres, the application specifies the relationship between the logical drawing area (the window) and the physical drawing area (the viewport).

The two programmable mapping modes differ as follows:

  • MM_ISOTROPIC maintains the same scale factor for both the X-axis and Y-axis. This preserves the aspect ratio of graphics, ensuring that circles remain circular and shapes are not distorted.
  • MM_ANISOTROPIC allows different scale factors for the X-axis and Y-axis. This permits graphics to be stretched or compressed independently in each direction.

When either of these mapping modes is selected, the application must define the logical size of the drawing area (the window extent) and the corresponding device size (the viewport extent).

The logical extents are specified using the SetWindowExt() member function, while the device extents are specified using SetViewportExt().

The prototypes are:

SetWindowExt

Sets the x- and y-extents of the window associated with the device context.

virtual CSize SetWindowExt( int cx, int cy ); virtual CSize SetWindowExt( SIZE size );

Parameters
cx – Specifies the Window x-extent (in logical units).
cy – Specifies the Window y-extent (in logical units).
size – Specifies the Windows x- and y-extents (in logical units).

Returns the previous extents of the window as a CSize object. If an error occurs, the x- and y-coordinates of the returned CSize object are set to 0.

SetViewportExt

Sets the x- and y-extents of the device context’s viewport.

virtual CSize SetViewportExt( int cx, int cy ); virtual CSize SetViewportExt( SIZE size );

Parameters
cx – Specifies the x-extent of the viewport (in device units).
cy – Specifies the y-extent of the viewport (in device units).
size – Specifies the x- and y-extents of the viewport (in device units).

Returns the previous extent of the viewport as a CSize object. When an error occurs, the x- and y-coordinates of the returned CSize object are set to 0.

For example, if SetViewportExt is called with parameters 100,50 and SetWindowExt is called with parameters 100,100 this will mean that each logical unit in the X direction will equate to 1 device unit and each logical unit in the y direction will equate to 1/2 a unit in the device coordinate.

Moving the Origin

By default, the origin of a device context is located at the upper-left corner of the client area, regardless of the mapping mode being used. The origin represents the point (0,0) from which all logical coordinates are measured.

Windows allows the origin to be repositioned using the CDC member functions SetWindowOrg() and SetViewportOrg().

  • SetWindowOrg() changes the logical origin (window origin) of the coordinate system.
  • SetViewportOrg() changes the device origin (viewport origin), effectively moving where the logical origin appears on the output device.

The prototypes for these functions are:

CPoint SetWindowOrg( int x, int y ); CPoint SetWindowOrg( POINT point );

And

virtual CPoint SetViewportOrg( int x, int y ); virtual CPoint SetViewportOrg( POINT point );

where
cx – Specifies the x-extent (in logical units) of the window.
cy – Specifies the y-extent (in logical units) of the window.
size – Specifies the x- and y-extents (in logical units) of the window.

Returns the previous origin or viewport of the window as a CPoint object

Example

The following short program draws 5 squares under different mapping to illustrate the different display characteristics of each

MFC Data Handling

The Microsoft Foundation Class (MFC) library provides a comprehensive collection of classes for storing, manipulating and exchanging data. These classes simplify many common programming tasks by encapsulating frequently used data structures and Windows data types within easy-to-use C++ classes.

MFC data handling facilities fall into three broad categories:

  • Collection classes, which manage groups of related objects.
  • Simple data type classes, which encapsulate commonly used Windows data types.
  • File classes, which provide object-oriented access to files and data storage.

Together these classes allow applications to manage data efficiently while reducing the amount of code required by the programmer.


MFC Collection Classes

Collection classes are designed to manage groups of related objects dynamically. Unlike ordinary C++ arrays, most MFC collection classes automatically increase or decrease in size as elements are added or removed. They also provide convenient member functions for inserting, deleting, searching and retrieving objects.

MFC collection classes fall into two categories:

  • Template collection classes
  • Non-template collection classes

Template collection classes provide compile-time type checking and are generally recommended for modern MFC development. Non-template collection classes remain available primarily for compatibility with existing applications developed before C++ templates became widely supported.

Template Collection Classes

Template collection classes allow programmers to store objects of almost any data type while maintaining compile-time type safety. Because the compiler knows the type of object stored within the collection, many programming errors can be detected during compilation rather than at run time.

The principal template collection classes supplied with MFC are described below.

ClassDescription
CArrayImplements a dynamically sized array that supports random access to its elements. The array automatically expands or contracts as elements are added or removed.
CListImplements a doubly linked list that allows efficient insertion and removal of elements at any position within the collection.
CMapImplements an associative array (dictionary) that maps unique keys to corresponding values, allowing rapid retrieval of stored objects.
CTypedPtrArrayProvides a type-safe wrapper around pointer array collection classes.
CTypedPtrListProvides a type-safe wrapper around pointer list collection classes.
CTypedPtrMapProvides a type-safe wrapper around pointer map collection classes.

Template collection classes are suitable for most new MFC applications because they combine flexibility with compile-time type checking, reducing the possibility of programming errors.

Non-Template Collection Classes

Before C++ templates became widely available, MFC provided a number of collection classes designed to store specific data types. Although these classes remain fully supported for compatibility with older applications, they have largely been superseded by the template collection classes.

The principal non-template collection classes are listed below.

ClassDescription
CObArrayDynamic array of pointers to objects derived from CObject.
CByteArrayDynamic array of BYTE values.
CDWordArrayDynamic array of DWORD values.
CPtrArrayDynamic array of generic pointers (void*).
CStringArrayDynamic array of CString objects.
CUIntArrayDynamic array of unsigned integer values.
CWordArrayDynamic array of 16-bit word values.
CObListDoubly linked list of pointers to objects derived from CObject.
CPtrListDoubly linked list of generic pointers (void*).
CStringListDoubly linked list of CString objects.
CMapPtrToPtrMaps pointer keys to pointer values.
CMapPtrToWordMaps pointer keys to 16-bit word values.
CMapStringToObMaps CString keys to pointers to CObject-derived objects.
CMapStringToPtrMaps CString keys to generic pointers.
CMapStringToStringMaps CString keys to CString values.
CMapWordToObMaps 16-bit word keys to pointers to CObject-derived objects.
CMapWordToPtrMaps 16-bit word keys to generic pointers.

Although non-template collection classes continue to be supported, programmers developing new MFC applications will generally find the template collection classes more flexible and easier to use.

Simple Data Type Classes

In addition to its collection classes, MFC provides a number of utility classes that encapsulate commonly used Windows data types. These classes simplify many programming tasks by providing convenient constructors, operators and member functions for manipulating strings, dates, times, coordinates, rectangles and other frequently used data.

Many of these classes are used extensively throughout the MFC library and appear as parameters or return values in numerous Windows and MFC member functions.

The principal simple data type classes are described below.

ClassDescription
CStringEncapsulates character strings and provides a comprehensive set of member functions for string manipulation, searching, formatting and comparison.
CTimeRepresents an absolute date and time value and provides functions for formatting and performing date and time calculations.
CTimeSpanRepresents a period of elapsed time rather than a specific date or time.
COleDateTimeEncapsulates the OLE Automation DATE data type and is commonly used by COM and ActiveX applications.
COleDateTimeSpanRepresents a time interval associated with COleDateTime objects.
CPointRepresents a two-dimensional point specified by x and y coordinates.
CSizeRepresents the width and height of an object or a horizontal and vertical displacement.
CRectRepresents a rectangular region using the coordinates of its upper-left and lower-right corners.
CImageListEncapsulates a Windows image list containing one or more small bitmap or icon images used by common controls.
COleVariantEncapsulates the OLE Automation VARIANT data type capable of storing values of many different types.
COleCurrencyEncapsulates the OLE Automation CURRENCY data type used for fixed-point monetary values.

These utility classes eliminate much of the complexity associated with manipulating the corresponding Windows data structures directly and provide a consistent object-oriented programming interface throughout the MFC library.


File Input and Output

Almost every Windows application requires the ability to store and retrieve information from files. Rather than requiring programmers to use the low-level Windows file handling functions directly, MFC provides a comprehensive set of classes that encapsulate file operations within an object-oriented framework.

The principal file handling class is CFile, which provides member functions for opening, creating, reading, writing, seeking and closing files. In addition, MFC provides derived classes that extend the capabilities of CFile for specialised applications.

The most commonly used file classes are listed below.

ClassDescription
CFileProvides general-purpose binary file input and output operations.
CStdioFileDerived from CFile; provides text file operations using the C run-time library.
CMemFileImplements a file whose contents are stored entirely in memory rather than on disk.
CSharedFileExtends CMemFile by allowing the memory buffer to be shared between applications, particularly during clipboard and OLE operations.

The CFile class supports numerous operations including:

  • Creating new files.
  • Opening existing files.
  • Reading data from a file.
  • Writing data to a file.
  • Seeking to a specified location within a file.
  • Determining the current file position.
  • Retrieving the file length.
  • Renaming files.
  • Deleting files.
  • Closing files.

Files are typically opened by calling the Open() member function, which specifies the filename together with the required access mode, such as read-only, write-only or read/write access. Once the file has been opened successfully, data may be transferred using the Read() and Write() member functions.

When all file operations have been completed, the application should call the Close() member function to release the associated system resources.


Choosing the Appropriate Collection Class

The large number of available collection classes may initially appear confusing. Fortunately, selecting the appropriate collection is usually straightforward.

  • Use CArray when random access by index is required.
  • Use CList when frequent insertion or deletion of elements is required.
  • Use CMap when objects must be retrieved quickly using a unique key.
  • Use CStringArray or CStringList when storing collections of text strings.
  • Use one of the pointer collection classes when storing pointers to dynamically allocated objects.

In general, template collection classes should be preferred for new applications because they provide better type checking and greater flexibility. The older non-template collection classes remain valuable when maintaining legacy applications or when compatibility with existing MFC code is required.

Summary

The MFC library provides a comprehensive set of classes for managing data within Windows applications. Collection classes simplify the storage and manipulation of groups of objects, utility classes encapsulate many of the Windows data types commonly encountered during programming, and the file classes provide a convenient object-oriented interface for persistent storage.

Although modern C++ applications frequently make use of the Standard Template Library (STL), the MFC collection and utility classes remain an important part of the framework and continue to be widely used in existing Windows applications. A sound understanding of these classes enables programmers to develop efficient, maintainable applications while taking full advantage of the facilities provided by the Microsoft Foundation Class Library.

Timers

Timers allow an application to execute code at regular time intervals without requiring continuous user interaction. They are commonly used for tasks such as updating clocks, creating animations, polling hardware, refreshing displays, or performing periodic background processing.

The CWnd member function SetTimer() starts a timer that generates events at a specified interval, while the KillTimer() member function stops a previously created timer.

A timer can notify an application in one of two ways:

  • By sending a WM_TIMER message to a window.
  • By calling an application-defined callback function.

The prototype for CWnd::SetTimer() is:

UINT_PTR SetTimer(
    UINT_PTR nIDEvent,
    UINT nElapse,
    TIMERPROC lpfnTimer = NULL
);

Where

  • nIDEvent specifies the timer identifier. This value is used to distinguish between multiple timers associated with the same window. (Traditionally this should be non-zero.)
  • nElapse specifies the timer interval in milliseconds.
  • lpfnTimer specifies the address of an application-defined callback function. If this parameter is NULL, the timer generates WM_TIMER messages that are placed in the application’s message queue.

The function returns the timer identifier if successful; otherwise it returns zero.


Example

SetTimer(1, 700, NULL);

This statement creates a timer with an identifier of 1 that generates a WM_TIMER message every 700 milliseconds. Because the callback parameter is NULL, the timer communicates by sending WM_TIMER messages rather than calling a callback function.


Responding to WM_TIMER Messages

When a timer generates WM_TIMER messages, MFC routes them through the ON_WM_TIMER() message-map macro to the OnTimer() member function.

The prototype is:

afx_msg void OnTimer(UINT_PTR nIDEvent);

where nIDEvent identifies the timer that generated the message.

A typical implementation is shown below.

void CMainFrame::OnTimer(UINT_PTR nIDEvent)
{
    if (nIDEvent == 1)
    {
        // Timer processing code
    }

    CFrameWnd::OnTimer(nIDEvent);
}

Using a Callback Function

Instead of generating WM_TIMER messages, a timer can call an application-defined callback function directly.

For example:

SetTimer(ID_TIMER, 500, TimerCallBackProc);

The callback function is declared as follows:

void CALLBACK TimerCallBackProc(
    HWND hwnd,
    UINT uMsg,
    UINT_PTR idEvent,
    DWORD dwTime
);

Where:

  • hwnd contains the handle of the associated window.
  • uMsg contains the message identifier (WM_TIMER).
  • idEvent contains the timer identifier.
  • dwTime specifies the number of milliseconds that have elapsed since Windows was started.

Timer callback functions are typically used when timer processing does not need to be associated directly with a window’s message handler.


Stopping a Timer

When a timer is no longer required, it should be destroyed by calling KillTimer().

For example:

KillTimer(1);

This statement stops the timer whose identifier is 1. Once the timer has been destroyed, no further WM_TIMER messages or callback notifications will be generated for that timer.

Note: Windows timers are intended for general-purpose timing and are not guaranteed to fire at the exact requested interval. Timer messages are processed through the application’s message queue and may be delayed if the system is busy or the application is processing other messages. They are therefore unsuitable for high-precision timing applications such as multimedia playback or real-time control systems.

Example

The following program illustrates a simple timer app by flashing a “hello world” message in the top left-hand corner of the window

Multi Document Interface

A Multiple Document Interface (MDI) application enables the user to work with several documents simultaneously within a single application window. Each document is displayed in its own MDI child window, which occupies the client area of the main application frame. Unlike separate top-level windows, all child windows are contained within the application’s main frame and can be arranged by cascading, tiling, or minimising them.

An MDI child window closely resembles a normal frame window, except that it exists within an MDI frame window rather than as an independent top-level window. Child windows do not possess their own menu bars. Instead, the active child window shares the menu and toolbar of the MDI frame. The MFC framework automatically updates the menu and other user interface elements to reflect the currently active document.

Like an SDI application, an MDI application contains document, view, frame, and application classes. However, an MDI application also requires a class derived from CMDIChildWnd, which encapsulates the behaviour of an individual MDI child window. Each child window hosts a single document and its associated view.

In addition to the resources associated with the main frame window, each document type normally has its own menu, accelerator table, and document template resources. These resources are automatically loaded whenever the corresponding document becomes active.


Document Templates

Unlike an SDI application, which uses a single CSingleDocTemplate, an MDI application uses one or more CMultiDocTemplate objects. Each document template associates a document class, view class, and child frame class with the resources required to create that document type.

The constructor for CMultiDocTemplate is:

CMultiDocTemplate(
    UINT nIDResource,
    CRuntimeClass* pDocClass,
    CRuntimeClass* pFrameClass,
    CRuntimeClass* pViewClass
);

Where:

  • nIDResource specifies the resource identifier associated with the document type.
  • pDocClass points to the document class derived from CDocument.
  • pFrameClass points to the child frame class derived from CMDIChildWnd.
  • pViewClass points to the view class derived from CView.

Working with Multiple Document Types

An MDI application may support several different document types. Each document type requires its own:

  • Document class
  • View class
  • Child frame class (optional but commonly used)
  • Resource identifier
  • CMultiDocTemplate

Each document template is created during the application’s InitInstance() function and registered with the framework by calling AddDocTemplate().

For example:

CMultiDocTemplate* pDocTemplate; PDocTemplate = new CMultiDocTemplate(IDR_SAMPLE1, RUNTIME_CLASS(CSample1Doc), RUNTIME_CLASS(CMDIChildWnd), RUNTIME_CLASS(CSample1View)); AddDocTemplate(pDocTemplate); pDocTemplate = new CMultiDocTemplate( IDR_SAMPL2, RUNTIME_CLASS(CSample2Doc), RUNTIME_CLASS(CMDIChildWnd), RUNTIME_CLASS(CSample2View)); AddDocTemplate(pDocTemplate);

Once the templates have been registered, the user can create each document type through the application’s File menu. The MFC framework automatically creates the appropriate document, child frame, and view objects based on the selected document template.

Example

The application below allows the user to create a multi-document interface based on the CeditView view class

Download Code

Document View Architecture

The MFC Document/View Architecture is a framework designed to separate the storage and management of application data from its presentation. This is achieved by encapsulating the application data within a document class and the presentation of that data within one or more view classes. Separating the data from its presentation makes applications easier to maintain and extend, particularly when multiple views display the same underlying document.

MFC supports two types of document/view applications: Single Document Interface (SDI) and Multiple Document Interface (MDI) applications.

Single Document Interface

A Single Document Interface (SDI) application displays only one document at a time. Each application window contains a single document and its associated view. To work with multiple documents simultaneously, the user must open multiple instances of the application.

Microsoft Notepad is a classic example of an SDI application.

A typical SDI application consists of four principal classes.

CDocument

The CDocument class provides the functionality required to manage an application’s data. This includes creating new documents, loading existing documents, saving documents, tracking modifications, and supporting printing.

One of the most important responsibilities of the document class is serialization. Serialization is the process of storing an object’s data to a file or restoring it from a file. MFC performs serialization through the CArchive class, allowing applications to read and write object data without performing low-level file operations manually.

CView

The CView class is responsible for displaying the contents of the document and processing user interaction. A view renders the document on the screen or printer while responding to keyboard and mouse input.

MFC supplies several specialised view classes derived from CView, including CEditView, CListView, CTreeView, CFormView, and CRichEditView, each designed for a particular style of presentation.

CMainFrame

The CMainFrame class encapsulates the application’s main frame window. In an SDI application, the view occupies the client area of the main frame window and is created automatically by the document template.

CWinApp

The CWinApp class is the base class from which every MFC application derives its application object. It is responsible for initialising the application, creating the document template, processing the message loop, and managing the application’s lifetime.


Dynamic Creation

Unlike ordinary C++ objects, document, view, and frame objects are created dynamically at run time by the MFC framework. To support this mechanism, MFC uses two macros.

DECLARE_DYNCREATE(ClassName)

Placed in the class declaration.

IMPLEMENT_DYNCREATE(ClassName, BaseClass)

Placed in the implementation (.cpp) file.

These macros enable MFC to create objects using runtime class information rather than explicit constructor calls.

Note: IMPLEMENT_DYNCREATE() belongs in the implementation file, not inside the class declaration.


Document Templates

An SDI application associates its document, frame, and view classes using a document template. MFC provides the CSingleDocTemplate class for this purpose.

CSingleDocTemplate(
    UINT nIDResource,
    CRuntimeClass* pDocClass,
    CRuntimeClass* pFrameClass,
    CRuntimeClass* pViewClass
);

Where

  • nIDResource specifies the resource identifier associated with the document type.
  • pDocClass points to the document class (CDocument derived).
  • pFrameClass points to the frame window class (CFrameWnd derived).
  • pViewClass points to the view class (CView derived).

Once created, the template is registered with the application using the AddDocTemplate() member function.


Command Line Processing

When an MFC application starts, it creates a CCommandLineInfo object to store command-line information. The ParseCommandLine() member function interprets the command line and determines whether the application should create a new document, open an existing document, or perform another action.

The resulting command information is then processed by calling ProcessShellCommand().


Saving and Loading Documents

The Serialize() member function, declared in the CObject class and overridden in CDocument, is responsible for saving and loading document data.

The function receives a CArchive object that manages the transfer of data between memory and a file.

When storing data, the application writes information using the insertion operator (<<).

When loading data, the application reads information using the extraction operator (>>).

Whether the archive is storing or loading data is determined by calling the IsStoring() member function.

A typical implementation is shown below.

void CMyDocument::Serialize(CArchive& ar)
{
    if (ar.IsStoring())
    {
        ar << m_Name;
        ar << m_Age;
    }
    else
    {
        ar >> m_Name;
        ar >> m_Age;
    }
}

he insertion operator (<<) or extracts data with the extraction operator (>>).

Example

In the following example, an SDI application is created which places a sequence of markers at the position of the mouse click. Selecting the relevant display option will change the display marker from x to asterisk and vice versa while the various file/save, file/load and /file/recent demonstrate how to save and load data using the serialize function

Download Code

Toolbars

MFC offers two classes to provide the functionality of the Windows toolbar: CToolbar and CtoolBarCtrl. The CToolBar encapsulates much of its functionality of the standard toolbar control whereas CToolBarCtrl offers a more substantive programming interface.

To create a toolbar the developer can either

1. Instantiate an object of the CToolbar class and then call the CreateEx() member function followed by the member function LoadToolBar() to load the toolbar resource.

2. Instantiate an object of the CtoolBarCtrl class and define a TBBUTTON structure to provide details about the individual buttons. The CtoolBarCtrl class also requires a bitmap resource containing images for the faces of the toolbar buttons.

Toolbar buttons are assigned command IDs and clicking a toolbar button sends a WM_COMMAND message to the parent windows where the button ID is linked to the relevant command handler.

In addition to buttons, Windows toolbars can contain combo boxes, checkboxes, and other non-push-button controls. MFC provides functions for hiding and displaying toolbars, saving and restoring toolbar states, and much more.

For a full description of the CToolBar Class and associated member functions
https://docs.microsoft.com/en-us/cpp/mfc/reference/ctoolbar-class?view=msvc-160#createex

For a full description of the CToolBarCtrl Class and associated member functions
https://docs.microsoft.com/en-us/cpp/mfc/reference/ctoolbarctrl-class?view=msvc-160

The following short program creates a simple program with two buttons. Clicking either button will produce a message box.

Example


Download Code

Working with Bitmaps

Windows supports two types of bitmap: device-independent bitmaps (DIBs) and device-dependent bitmaps (DDBs).

A device-independent bitmap (DIB) stores image data in a standard format that is independent of the display hardware. Because the bitmap contains all the information required to describe the image, it can be copied between different computers, printers and display devices while maintaining a consistent appearance. DIBs are therefore the preferred format for storing bitmap files on disk and exchanging bitmap images between applications.

A device-dependent bitmap (DDB) is created in a format that is optimised for a particular display device. Since the bitmap format depends on the capabilities of the target device, it may not be suitable for use on different hardware without conversion. DDBs are generally used for fast screen drawing because they are stored in a format that is efficient for the graphics device currently being used.

The CBitmap Class

The CBitmap class encapsulates a Windows GDI bitmap and provides member functions for creating, loading and manipulating bitmap images. A CBitmap object normally represents a device-dependent bitmap (DDB). Although MFC provides the CBitmap class for GDI bitmaps, it does not provide a dedicated wrapper class for device-independent bitmaps. DIBs are normally manipulated using the Win32 API.

Before a bitmap can be displayed it must first be loaded into a CBitmap object. This is commonly achieved by loading a bitmap resource using the LoadBitmap() member function.

BOOL LoadBitmap(LPCTSTR lpszResourceName); BOOL LoadBitmap(UINT nIDResource);

where

lpszResourceName – Specifies the name of the bitmap resource.

nIDResource – Specifies the resource identifier of the bitmap resource.

Returns non-zero if successful; otherwise 0.


Displaying a Bitmap

Displaying a bitmap involves copying the bitmap from memory onto the window’s device context.

The usual procedure is:

  1. Create a device context for the window.
  2. Create a compatible memory device context.
  3. Select the bitmap into the memory device context.
  4. Copy the bitmap from the memory device context to the window using BitBlt().

For example

CClientDC dc(this);          // Window device context

CDC memDC;
memDC.CreateCompatibleDC(&dc);

memDC.SelectObject(&bmp);

dc.BitBlt(x, y, width, height,
          &memDC, 0, 0, SRCCOPY);

where

x, y – Destination coordinates.

width, height – Size of the bitmap to copy.

SRCCOPY – Copies the source bitmap directly to the destination.

The use of a memory device context prevents unnecessary screen flicker and allows graphics to be composed in memory before being displayed.


CreateCompatibleDC()

The CreateCompatibleDC() member function creates a memory device context that is compatible with an existing device context.

BOOL CreateCompatibleDC(CDC* pDC);

where

pDC – Points to the device context with which the new memory device context should be compatible. Passing NULL creates a memory device context compatible with the application’s current display.

Returns non-zero if successful; otherwise 0.

A compatible memory device context is typically used together with BitBlt() for bitmap drawing and double buffering.


BitBlt()

The BitBlt() (Bit Block Transfer) member function copies a rectangular block of pixels from one device context to another.

BOOL BitBlt(
    int x,
    int y,
    int nWidth,
    int nHeight,
    CDC* pSrcDC,
    int xSrc,
    int ySrc,
    DWORD dwRop
);

where

x, y – Destination coordinates.

nWidth, nHeight – Width and height of the area to copy.

pSrcDC – Source device context.

xSrc, ySrc – Upper-left corner of the source image.

dwRop – Raster operation defining how the pixels are copied.

Returns non-zero if successful; otherwise 0.

The most commonly used raster operation is

SRCCOPY – Copies the source bitmap directly to the destination.

Other useful raster operations include:

Raster operationDescription
SRCCOPYCopies source directly to destination.
SRCANDPerforms a bitwise AND between source and destination.
SRCPAINTPerforms a bitwise OR between source and destination.
SRCINVERTPerforms a bitwise XOR between source and destination.
NOTSRCCOPYCopies the inverted source bitmap.
BLACKNESSFills the destination rectangle with black.
WHITENESSFills the destination rectangle with white.

Double Buffering

One of the most common uses of a memory device context is double buffering.

Instead of drawing directly onto the screen, all graphics are first drawn onto an off-screen bitmap stored in memory. When drawing is complete, the entire image is copied to the window using BitBlt(). Because the user only sees the finished image, screen flicker is greatly reduced.

Double buffering is widely used in drawing programs, animation, games and applications that frequently repaint their windows.


Repainting the Screen Using Bitmaps

A memory bitmap can also be used to maintain a permanent copy of the window contents.

Instead of redrawing every graphical object whenever a WM_PAINT message is received, the application draws all graphics to an off-screen bitmap. Whenever the window requires repainting, the bitmap is simply copied back to the screen using BitBlt(). This technique simplifies repainting and is considerably faster than recreating every graphical object individually.


Example

The following example creates a simple drawing program. Each mouse click draws a line from the previous cursor position to the current cursor position. Rather than drawing directly to the screen, all drawing operations are performed on an off-screen bitmap stored in a compatible memory device context. Whenever the window receives a repaint request, the contents of the memory bitmap are copied back to the screen using BitBlt(), allowing the drawing to be restored without maintaining a list of every line drawn.

Common Dialog Box

Common dialog boxes are a collection of predefined dialog boxes supplied by Windows for performing frequently used tasks such as opening and saving files, selecting fonts and colours, printing documents, and configuring page settings. Using these standard dialogs gives applications a consistent appearance and behaviour while reducing the amount of code the developer needs to write.

All MFC common dialog classes are derived from the CCommonDialog base class. Each derived class encapsulates one of the standard Windows common dialog boxes and provides member functions and constructors for configuring and displaying the dialog.

The appearance and behaviour of a common dialog box can be customised by supplying parameters to the class constructor or by setting one or more option flags before the dialog is displayed.

In MFC applications, the common dialog classes are declared in the afxdlgs.h header file, which is normally included automatically through afxwin.h.

The principal MFC common dialog classes are listed below.

ClassPurpose
CColorDialogAllows the user to select or create a color
CFileDialogAllows the user to open or save a file
CFindReplaceDialogAllows the user to substitute one string for another
CFontDialogAllows the user to select a font from a list of available fonts
COleDialogUseful for inserting OLE objects
CPageSetupDialogAllows the user to set page measurement parameters
CPrintDialogAllows the user to set up the printer and print a document
CPrintDialogExPrinting and Print Preview for Windows 2000

For further detailed reading
https://docs.microsoft.com/en-us/cpp/mfc/reference/ccommondialog-class?view=vs-2019

Example

The following short program illustrates the use of the CColourDialog by changing the background colour of the windows to match that selected from the colour dialog box

Dialog Windows

A dialog box is a temporary pop-up window that an application uses to prompt the user for additional information or input. A dialog box usually contains one or more controls (child windows) that allow the user to enter text, choose options, or control the operation of the application.

MFC encapsulates dialog box functionality in the CDialog class. Dialog boxes are classified as either modal or modeless, depending on their behaviour. A modal dialog box prevents the user from interacting with the rest of the application until the dialog box is closed. In contrast, a modeless dialog box allows the user to continue working with the application while the dialog remains open.

Although it is possible to instantiate the CDialog class directly for very simple dialogs, most applications derive their own dialog class from CDialog (or CDialogEx in newer versions of MFC). The derived class contains its own message map and message handlers because messages generated by controls within the dialog are sent to the dialog itself rather than the application’s main window.

Dialog boxes are normally defined as resources using the Visual Studio resource editor and are compiled into the application’s executable. A dialog box is typically closed when it receives an IDOK or IDCANCEL command. These commands are processed by the virtual member functions OnOK() and OnCancel(), both of which can be overridden to perform custom validation or cleanup before the dialog closes.


Creating a Modal Dialog Box

A modal dialog box is created by constructing a dialog object using the dialog resource identifier and then calling the member function DoModal(). The constructors are:

CDialog(LPCTSTR lpszTemplateName, CWnd* pParentWnd = NULL); CDialog(UINT nIDTemplate, CWnd* pParentWnd = NULL);

where

  • lpszTemplateName – Specifies the name of the dialog-box template resource.
  • nIDTemplate – Specifies the resource identifier of the dialog-box template.
  • pParentWnd – Points to the parent window. If NULL, the application’s main window is used.

The DoModal() member function creates the dialog, displays it, enters its own message loop, and does not return until the dialog is closed.

Its return value is typically:

  • IDOK – The user accepted the dialog.
  • IDCANCEL – The user cancelled or closed the dialog.
  • -1 – The dialog could not be created.

Because DoModal() does not return until the dialog is closed, modal dialog objects are usually created as local (stack) variables.


Creating a Modeless Dialog Box

A modeless dialog box is created using the default constructor followed by a call to the Create() member function.

BOOL Create(UINT nIDTemplate, CWnd* pParentWnd = NULL); BOOL Create(LPCTSTR lpszTemplateName, CWnd* pParentWnd = NULL);

where

  • nIDTemplate – Specifies the dialog resource identifier.
  • lpszTemplateName – Specifies the name of the dialog template.
  • pParentWnd – Points to the parent window.

Create() returns a nonzero value if the dialog is successfully created; otherwise it returns 0.

Unlike a modal dialog, Create() returns immediately after the dialog is displayed, allowing the user to continue interacting with the rest of the application. Because the creating function may return while the dialog is still visible, modeless dialogs are normally allocated dynamically using new. They must also be explicitly destroyed when they are no longer required, typically by calling DestroyWindow(), after which the dialog object is usually deleted.

The code section below demonstrates a modeless and modal dialog box.


Dialog-Based Applications

A dialog-based application is an application whose main window is a dialog box rather than a frame window. This approach simplifies application development because controls such as buttons, edit boxes, list boxes, and combo boxes can be placed directly onto the main window using the Visual Studio resource editor. A familiar example of a dialog-based application is the Windows Calculator.

In an MFC dialog-based application, the application’s main window is represented by a class derived from the CDialog class (or CDialogEx in newer versions of MFC). The derived class contains the dialog’s controls, message map, and event handlers. During application initialisation, an instance of this dialog class is created and assigned to the MFC application member variable m_pMainWnd. The dialog is then displayed by calling the DoModal() member function.

Unlike an SDI or MDI application, a dialog-based application does not normally contain a frame window, document, or view architecture. Instead, the dialog itself provides the primary user interface and remains active until it is closed. When the dialog is dismissed by the user, DoModal() returns and the application normally terminates.

Download Code