<Previous Lesson

Visual Programming

Next Lesson>

Lesson#20

Dialogs

20.1 DIALOG BOX TEMPLATES 2
20.1.1 DIALOG BOX TEMPLATES STYLES 2
20.1.2 DIALOG BOX MEASUREMENTS 5
20.1.3 DIALOG BOX CONTROLS 6
20.1.4 DIALOG BOX WINDOW MENU 7
20.1.5 DIALOG BOX FONTS 8
20.1.6 TEMPLATES IN MEMORY 8
Template Header 9
Control Definitions 9
20.2 WHEN TO USE A DIALOGBOX 10
20.3 DIALOG BOX OWNER WINDOW 11
20.4 CREATING MODAL DIALOG 12
20.5 DIALOG PROCEDURE 13
20.6 THE WM_INITDIALOG MESSAGE 14
20.7 USING DIALOG PROCEDURE 15
20.8 SCREEN SHOT OF ABOUT MODAL DIALOG 15
20.9 DIALOG BOX MESSAGES AND FUNCTIONS 16
20.9.1 RETRIEVE HANDLE OF THE CONTROL 16
20.9.2 SET WINDOW TEXT 16
20.9.3 RETRIEVE THE IDENTIFIER OF THE SPECIFIED CONTROL 17
20.9.4 RETRIEVE THE TEXT ASSOCIATED WITH THE SPECIFIED CONTROL IN DIALOG 18
20.9.5 SENDS A MESSAGE TO THE SPECIFIED CONTROL IN A DIALOG BOX 18
20.9.6 SETTING OR GETTING TEXT ASSOCIATED WITH A WINDOW OR CONTROL 20
20.9.7 SET OR RETRIEVE CURRENT SELECTION IN AN EDIT CONTROL 20
20.10 CREATING MODELESS DIALOG 20
20.10.1 SHOWING MODELESS DIALOG 21
20.10.2 PROCESSING DIALOG MESSAGES 23
20.10.3 MESSAGE LOOP TO DISPATCH MESSAGES TO A MODELESS DIALOG 24
20.11 WINDOWS COMMON DIALOGS 24
20.11.1 OPEN FILE DIALOG 24
20.11.2 CHOOSE FONT DIALOG 25
20.11.3 CHOOSE COLOR DIALOG 25
20.11.4 PRINT DIALOG 26
SUMMARY 26
EXERCISES 27
Dialogs 2

20.1 Dialog Box Templates

A dialog box template is binary data that describes the dialog box, defining its height,
width, style, and the controls it contains. To create a dialog box, the system either loads a
dialog box template from the resources in the application's executable file or uses the
template passed to it in global memory by the application. In either case, the application
must supply a template when creating a dialog box.
A developer creates template resources by using a resource compiler or a dialog box
editor. A resource compiler converts a text description into a binary resource, and a
dialog box editor saves an interactively constructed dialog box as a binary resource.
To create a dialog box without using template resources, you must create a template in
memory and pass it to the CreateDialogIndirectParam or DialogBoxIndirectParam

function, or to the CreateDialogIndirect or DialogBoxIndirect macro.
A dialog box template in memory consists of a header that describes the dialog box,
followed by one or more additional blocks of data that describe each of the controls in the
dialog box. The template can use either the standard format or the extended format. In a
standard template, the header is a DLGTEMPLATE structure followed by additional
variable-length arrays; and the data for each control consists of a DLGITEMTEMPLATE
structure followed by additional variable-length arrays. In an extended dialog box
template, the header uses the DLGTEMPLATEEX format and the control definitions use
the DLGITEMTEMPLATEEX format.
You can create a memory template by allocating a global memory object and filling it
with the standard or extended header and control definitions. A memory template is
identical in form and content to a template resource. Many applications that use memory
templates first use the LoadResource function to load a template resource into memory,
and then modify the loaded resource to create a new memory template.

20.1.1 Dialog Box Templates Styles

Every dialog box template specifies a combination of style values that define the
appearance and features of the dialog box. The style values can be window styles, such as
WS_POPUP and WS_SYSMENU, and dialog box styles, such as DS_MODALFRAME.
The number and type of styles for a template depends on the type and purpose of the
dialog box.
The system passes all window styles specified in the template to the CreateWindowEx
function when creating the dialog box. The system may pass one or more extended styles
depending on the specified dialog box styles. For example, when the template specifies
DS_MODALFRAME, the system uses WS_EX_DLGMODALFRAME when creating
the dialog box.
Dialogs 3
Most dialog boxes are pop-up windows that have a window menu and a title bar.
Therefore, the typical template specifies the WS_POPUP, WS_SYSMENU, and
WS_CAPTION styles. The template also specifies a border style: WS_BORDER for
modeless dialog boxes and DS_MODALFRAME for modal dialog boxes. A template
may specify a window type other than pop-up (such as WS_OVERLAPPED) if it creates
a customized window instead of a dialog box.
The system always displays a modal dialog box regardless of whether the WS_VISIBLE
style is specified. When the template for a modeless dialog box specifies the
WS_VISIBLE style, the system automatically displays the dialog box when it is created.
Otherwise, the application is responsible for displaying the dialog box by using the
ShowWindow function.
The following table lists the dialog box styles that you can specify when you create a
dialog box. You can use these styles in calls to the CreateWindow and
CreateWindowEx functions, in the style member of the DLGTEMPLATE and
DLGTEMPLATEEX structures, and in the statement of a dialog box definition in a
resource file.

Value Meaning

DS_3DLOOK
Gives the dialog box a nonbold font, and draws threedimensional
borders around control windows in the dialog box.
The DS_3DLOOK style is required only by applications
compiled for Windows NT 3.51. The system automatically
applies the three-dimensional look to dialog boxes created by
applications compiled for Windows 95/98/Me and later
versions of Windows NT.
DS_ABSALIGN
Indicates that the coordinates of the dialog box are screen
coordinates. If this style is not specified, the coordinates are
client coordinates.
DS_CENTER
Centers the dialog box in the working area of the monitor that
contains the owner window. If no owner window is specified,
the dialog box is centered in the working area of a monitor
determined by the system. The working area is the area not
obscured by the taskbar or any application bars.
DS_CENTERMOUSE Centers the dialog box on the mouse cursor.
DS_CONTEXTHELP
Includes a question mark in the title bar of the dialog box.
When the user clicks the question mark, the cursor changes to
a question mark with a pointer. If the user then clicks a control
in the dialog box, the control receives a WM_HELP message.
The control should pass the message to the dialog box
procedure, which should call the function using the
HELP_WM_HELP command. The help application displays a
pop-up window that typically contains help for the control.
Dialogs 4
Note that DS_CONTEXTHELP is only a placeholder. When
the dialog box is created, the system checks for
DS_CONTEXTHELP and, if it is there, adds
WS_EX_CONTEXTHELP to the extended style of the dialog
box. WS_EX_CONTEXTHELP cannot be used with the
WS_MAXIMIZEBOX or WS_MINIMIZEBOX styles.
DS_CONTROL
Creates a dialog box that works well as a child window of
another dialog box, much like a page in a property sheet. This
style allows the user to tab among the control windows of a
child dialog box, use its accelerator keys, and so on.
DS_FIXEDSYS
Causes the dialog box to use the SYSTEM_FIXED_FONT
instead of the default SYSTEM_FONT. This is a monospace
font compatible with the System font in 16-bit versions of
Windows earlier than 3.0.
DS_LOCALEDIT
Applies to 16-bit applications only. This style directs edit
controls in the dialog box to allocate memory from the
application's data segment. Otherwise, edit controls allocate
storage from a global memory object.
DS_MODALFRAME
Creates a dialog box with a modal dialog-box frame that can
be combined with a title bar and window menu by specifying
the WS_CAPTION and WS_SYSMENU styles.
DS_NOFAILCREATE
Windows 95/98/Me: Creates the dialog box even if errors
occur — for example, if a child window cannot be created or if
the system cannot create a special data segment for an edit
control.
DS_NOIDLEMSG
Suppresses WM_ENTERIDLE messages that the system
would otherwise send to the owner of the dialog box while the
dialog box is displayed.
DS_SETFONT
Indicates that the header of the dialog box template (either
standard or extended) contains additional data specifying the
font to use for text in the client area and controls of the dialog
box. If possible, the system selects a font according to the
specified font data. The system passes a handle to the font to
the dialog box and to each control by sending them the
WM_SETFONT message. For descriptions of the format of
this font data, see DLGTEMPLATE and
DLGTEMPLATEEX.
If neither DS_SETFONT nor DS_SHELLFONT is specified,
the dialog box template does not include the font data.
DS_SETFOREGROUND
Causes the system to use the SetForegroundWindow function
to bring the dialog box to the foreground. This style is useful
for modal dialog boxes that require immediate attention from
Dialogs 5
the user regardless of whether the owner window is the
foreground window.
DS_SHELLFONT
Indicates that the dialog box should use the system font. The
typeface member of the extended dialog box template must be
set to MS Shell Dialog. Otherwise, this style has no effect. It is
also recommended that you use the DIALOGEX Resource,
rather than the DIALOG Resource.
The system selects a font using the font data specified in the
pointsize, weight, and italic members. The system passes a
handle to the font to the dialog box and to each control by
sending them the WM_SETFONT message. For descriptions
of the format of this font data, see DLGTEMPLATEEX.
If neither DS_SHELLFONT nor DS_SETFONT is specified,
the extended dialog box template does not include the font
data.
DS_SYSMODAL
This style is obsolete and is included for compatibility with 16-
bit versions of Windows. If you specify this style, the system
creates the dialog box with the WS_EX_TOPMOST style.
This style does not prevent the user from accessing other
windows on the desktop.
Do not combine this style with the DS_CONTROL style.

20.1.2 Dialog Box Measurements

Every dialog box template contains measurements that specify the position, width, and
height of the dialog box and the controls it contains. These measurements are device
independent, so an application can use a single template to create the same dialog box for
all types of display devices. This ensures that a dialog box will have the same proportions
and appearance on all screens despite differing resolutions and aspect ratios between
screens.
The measurements in a dialog box template are specified in dialog template units. To
convert measurements from dialog template units to screen units (pixels), use the
MapDialogRect function, which takes into account the font used by the dialog box and
correctly converts a rectangle from dialog template units into pixels. For dialog boxes
that use the system font, you can use the GetDialogBaseUnits function to perform the
conversion calculations yourself, although using MapDialogRect is simpler.
The template must specify the initial coordinates of the upper left corner of the dialog
box. Usually the coordinates are relative to the upper left corner of the owner window's
client area. When the template specifies the DS_ABSALIGN style or the dialog box has
Dialogs 6
no owner, the position is relative to the upper left corner of the screen. The system sets
this initial position when creating the dialog box, but permits an application to adjust the
position before displaying the dialog box. For example, an application can retrieve the
dimensions of the owner window, calculate a new position that centers the dialog box in
the owner window, and then set the position by using the SetWindowPos function.
The template should specify a dialog box width and height that does not exceed the width
and height of the screen and ensures that all controls are within the client area of the
dialog box. Although the system permits a dialog box to be any size, creating one that is
too small or too large can prevent the user from providing input, defeating the purpose of
the dialog box. Many applications use more than one dialog box when there are a large
number of controls. In such cases, the initial dialog box usually contains one or more
buttons that the user can choose to display the next dialog box.

20.1.3 Dialog Box Controls

The template specifies the position, width, height, style, identifier, and window class for
each control in the dialog box. The system creates each control by passing this data to the
CreateWindowEx function. Controls are created in the order they are specified in the
template. The template should specify the appropriate number, type, and order of controls
to ensure that the user can enter the input needed to complete the task associated with the
dialog box.
For each control, the template specifies style values that define the appearance and
operation of the control. Every control is a child window and therefore must have the
WS_CHILD style. To ensure that the control is visible when the dialog box is displayed,
each control must also have the WS_VISIBLE style. Other commonly used window
styles are WS_BORDER for controls that have optional borders, WS_DISABLED for
controls that should be disabled when the dialog box is initially created, and
WS_TABSTOP and WS_GROUP for controls that can be accessed using the keyboard.
The WS_TABSTOP and WS_GROUP styles are used in conjunction with the dialog
keyboard interface described later in this topic.
The template may also specify control styles specific to the control's window class. For
example, a template that specifies a button control must give a button control style such
as BS_PUSHBUTTON or BS_CHECKBOX. The system passes the control styles to the
control window procedure through the WM_CREATE message, allowing the procedure
to adapt the appearance and operation of the control.
The system converts the position coordinates and the width and height measurements
from dialog base units to pixels, before passing these to CreateWindowEx. When the
system creates a control, it specifies the dialog box as the parent window. This means the
system always interprets the position coordinates of the control as client coordinates,
relative to the upper left corner of the dialog box's client area.
Dialogs 7
The template specifies the window class for each control. Typical dialog box contains
controls belonging to the predefined control window classes such as the button and edit
control window classes. In this case, the template specifies window classes by supplying
the corresponding predefined atom values for the classes. When a dialog box contains a
control belonging to a custom control window class, the template gives the name of that
registered window class or the atom value currently associated with the name.
Each control in a dialog box must have a unique identifier to distinguish it from other
controls. Controls send information to the dialog box procedure through
WM_COMMAND messages, so the control identifiers are essential for the procedure to
determine which control sent a specified message. The only exception to this rule is
control identifiers for static controls. Static controls do not require unique identifiers
because they send no WM_COMMAND messages.
To permit the user to close the dialog box, the template should specify at least one push
button and give it the control identifier IDCANCEL. To permit the user to choose
between completing or canceling the task associated with the dialog box, the template
should specify two push buttons, labeled OK and Cancel, with control identifiers of
IDOK and IDCANCEL, respectively.
A template also specifies optional text and creation data for a control. The text typically
provides labels for button controls or specifies the initial content of a static text control.
The creation data is one or more bytes of data that the system passes to the control
window procedure when creating the control. Creation data is useful for controls that
require more information about their initial content or style than is specified by other
data. For example, an application can use creation data to set the initial setting and range
for a scroll bar control.

20.1.4 Dialog Box Window Menu

The system gives a dialog box a window menu when the template specifies the
WS_SYSMENU style. To prevent inappropriate input, the system automatically disables
all items in the menu except Move and Close. The user can click Move to move the
dialog box. When the user clicks Close, the system sends a WM_COMMAND message
to the dialog box procedure with the wParam parameter set to IDCANCEL. This is
identical to the message sent by the Cancel button when the user clicks it. The
recommended action for this message is to close the dialog box and cancel the requested
task.
Although other menus in dialog boxes are not recommended, a dialog box template can
specify a menu by supplying the identifier or the name of a menu resource. In this case,
the system loads the resource and creates the menu for the dialog box. Applications
typically use menu identifiers or names in templates when using the templates to create
custom windows rather than dialog boxes.
Dialogs 8

20.1.5 Dialog Box Fonts

The system uses the average character width of the dialog box font to calculate the
position and dimensions of the dialog box. By default, the system draws all text in a
dialog box using the SYSTEM_FONT font.
To specify a font for a dialog box other than the default, you must create the dialog box
using a dialog box template. In a template resource, use the FONT Statement. In a dialog
box template, set the DS_SETFONT or DS_SHELLFONT style and specify a point size
and a typeface name. Even if a dialog box template specifies a font in this manner, the
system always uses the system font for the dialog box title and dialog box menus.
When the dialog box has the DS_SETFONT or DS_SHELLFONT style, the system
sends a WM_SETFONT message to the dialog box procedure and to each control as it
creates the control. The dialog box procedure is responsible for saving the font handle
passed with the WM_SETFONT message and selecting the handle into the display
device context whenever it writes text to the window. Predefined controls do this by
default.
The system font can vary between different versions of Windows. To have your
application use the system font no matter which system it is running on, use
DS_SHELLFONT with the typeface MS Shell Dlg, and use the DIALOGEX Resource

instead of the DIALOG Resource. The system maps this typeface such that your dialog
box will use the Tahoma font on Windows 2000/Windows XP, and the MS Sans Serif
font on earlier systems.
Note that DS_SHELLFONT has no effect if the typeface is not MS Shell Dlg.

20.1.6 Templates in Memory

A dialog box template in memory consists of a header that describes the dialog box,
followed by one or more additional blocks of data that describe each of the controls in the
dialog box. The template can use either the standard format or the extended format. In a
standard template, the header is a DLGTEMPLATE structure followed by additional
variable-length arrays. The data for each control consists of a DLGITEMTEMPLATE

structure followed by additional variable-length arrays. In an extended dialog box
template, the header uses the DLGTEMPLATEEX format and the control definitions
use the DLGITEMTEMPLATEEX format.
To distinguish between a standard template and an extended template, check the first 16-
bits of a dialog box template. In an extended template, the first WORD is 0xFFFF; any
other value indicates a standard template.
If you create a dialog template in memory, you must ensure that the each of the
DLGITEMTEMPLATE or DLGITEMTEMPLATEEX control definitions is aligned
on DWORD boundaries. In addition, any creation data that follows a control definition
Dialogs 9
must be aligned on a DWORD boundary. All of the other variable-length arrays in a
dialog box template must be aligned on WORD boundaries.

Template Header

In both the standard and extended templates for dialog boxes, the header includes the
following general information:
The location and dimensions of the dialog box
The window and dialog box styles for the dialog box
The number of controls in the dialog box. This value determines the number of
DLGITEMTEMPLATE or DLGITEMTEMPLATEEX control definitions in
the template.
An optional menu resource for the dialog box. The template can indicate that the
dialog box does not have a menu, or it can specify an ordinal value or nullterminated
Unicode string that identifies a menu resource in an executable file.
The window class of the dialog box. This can be either the predefined dialog box
class, or an ordinal value or null-terminated Unicode string that identifies a
registered window class.
A null-terminated Unicode string that specifies the title for the dialog box
window. If the string is empty, the title bar of the dialog box is blank. If the dialog
box does not have the WS_CAPTION style, the system sets the title to the
specified string but does not display it.
If the dialog box has the DS_SETFONT style, the header specifies the point size
and typeface name of the font to use for the text in the client area and controls of
the dialog box.
In an extended template, the DLGTEMPLATEEX header also specifies the following
additional information:
The help context identifier of the dialog box window when the system sends a
WM_HELP message.
If the dialog box has the DS_SETFONT or DS_SHELLFONT style, the header
specifies the font weight and indicates whether the font is italic.

Control Definitions

Following the template header is one or more control definitions that describe the
controls of the dialog box. In both the standard and extended templates, the dialog box
header has a member that indicates the number of control definitions in the template. In a
standard template, each control definition consists of a DLGITEMTEMPLATE

structure followed by additional variable-length arrays. In an extended template, the
control definitions use the DLGITEMTEMPLATEEX format.
In both the standard and extended templates, the control definition includes the following
information:
Dialogs 10
The location and dimensions of the control.
The window and control styles for the control.
The control identifier.
The window class of the control. This can be either the ordinal value of a
predefined system class or a null-terminated Unicode string that specifies the
name of a registered window class.
A null-terminated Unicode string that specifies the initial text of the control, or an
ordinal value that identifies a resource, such as an icon, in an executable file.
An optional variable-length block of creation data. When the system creates the
control, it passes a pointer to this data in the lParam parameter of the
WM_CREATE message that it sends to the control.
In an extended template, the control definition also specifies a help context identifier for
the control when the system sends a WM_HELP message.

20.2 When to Use a DialogBox

Most applications use dialog boxes to prompt for additional information for menu items
that require user input. Using a dialog box is the only recommended way for an
application to retrieve the input. For example, a typical Open menu item requires the
name of a file to open, so an application should use a dialog box to prompt the user for
the name. In such cases, the application creates the dialog box when the user clicks the
menu item and destroys the dialog box immediately after the user supplies the
information.
Many applications also use dialog boxes to display information or options while the user
works in another window. For example, word processing applications often use a dialog
box with a text-search option. While the application searches for the text, the dialog box
remains on the screen. The user can then return to the dialog box and search for the same
word again; or the user can change the entry in the dialog box and search for a new word.
Applications that use dialog boxes in this way typically create one when the user clicks
the menu item and continue to display it for as long as the application runs or until the
user explicitly closes the dialog box.
To support the different ways applications use dialog boxes, there are two types of dialog
box: modal and modeless. A modal dialog box requires the user to supply information or
cancel the dialog box before allowing the application to continue. Applications use modal
dialog boxes in conjunction with menu items that require additional information before
they can proceed. A modeless dialog box allows the user to supply information and return
to the previous task without closing the dialog box. Modal dialog boxes are simpler to
manage than modeless dialog boxes because they are created, perform their task, and are
destroyed by calling a single function.
To create either a modal or modeless dialog box, an application must supply a dialog box
template to describe the dialog box style and content; the application must also supply a
dialog box procedure to carry out tasks. The dialog box template is a binary description
Dialogs 11
of the dialog box and the controls it contains. The developer can create this template as a
resource to be loaded from the application's executable file, or created in memory while
the application runs. The dialog box procedure is an application-defined callback
function that the system calls when it has input for the dialog box or tasks for the dialog
box to carry out. Although a dialog box procedure is similar to a window procedure, it
does not have the same responsibilities.
An application typically creates a dialog box by using either the DialogBox or
CreateDialog function. DialogBox creates a modal dialog box; CreateDialog creates a
modeless dialog box. These two functions load a dialog box template from the
application's executable file and create a pop-up window that matches the template's
specifications. There are other functions that create a dialog box by using templates in
memory; they pass additional information to the dialog box procedure as the dialog box is
created.
Dialog boxes usually belong to a predefined, exclusive window class. The system uses
this window class and its corresponding window procedure for both modal and modeless
dialog boxes. When the function is called, it creates the window for the dialog box as
well as the windows for the controls in the dialog box, and then sends selected messages
to the dialog box procedure. While the dialog box is visible, the predefined window
procedure manages all messages, processing some messages and passing others to the
dialog box procedure so that the procedure can carry out tasks. Applications do not have
direct access to the predefined window class or window procedure, but they can use the
dialog box template and dialog box procedure to modify the style and behavior of a
dialog box.

20.3 Dialog Box Owner window

Most dialog boxes have an owner window (or more simply, an owner). When creating the
dialog box, the application sets the owner by specifying the owner's window handle. The
system uses the owner to determine the position of the dialog box in the Z order so that
the dialog box is always positioned above its owner. Also, the system can send messages
to the window procedure of the owner, notifying it of events in the dialog box.
The system automatically hides or destroys the dialog box whenever its owner is hidden
or destroyed. This means the dialog box procedure requires no special processing to
detect changes to the state of the owner window.
Because the typical dialog box is used in conjunction with a menu item, the owner
window is usually the window containing the menu. Although it is possible to create a
dialog box that has no owner, it is not recommended. For example, when a modal dialog
box has no owner, the system does not disable any of the application's other windows and
allows the user to continue to carry out work in the other windows, defeating the purpose
of the modal dialog box.
Dialogs 12
When a modeless dialog box has no owner, the system neither hides nor destroys the
dialog box when other windows in the application are hidden or destroyed. Although this
does not defeat the purpose of the modeless dialog box, it requires that the application
carry out special processing to ensure the dialog box is hidden and destroyed at
appropriate times.

20.4 Creating Modal Dialog

The DialogBoxParam function creates a modal dialog box from a dialog box template
resource. Before displaying the dialog box, the function passes an application-defined
value to the dialog box procedure as the lParam parameter of the WM_INITDIALOG
message. An application can use this value to initialize dialog box controls.
INT_PTR DialogBoxParam(
HINSTANCE hInstance, //handle to the istance
LPCTSTR lpTemplateName, //name of the template*/
HWND hWndParent, //parent handle if any*/
DLGPROC lpDialogFunc, //dialog function
procedure*/
LPARAM dwInitParam /*initialize parameters*/
);
hInstance: Handle to the module whose executable file contains the dialog box template.
lpTemplateName: Specifies the dialog box template. This parameter is either the pointer
to a null-terminated character string that specifies the name of the dialog box template or
an integer value that specifies the resource identifier of the dialog box template. If the
parameter specifies a resource identifier, its high-order word must be zero and its loworder
word must contain the identifier. You can use the MAKEINTRESOURCE macro to
create this value.
hWndParent: Handle to the window that owns the dialog box.
lpDialogFunc: Pointer to the dialog box procedure. For more information about the
dialog box procedure, see DialogProc.
dwInitParam: Specifies the value to pass to the dialog box in the lParam parameter of the
WM_INITDIALOG message.
Return Value: If the function succeeds, the return value is the value of the nResult
parameter specified in the call to the EndDialog function used to terminate the dialog
box.
If the function fails because the hWndParent parameter is invalid, the return value is zero.
The function returns zero in this case for compatibility with previous versions of
Dialogs 13
Microsoft® Windows®. If the function fails for any other reason, the return value is –1.
To get extended error information, call GetLastError.
The DialogBoxParam function uses the CreateWindowEx function to create the dialog
box. DialogBoxParam then sends a WM_INITDIALOG message (and a
WM_SETFONT message if the template specifies the DS_SETFONT or
DS_SHELLFONT style) to the dialog box procedure. The function displays the dialog
box (regardless of whether the template specifies the WS_VISIBLE style), disables the
owner window, and starts its own message loop to retrieve and dispatch messages for the
dialog box.
When the dialog box procedure calls the EndDialog function, DialogBoxParam destroys
the dialog box, ends the message loop, enables the owner window (if previously enabled),
and returns the nResult parameter specified by the dialog box procedure when it called
EndDialog.

20.5 Dialog Procedure

The DialogProc function is an application-defined callback function used with the
CreateDialog and DialogBox families of functions. It processes messages sent to a modal
or modeless dialog box. The DLGPROC type defines a pointer to this callback function.
DialogProc is a placeholder for the application-defined function name.
INT_PTR CALLBACK DialogProc(
HWND hwndDlg, //handle to the dialog
UINT uMsg, //message structure
WPARAM wParam, //wParam
LPARAM lParam //lParam
);
hwndDlg: Handle to the dialog box.
uMsg: Specifies the message.
wParam: Specifies additional message-specific information.
lParam: Specifies additional message-specific information.
Return Value: Typically, the dialog box procedure should return TRUE if it processed the
message, and FALSE if it did not. If the dialog box procedure returns FALSE, the dialog
manager performs the default dialog operation in response to the message.
If the dialog box procedure processes a message that requires a specific return value, the
dialog box procedure should set the desired return value by calling
SetWindowLong(hwndDlg, DWL_MSGRESULT, lResult) immediately before returning
Dialogs 14
TRUE. Note that you must call SetWindowLong immediately before returning TRUE;
doing so earlier may result in the DWL_MSGRESULT value being overwritten by a
nested dialog box message.
You should use the dialog box procedure only if you use the dialog box class for the
dialog box. This is the default class and is used when no explicit class is specified in the
dialog box template. Although the dialog box procedure is similar to a window
procedure, it must not call the DefWindowProc function to process unwanted messages.
Unwanted messages are processed internally by the dialog box window procedure.

20.6 The WM_INITDIALOG Message

The WM_INITDIALOG message is sent to the dialog box procedure immediately
before a dialog box is displayed. Dialog box procedures typically use this message to
initialize controls and carry out any other initialization tasks that affect the appearance of
the dialog box.
WM_INITDIALOG
WPARAM wParam
LPARAM lParam;
wParam
Handle to the control to receive the default keyboard focus. The system assigns
the default keyboard focus only if the dialog box procedure returns TRUE.
lParam
Specifies additional initialization data. This data is passed to the system as the
lParam parameter in a call to the CreateDialogIndirectParam,
CreateDialogParam, DialogBoxIndirectParam, or DialogBoxParam function used
to create the dialog box. For property sheets, this parameter is a pointer to the
PROPSHEETPAGE structure used to create the page. This parameter is zero if
any other dialog box creation function is used.
Return Value:
The dialog box procedure should return TRUE to direct the system to set the
keyboard focus to the control specified by wParam. Otherwise, it should return
FALSE to prevent the system from setting the default keyboard focus.
The dialog box procedure should return the value directly. The
DWL_MSGRESULT value set by the SetWindowLong function is ignored.
The control to receive the default keyboard focus is always the first control in the dialog
box that is visible, not disabled, and that has the WS_TABSTOP style. When the dialog
box procedure returns TRUE, the system checks the control to ensure that the procedure
Dialogs 15
has not disabled it. If it has been disabled, the system sets the keyboard focus to the next
control that is visible, not disabled, and has the WS_TABSTOP.
An application can return FALSE only if it has set the keyboard focus to one of the
controls of the dialog box.

20.7 Using Dialog Procedure

BOOL CALLBACK AboutAuthorDialog(HWND hDlg, UINT message,
WPARAM wParam, LPARAM lParam)
{
switch(message)
{
case WM_INITDIALOG:
return TRUE;
case WM_COMMAND:
switch(LOWORD(wParam))
{
case IDOK:
case IDCANCEL:
EndDialog(hDlg, 0);
return TRUE;
}
break;
}
return FALSE;
}

20.8 Screen Shot of About Modal Dialog

Dialogs 16

20.9 Dialog Box Messages and functions

Following are the description of dialog box functions.

20.9.1 Retrieve handle of the control

The GetDlgItem function retrieves a handle to a control in the specified dialog box.
HWND GetDlgItem(
HWND hDlg,
int nIDDlgItem
);
hDlg
[in] Handle to the dialog box that contains the control.
nIDDlgItem
[in] Specifies the identifier of the control to be retrieved.
Return Value:
If the function succeeds, the return value is the window handle of the specified
control.
If the function fails, the return value is NULL, indicating an invalid dialog box
handle or a nonexistent control. To get extended error information, call
GetLastError.
You can use the GetDlgItem function with any parent-child window pair, not just with
dialog boxes. As long as the hDlg parameter specifies a parent window and the child
window has a unique identifier (as specified by the hMenu parameter in the
CreateWindow or CreateWindowEx function that created the child window),

GetDlgItem returns a valid handle to the child window.

20.9.2 Set Window Text

The SetWindowText function changes the text of the specified window's title bar (if it
has one). If the specified window is a control, the text of the control is changed.
However, SetWindowText cannot change the text of a control in another application.
BOOL SetWindowText(
HWND hWnd,
LPCTSTR lpString
Dialogs 17
);
hWnd: Handle to the window or control whose text is to be changed.
lpString: Pointer to a null-terminated string to be used as the new title or control text.
Return Value:
If the function succeeds, the return value is nonzero.
If the target window is owned by the current process, SetWindowText causes a
WM_SETTEXT message to be sent to the specified window or control. If the control is a
list box control created with the WS_CAPTION style, however, SetWindowText sets the
text for the control, not for the list box entries.
To set the text of a control in another process, send the WM_SETTEXT message
directly instead of calling SetWindowText.
The SetWindowText function does not expand tab characters (ASCII code 0x09). Tab
characters are displayed as vertical bar (|) characters.

20.9.3 Retrieve the identifier of the specified control

The GetDlgCtrlID function retrieves the identifier of the specified control.
int GetDlgCtrlID(
HWND hwndCtl /*handle to the control whose id is
required*/
);
hwndCtl: Handle to the control.
Return Value
If the function succeeds, the return value is the identifier of the control.
GetDlgCtrlID accepts child window handles as well as handles of controls in dialog
boxes. An application sets the identifier for a child window when it creates the window
by assigning the identifier value to the hmenu parameter when calling the CreateWindow
or CreateWindowEx function.
Although GetDlgCtrlID may return a value if hwndCtl is a handle to a top-level window,
top-level windows cannot have identifiers and such a return value is never valid.
Dialogs 18

20.9.4 Retrieve the text associated with the specified control in Dialog

The GetDlgItemText function retrieves the title or text associated with a control in a
dialog box.
UINT GetDlgItemText(
HWND hDlg, /*handle to the dialog*/
int nIDDlgItem, /*id of the control */
LPTSTR lpString, /*text data*/
int nMaxCount /*maximum limit of the text*/
);
hDlg: Handle to the dialog box that contains the control.
nIDDlgItem: Specifies the identifier of the control whose title or text is to be retrieved.
lpString: Pointer to the buffer to receive the title or text.
nMaxCount: Specifies the maximum length, in TCHARs, of the string to be copied to
the buffer pointed to by lpString. If the length of the string, including the NULL
character, exceeds the limit, the string is truncated.
Return Value:
If the function succeeds, the return value specifies the number of TCHARs

copied to the buffer, not including the terminating NULL character.
If the function fails, the return value is zero. To get extended error information,
call GetLastError.
If the string is as long as or longer than the buffer, the buffer will contain the truncated
string with a terminating NULL character.
The GetDlgItemText function sends a WM_GETTEXT message to the control.
For the ANSI version of the function, the number of TCHARs is the number of bytes; for
the Unicode version, it is the number of characters.

20.9.5 Sends a message to the specified control in a dialog box

The SendDlgItemMessage function sends a message to the specified control in a dialog
box.
Dialogs 19
LRESULT SendDlgItemMessage(
HWND hDlg, /*handle to the dialog*/
int nIDDlgItem, /*id of the dialog item*/
UINT Msg, /*message type*/
WPARAM wParam, /*message wParam*/
LPARAM lParam /*message lParam*/
);
hDlg: Handle to the dialog box that contains the control.
nIDDlgItem: Specifies the identifier of the control that receives the message.
Msg: Specifies the message to be sent.
wParam: Specifies additional message-specific information.
lParam: Specifies additional message-specific information.
Return Value:
The return value specifies the result of the message processing and depends on the
message sent.
The SendDlgItemMessage function does not return until the message has been
processed.
Using SendDlgItemMessage is identical to retrieving a handle to the specified control
and calling the SendMessage function.

Example

In this example we send a message to edit control of EM_LIMITTEXT. This message
will limit the text to the given number say 25 in our case. Edit control will not receive
more than this limit.
EM_LIMITTEXT
wParam, // text length
lParam // not used; must be zero
//Sets the text limit of an edit control
//This message is sent by sendDlgItemMessage function.
SendDlgItemMessage(hEdit, EM_LIMITTEXT, (WPARAM)25, (LPARAM)0);
Dialogs 20

20.9.6 Setting or getting text associated with a window or control

WM_GETTEXT
wParam, // number of characters to copy
lParam // text buffer
Get Text Message retrieve the text associated with the window. This text could be a
caption text on any window or the text displayed in edit controls.
WM_SETTEXT
wParam, // not used; must be zero
lParam // window-text string (LPCTSTR)
Set Text set the text in window.
GetWindowText() function internally sends a WM_GETTEXT message to get the text.
SetWindowText() function internally sends a WM_SETTEXT message to set the text.

20.9.7 Set or retrieve current selection in an edit control

Setting or getting the current selection in an edit control we use two message
EM_SETSEL and EM_GETSEL.
EM_SETSEL or EM_GETSEL
wParam, // starting position
lParam // ending position

20.10 Creating Modeless Dialog

In our previous lecture, we have studied Modeless dialogs. Here we will create the
modeless dialogs.
Modeless dialogs are created with CreateDialog function.
HWND CreateDialog(
HINSTANCE hInstance, /*handle to the instance*/
LPCTSTR lpTemplate, /*template name*/
HWND hWndParent, /*handle to the parent*/
DLGPROC lpDialogFunc /*dialog function*/
);
hInstance: Handle to the module whose executable file contains the dialog box template.
lpTemplate: Specifies the dialog box template. This parameter is either the pointer to a
null-terminated character string that specifies the name of the dialog box template or an
integer value that specifies the resource identifier of the dialog box template. If the
Dialogs 21
parameter specifies a resource identifier, its high-order word must be zero and its loworder
word must contain the identifier. You can use the MAKEINTRESOURCE macro to
create this value.
hWndParent: Handle to the window that owns the dialog box.
lpDialogFunc: Pointer to the dialog box procedure.
Return Value:
If the function succeeds, the return value is the handle to the dialog box.
If the function fails, the return value is NULL. To get extended error information,
call GetLastError.
The CreateDialog function uses the CreateWindowEx function to create the dialog box.
CreateDialog, then sends a WM_INITDIALOG message (and a WM_SETFONT
message if the template specifies the DS_SETFONT or DS_SHELLFONT style) to the
dialog box procedure. The function displays the dialog box if the template specifies the
WS_VISIBLE style. Finally, CreateDialog returns the window handle to the dialog box.
After CreateDialog returns, the application displays the dialog box (if it is not already
displayed) by using the ShowWindow function. The application destroys the dialog box
by using the DestroyWindow function. To support keyboard navigation and other dialog
box functionality, the message loop for the dialog box must call the IsDialogMessage
function.

20.10.1 Showing Modeless Dialog

Modeless dialogs are initially hidden unless their property of visibility is not set.
For showing Dialog we can use ShowWindow function, which can show any window
created in Windows.
BOOL ShowWindow(
HWND hWnd, /*handle to the window*/
int nCmdShow /*show style*/
);
hWnd: Handle to the window.
nCmdShow: Specifies how the window is to be shown. This parameter is ignored the first
time an application calls ShowWindow, if the program that launched the application
provides a STARTUPINFO structure. Otherwise, the first time ShowWindow is called,
the value should be the value obtained by the WinMain function in its nCmdShow
parameter. In subsequent calls, this parameter can be one of the following values.
SW_HIDE: Hides the window and activates another window.
Dialogs 22
SW_MAXIMIZE: Maximizes the specified window.
SW_MINIMIZE: Minimizes the specified window and activates the next toplevel
window in the Z order.
SW_RESTORE: Activates and displays the window. If the window is minimized
or maximized, the system restores it to its original size and position. An
application should specify this flag when restoring a minimized window.
SW_SHOW:Activates the window and displays it in its current size and position.
SW_SHOWDEFAULT:Sets the show state based on the SW_ value specified in the STARTUPINFO

structure passed to the CreateProcess function by the program that started the
application.
SW_SHOWMAXIMIZED:Activates the window and displays it as a maximized window.
SW_SHOWMINIMIZED:Activates the window and displays it as a minimized window.
SW_SHOWMINNOACTIVE:Displays the window as a minimized window. This value is similar to
SW_SHOWMINIMIZED, except the window is not activated.
SW_SHOWNA:Displays the window in its current size and position. This value is similar to
SW_SHOW, except the window is not activated.
SW_SHOWNOACTIVATE:Displays a window in its most recent size and position. This value is similar to
SW_SHOWNORMAL, except the window is not actived.
SW_SHOWNORMAL:Activates and displays a window. If the window is minimized or maximized, the
system restores it to its original size and position. An application should specify
this flag when displaying the window for the first time.
Return Value
If the window was previously visible, the return value is nonzero.
If the window was previously hidden, the return value is zero.
To perform certain special effects when showing or hiding a window, use
AnimateWindow.
The first time an application calls ShowWindow, it should use the WinMain function's
nCmdShow parameter as its nCmdShow parameter. Subsequent calls to ShowWindow

must use one of the values in the given list, instead of the one specified by the WinMain

function's nCmdShow parameter.
Dialogs 23
As noted in the discussion of the nCmdShow parameter, the nCmdShow value is ignored
in the first call to ShowWindow if the program that launched the application specifies
startup information in the structure. In this case, ShowWindow uses the information
specified in the STARTUPINFO structure to show the window. On subsequent calls, the
application must call ShowWindow with nCmdShow set to SW_SHOWDEFAULT to
use the startup information provided by the program that launched the application. This
behavior is designed for the following situations:
Applications create their main window by calling CreateWindow with the
WS_VISIBLE flag set.
Applications create their main window by calling CreateWindow with the
WS_VISIBLE flag cleared, and later call ShowWindow with the SW_SHOW
flag set to make it visible.

20.10.2 Processing Dialog Messages

The IsDialogMessage function determines whether a message is intended for the
specified dialog box and, if it is, processes the message.
BOOL IsDialogMessage(
HWND hDlg, /*handle to the dialog*/
LPMSG lpMsg /*message structure */
);
hDlg: Handle to the dialog box.
lpMsg: Pointer to an MSG structure that contains the message to be checked.
Return Value:
If the message has been processed, the return value is nonzero.
If the message has not been processed, the return value is zero.
Although the IsDialogMessage function is intended for modeless dialog boxes, you can
use it with any window that contains controls, enabling the windows to provide the same
keyboard selection as is used in a dialog box.
When IsDialogMessage processes a message, it checks for keyboard messages and
converts them into selections for the corresponding dialog box. For example, the TAB
key, when pressed, selects the next control or group of controls, and the DOWN
ARROW key, when pressed, selects the next control in a group.
Because the IsDialogMessage function performs all necessary translating and
dispatching of messages, a message processed by IsDialogMessage must not be passed
to the TranslateMessage or DispatchMessage function.
Dialogs 24
IsDialogMessage sends WM_GETDLGCODE messages to the dialog box procedure to
determine which keys should be processed.
IsDialogMessage can send DM_GETDEFID and DM_SETDEFID messages to the
window. These messages are defined in the Winuser.h header file as WM_USER and
WM_USER + 1, so conflicts are possible with application-defined messages having the
same values.

20.10.3 Message Loop to dispatch messages to a modeless dialog

While(GetMessage(&msg, NULL, 0, 0) > 0) /*get message from the queue and
check its validity, it should be greater than zero*/
{
/*check if this is the dialog message otherwise send it to the window procedure*/
if(!IsDialogMessage(hDlg, &msg))
{
/*translate message before dispatching it*/
TranslateMessage(&msg);
/*now dispatch to the window procedure*/
DispatchMessage(&msg);
}
}
Modeless dialogs can be destroyed by calling DestroyWindow function.

20.11 Windows Common Dialogs

Windows common dialogs are of the following types.

20.11.1 Open File Dialog

Dialogs 25

20.11.2 Choose Font Dialog
20.11.3 Choose Color Dialog

Dialogs 26

20.11.4 Print Dialog
Summary

A dialog box template is binary data that describes the dialog box, defining its
height, width, style, and the controls it contains. Dialog box template becomes later part
of the executable file. Dialogs are of two types: Modal dialogs and Modeless dialogs. For
dispatching message for Modeless dialogs, we can use IsDialogMessage Function in our
main Message Loop. In windows lot of common dialogs are available. Print dialog is
used to print the document, this dialog show the setting for printer and its path name.
Choose color dialog help the user to choose the color of its own choice. File Open dialog
are useful to open and save the files on disk.
Dialogs 27

Exercises

1. Create a notepad like window and facilitate the user to save and open the text in a
file. For saving the file use open file and save file dialog.

<Previous Lesson

Visual Programming

Next Lesson>

Home

Lesson Plan

Topics

Go to Top

Next Lesson
Previous Lesson
Lesson Plan
Topics
Home
Go to Top