<Previous Lesson

Visual Programming

Next Lesson>

Lesson#21

Using Dialogs and Windows Controls


Chapter 21
21.1 WINDOWS COMMON DIALOGS 2
21.2 DIALOG UNITS 2
21.3 TAB STOPS, TAB ORDER, GROUPS 3
21.4 EDIT CONTROL 3
21.4.1 EDIT CONTROL FEATURES 3
21.4.2 EDIT CONTROL NOTIFICATION MESSAGES 3
21.4.3 EDIT CONTROL DEFAULT MESSAGE PROCESSING 4
21.5 BUTTON 10
21.5.1 BUTTON TYPES AND STYLES 10
CHECK BOXES 10
GROUP BOXES 11
OWNER DRAWN BUTTONS 11
PUSH BUTTONS 11
RADIO BUTTONS 12
21.5.2 NOTIFICATION MESSAGES FROM BUTTON 12
21.5.3 BUTTON DEFAULT MESSAGE PROCESSING 13
21.6 LIST BOX 15
21.6.1 LIST BOX TYPES AND STYLES 16
21.6.2 NOTIFICATION MESSAGES FROM LIST BOXES 18
21.6.3 MESSAGES TO LIST BOXES 18
21.7 EXAMPLE APPLICATION 21
21.7.1 MODELESS DIALOGS 21
21.7.2 CHOOSE COLOR DIALOGS 21
21.7.3 ABOUT DIALOGS 22
21.7.4 CREATING WINDOWS USED IN APPLICATION 22
21.7.5 CREATING DIALOGS 22
21.7.6 MESSAGE LOOP 23
21.7.7 MENU COMMAND 23
21.7.8 COMMAND DIALOG PROCEDURE 23
21.7.9 MESSAGES USED IN OUR APPLICATION 25
21.7.10 THE WM_CTRLCOLORSTATIC MESSAGE 25
SUMMARY 26
EXERCISES 26
Using Dialogs and Windows Controls 2

21.1 Windows Common Dialogs

In our previous lecture, we have viewed common dialogs and in this lecture we will learn
to use them. Following are the Windows common dialog names and the functions that
create these common dialogs.
Choose color:
o For creating the color dialog we use function
ChooseColor(&CHOOSCOLOR). This function inputs CHOOSCOLOR
structure and create the color dialog.
Find:
o FindText(&FINDREPLACE) function create the find text dialog. This
dialog helps to find and replace text in text document. This function inputs
FINDREPLACE structure.
Choose font:
o ChooseFont(&CHOOSEFONT) function create a Choose Font dialog.
This dialog helps choose the font from installed system fonts. This
function inputs CHOOSEFONT structure.
Open File:
o GetOpenFilename(&OPENFILENAM) function creates a dialog that lets
the user specify the drive, directory, and the name of a file or set of files to
open.
Print
o PrintDlg() function open dialog which help to print the document.
Save As:
o GetSaveFilename(&OPENFILENAM) function open a file dialog which
help to save a file on the drive

21.2 Dialog Units

Dialog Unit (DLU): A unit of horizontal or vertical distance within a dialog box. A
horizontal DLU is the average width of the current dialog box font divided by 4. A
vertical DLU is the average height of the current dialog-box font divided by 8.
Dialogs Units have also explained in our previous lectures.
Using Dialogs and Windows Controls 3

21.3 Groups and Focus

WS_GROUP style specifies the first control of a group of controls in which the
user can move from one control to the next with the arrow keys. All controls
defined with the WS_GROUP style FALSE after the first control belongs to the
same group. The next control with the WS_GROUP style starts the next group
(that is, one group ends where the next begins)
Focus: for setting focus on any control in dialog the SetFocus and GetFocus
functions are used.

21.4 Edit Control

Dialog boxes and controls support communication between applications and their users.
An edit control is a rectangular control window typically used in a dialog box to permit
the user to enter and edit text by typing on the keyboard.

21.4.1 Edit Control Features

An edit control is selected and receives the input focus when a user clicks the mouse
inside it or presses the TAB key. After it is selected, the edit control displays its text (if
any) and a flashing caret that indicates the insertion point. The user can then enter text,
move the insertion point, or select text to be edited by using the keyboard or the mouse.
An edit control can send notification messages to its parent window in the form of
WM_COMMAND messages. A parent window can send messages to an edit control in a
dialog box by calling the SendDlgItemMessage function.
The system provides both single-line edit controls (sometimes called SLEs) and multiline
edit controls (sometimes called MLEs). Edit controls belong to the EDIT window class.
A combo box is a control that combines much of the functionality of an edit control and a
list box. In a combo box, the edit control displays the current selection and the list box
presents options a user can select. Many developers use the dialog boxes provided in the
common dialog box (Comdlg32.dll) to perform tasks that otherwise might require
customized edit controls.

21.4.2 Edit Control Notification Messages

The user makes editing requests by using the keyboard and mouse. The system sends
each request to the edit control's parent window in the form of a WM_COMMAND message. The message includes the edit control identifier in the low-order word of the
wParam parameter, the handle of the edit control in the lParam parameter, and an edit
Using Dialogs and Windows Controls 4
control notification message corresponding to the user's action in the high-order word of
the wParam parameter.
An application should examine each notification message and respond appropriately. The
following table lists each edit control notification message and the action that generates
it.
Notification
message User actionEN_CHANGE The user has modified text in an edit control. The system updates the
display before sending this message (unlike EN_UPDATE).
EN_ERRSPACE
The edit control cannot allocate enough memory to meet a specific
request.
EN_HSCROLL The user has clicked the edit control's horizontal scroll bar. The
system sends this message before updating the screen.
EN_KILLFOCUS The user has selected another control.
EN_MAXTEXT
While inserting text, the user has exceeded the specified number of
characters for the edit control. Insertion has been truncated. This
message is also sent either when an edit control does not have the
ES_AUTOHSCROLL style and the number of characters to be
inserted exceeds the width of the edit control or when an edit control
does not have the ES_AUTOVSCROLL style and the total number of
lines to be inserted exceeds the height of the edit control.
EN_SETFOCUS The user has selected this edit control.

EN_UPDATE

The user has altered the text in the edit control and the system is about
to display the new text. The system sends this message after
formatting the text, but before displaying it, so that the application
can resize the edit control window.
EN_VSCROLL
The user has clicked the edit control's vertical scroll bar or has
scrolled the mouse wheel over the edit control. The system sends this
message before updating the screen.
In addition, the system sends a WM_CTLCOLOREDIT message to an edit control's
parent window before the edit control is drawn. This message contains a handle of the
edit control's display context (DC) and a handle of the child window. The parent window
can use these handles to change the edit control's text and background colors.

21.4.3 Edit Control Default Message Processing

The window procedure for the predefined edit control window class carries out default
processing for all messages that the edit control procedure does not process. When the
edit control procedure returns FALSE for any message, the predefined window procedure
checks the messages and carries out the following default actions.
Using Dialogs and Windows Controls 5
Message Default action
EM_CANUNDO Returns TRUE if the edit control operation can be
undone.
EM_CHARFROMPOS Returns the character index and line index of the
character nearest the specified point.
EM_EMPTYUNDOBUFFER
Empties the undo buffer and sets the undo flag retrieved
by the EM_CANUNDO message to FALSE. The
system automatically clears the undo flag whenever the
edit control receives a WM_SETTEXT or
EM_SETHANDLE message.
EM_FMTLINES
Adds or removes soft line-break characters (two carriage
returns and a line feed) to the ends of wrapped lines in a
multiline edit control. It is not processed by single-line
edit controls.
EM_GETFIRSTVISIBLELINE
Returns the zero-based index of the first visible
character in a single-line edit control or the zero-based
index of the uppermost visible line in a multiline edit
control.

EM_GETHANDLE

Returns a handle identifying the buffer containing the
multiline edit control's text. It is not processed by singleline
edit controls.
EM_GETLIMITTEXT Returns the current text limit, in characters.
EM_GETLINE
Copies characters in a single-line edit control to a buffer
and returns the number of characters copied. In a
multiline edit control, retrieves a line of text from the
control and returns the number of characters copied.
EM_GETLINECOUNT Returns the number of lines in the edit control.
EM_GETMARGINS Returns the widths of the left and right margins.
EM_GETMODIFY Returns a flag indicating whether the content of an edit
control has been modified.
EM_GETPASSWORDCHAR Returns the character that edit controls use in
conjunction with the ES_PASSWORD style.
EM_GETRECT Returns the coordinates of the formatting rectangle in an
edit control.
EM_GETSEL Returns the starting and ending character positions of
the current selection in the edit control.
EM_GETTHUMB Returns the position of the scroll box in the vertical
scroll bar in a multiline edit control.
EM_GETWORDBREAKPROC Returns the address of the current Wordwrap function in
an edit control.
EM_LINEFROMCHAR Returns the zero-based number of the line in a multiline
edit control that contains a specified character index.
Using Dialogs and Windows Controls 6
This message is the reverse of the EM_LINEINDEX
message. It is not processed by single-line edit controls.
EM_LINEINDEX
Returns the character of a line in a multiline edit control.
This message is the reverse of the
EM_LINEFROMCHAR message. It is not processed
by single-line edit controls.
EM_LINELENGTH
Returns the length, in characters, of a single-line edit
control. In a multiline edit control, returns the length, in
characters, of a specified line.
EM_LINESCROLL
Scrolls the text vertically in a single-line edit control or
horizontally in a multiline edit control (when the control
has the ES_LEFT style). The lParam parameter
specifies the number of lines to scroll vertically, starting
from the current line. The wParam parameter specifies
the number of characters to scroll horizontally, starting
from the current character.
EM_POSFROMCHAR Returns the client coordinates of the specified character.
EM_REPLACESEL
Replaces the current selection with the text in an
application-supplied buffer, sends the parent window
EN_UPDATE and EN_CHANGE messages, and
updates the undo buffer.
EM_SCROLL
Scrolls the text vertically in a multiline edit control. This
message is equivalent to sending a WM_VSCROLL
message to the edit control. It is not processed by singleline
edit controls.
EM_SCROLLCARET Scrolls the caret into view in an edit control.
EM_SETFONT Unsupported.
EM_SETHANDLE
Sets a handle to the memory used as a text buffer,
empties the undo buffer, resets the scroll positions to
zero, and redraws the window.
EM_SETLIMITTEXTSets the maximum number of characters the user may
enter in the edit control.
Windows NT/2000/XP: For single-line edit controls,
this value is either 0x7FFFFFFE or the value of the
wParam parameter, whichever is smaller. For multiline
edit controls, this value is either –1 or the value of the
wParam parameter, whichever is smaller.
Windows 95/98/Me: For single-line edit controls, this
value is either 0x7FFE or the value of the wParam
parameter, whichever is smaller. For multiline edit
controls, this value is either 0xFFFF or the value of the
wParam parameter, whichever is smaller.
Using Dialogs and Windows Controls 7
EM_SETMARGINS Sets the widths of the left and right margins, and
redraws the edit control to reflect the new margins.
EM_SETMODIFY Sets or clears the modification flag to indicate whether
the edit control has been modified.
EM_SETPASSWORDCHAR Defines the character that edit controls use in
conjunction with the ES_PASSWORD style.
EM_SETREADONLY Sets or removes the read-only style (ES_READONLY)
in an edit control.
EM_SETRECTSets the formatting rectangle for the multiline edit
control and redraws the window. It is not processed by
single-line edit controls.
EM_SETRECTNPSets the formatting rectangle for the multiline edit
control but does not redraw the window. It is not
processed by single-line edit controls.
EM_SETSEL Selects a range of characters in the edit control by
setting the starting and ending positions to be selected.
EM_SETTABSTOPS Sets tab-stop positions in the multiline edit control. It is
not processed by single-line edit controls.
EM_SETWORDBREAKPROC Replaces the default Wordwrap function with an
application-defined Wordwrap function.
EM_UNDO
Removes any text that was just inserted or inserts any
deleted characters and sets the selection to the inserted
text. If necessary, sends the EN_UPDATE and
EN_CHANGE notification messages to the parent
window.
WM_CHAR
Writes a character to the single-line edit control and
sends the EN_UPDATE and EN_CHANGEnotification messages to the parent window. Writes a
character to the multiline edit control. Handles the
accelerator keys for standard functions, such as
CTRL+C for copying and CTRL+V for pasting. In
multiline edit controls, also processes TAB, and
CTRL+TAB keystrokes to move among the controls in
a dialog box and to insert tabs into multiline edit
controls. Uses the MessageBeep function for illegal
characters.
WM_CLEAR
Clears the current selection, if any, in an edit control. If
there is no current selection, deletes the character to the
right of the caret. If the user presses the SHIFT key, this
cuts the selection to the clipboard, or deletes the
character to the left of the caret when there is no
selection. If the user presses the CTRL key, this deletes
the selection, or deletes to the end of the line when there
is no selection.
Using Dialogs and Windows Controls 8
WM_COPY
Copies text to the clipboard unless the style is
ES_PASSWORD, in which case the message returns
zero.
WM_CREATE Creates the edit control and notifies the parent window
with TRUE for success or –1 for failure.
WM_CUT Cuts the selection to the clipboard, or deletes the
character to the left of the cursor if there is no selection.
WM_ENABLE
Causes the rectangle to be redrawn in gray for singleline
edit controls. Returns the enabled state for singleline
and multiline edit controls.
WM_ERASEBKGND Fills the multiline edit control window with the current
color of the edit control.
WM_GETDLGCODE
Returns the following values: DLGC_WANTCHARS,
DLGC_HASSETSEL, and DLGC_WANTARROWS.
In multiline edit controls, it also returns
DLGC_WANTALLKEYS. If the user presses
ALT+BACKSPACE, it also returns
DLGC_WANTMESSAGE.
WM_GETFONT Returns the handle of the font being used by the control,
or NULL if the control uses the system font.
WM_GETTEXT Copies the specified number of characters to a buffer
and returns the number of characters copied.
WM_GETTEXTLENGTH
Returns the length, in characters, of the text in an edit
control. The length does not include the nullterminating
character.
WM_HSCROLL Scrolls the text in a multiline edit control horizontally
and handles scroll box movement.
WM_KEYDOWN Performs standard processing of the virtual-key codes.
WM_KILLFOCUS
Removes the keyboard focus of an edit control window,
destroys the caret, hides the current selection, and
notifies the parent window that the edit control has lost
the focus.
WM_LBUTTONDBLCLK
Clears the current selection and selects the word under
the cursor. If the SHIFT key is depressed, extends the
selection to the word under the cursor.
WM_LBUTTONDOWN
Changes the current insertion point. If the SHIFT key is
depressed, extends the selection to the position of the
cursor. In multiline edit controls, also sets the timer to
automatically scroll when the user holds down the
mouse button outside the multiline edit control window.
WM_LBUTTONUP
Releases the mouse capture and sets the text insertion
point in the single-line edit control. In a multiline edit
control, also kills the timer set in the
Using Dialogs and Windows Controls 9
WM_LBUTTONDOWN message.
WM_MOUSEMOVE
Changes the current selection in the single-line edit
control, if the mouse button is down. In a multiline edit
controls, also sets the timer to automatically scroll if the
user holds down the mouse button outside the multiline
edit control window.
WM_NCCREATE
Pointer to the CREATESTRUCT structure for the
window. This message is sent to the WM_CREATEmessage when a window is first created.
WM_NCDESTROY
Frees all memory associated with the edit control
window, including the text buffer, undo buffer, tab-stop
buffer, and highlight brush.
WM_PAINT
Erases the background, fills the window with the current
color of the edit control window, draws the border (if
any), sets the font and draws any text, and shows the
text-insertion caret.
WM_PASTE Pastes text from the clipboard into the edit control
window at the caret position.
WM_SETFOCUS
Sets the keyboard focus of an edit control window
(shows the current selection, if it was hidden, and
creates the caret).
WM_SETFONT Sets the font and optionally redraws the edit control.
WM_SETTEXT
Copies text to the single-line edit control, notifies the
parent window when there is insufficient memory,
empties the undo buffer, and sends the EN_UPDATE and EN_CHANGE notification messages to the parent
window. In multiline edit controls, also rewraps the
lines (if necessary) and sets the scroll positions.
WM_SIZE
Changes the size of the edit control window and ensures
that the minimum size accommodates the height and
width of a character.
WM_SYSCHAR Returns TRUE if the user presses ALT+BACKSPACE;
otherwise takes no action.
WM_SYSKEYDOWN Undoes the last action if the user presses
ALT+BACKSPACE; otherwise takes no action.
WM_TIMER
Scrolls the text in the edit control window if the user
holds down the mouse button outside the multiline edit
control window.
WM_UNDO
Removes any text that was just inserted or inserts any
deleted characters and sets the selection to the inserted
text. If necessary, sends the EN_UPDATE and
EN_CHANGE notification messages to the parent
window.
Using Dialogs and Windows Controls 10
WM_VSCROLL
Scrolls a multiline edit control vertically and handles
scroll box movement. It is not processed by single-line
edit controls.
The predefined edit control window procedure passes all other messages to the
DefWindowProc function for default processing.
21.5 Button
A button is a control the user can click to provide input to an application.

21.5.1 Button Types and Styles

There are five styles of a button:
Check Boxes
Group Boxes
Owner Drawn Buttons
Push Buttons
Radio Buttons

Check Boxes

A check box consists of a square box and application-defined text (label), an icon, or a
bitmap, that indicates a choice the user can make by selecting the button. Applications
typically display check boxes in a group box to permit the user to choose from a set of
related, but independent options. For example, an application might present a group of
check boxes from which the user can select error conditions that produce warning beeps.
A check box can be one of four styles: standard, automatic, three-state, and automatic
three-state, as defined by the constants BS_CHECKBOX, BS_AUTOCHECKBOX,
BS_3STATE, and BS_AUTO3STATE, respectively. Each style can assume two check
states: checked (a check mark inside the box) or cleared (no check mark). In addition, a
three-state check box can assume an indeterminate state (a grayed box inside the check
box). Repeatedly clicking a standard or automatic check box toggles it from checked to
cleared and back again. Repeatedly clicking a three-state check box toggles it from
checked to cleared to indeterminate and back again.
When the user clicks a check box (of any style), the check box receives the keyboard
focus. The system sends the check box's parent window a WM_COMMAND message
containing the BN_CLICKED notification code. The parent window doesn't
acknowledge this message if it comes from an automatic check box or automatic threestate
check box, because the system automatically sets the check state for those styles.
But the parent window must acknowledge the message if it comes from a check box or
three-state check box because the parent window is responsible for setting the check state
Using Dialogs and Windows Controls 11
for those styles. Regardless of the check box style, the system automatically repaints the
check box once its state is changed.

Group Boxes

A group box is a rectangle that surrounds a set of controls, such as check boxes or radio
buttons, with application-defined text (label) in its upper left corner. The sole purpose of
a group box is to organize controls related by a common purpose (usually indicated by
the label). The group box has only one style, defined by the constant BS_GROUPBOX.
Because a group box cannot be selected, it has no check state, focus state, or push state.
An application cannot send messages to a group box.

Owner Drawn Buttons

Unlike radio buttons, an owner-drawn button is painted by the application, not by the
system, and has no predefined appearance or usage. Its purpose is to provide a button
whose appearance and behavior are defined by the application alone. There is only one
owner-drawn button style: BS_OWNERDRAW.
When the user selects an owner-drawn button, the system sends the button's parent
window a WM_COMMAND message containing the BN_CLICKED notification code,
just as it does for a button that is not owner-drawn. The application must respond
appropriately.

Push Buttons

A push button is a rectangle containing application-defined text (label), an icon, or a
bitmap that indicates what the button does when the user selects it. A push button can be
one of two styles: standard or default, as defined by the constants BS_PUSHBUTTON
and BS_DEFPUSHBUTTON. A standard push button is typically used to start an
operation. It receives the keyboard focus when the user clicks it. A default push button,
on the other hand, is typically used to indicate the most common or default choice. It is a
button that the user can select by simply pressing ENTER when a dialog box has the
input focus.
When the user clicks a push button (of either style), it receives the keyboard focus. The
system sends the button's parent window a WM_COMMAND message that contains the
BN_CLICKED notification code. In response, the dialog box typically closes and carries
out the operation indicated by the button.
The default push button cannot be a check box, a radio button, or an ownerdraw button at
the same time.
Using Dialogs and Windows Controls 12

Radio Buttons

A radio button consists of a round button and application-defined text (a label), an icon,
or a bitmap that indicates a choice the user can make by selecting the button. An
application typically uses radio buttons in a group box to permit the user to choose from a
set of related, but mutually exclusive options. For example, the application might present
a group of radio buttons from which the user can select a format preference for text
selected in the client area. The user could select a left-aligned, right-aligned, or centered
format by selecting the corresponding radio button. Typically, the user can select only
one option at a time from a set of radio buttons.
A radio button can be one of two styles: standard or automatic, as defined by the
constants BS_RADIOBUTTON and BS_AUTORADIOBUTTON. Each style can
assume two check states: checked (a dot in the button) or cleared (no dot in the button).
Repeatedly selecting a radio button (standard or automatic) toggles it from checked to
cleared and back again.
When the user selects either state, the radio button receives the keyboard focus. The
system sends the button's parent window a WM_COMMAND message containing the
BN_CLICKED notification code. The parent window doesn't acknowledge this message
if it comes from an automatic radio button because the system automatically sets the
check state for that style. But the parent window should acknowledge the message if it
comes from a radio button because the parent window is responsible for setting the check
state for that style. Regardless of the radio button style, the system automatically repaints
the button as its state changes.
When the user selects an automatic radio button, the system automatically sets the check
state of all other radio buttons within the same group to clear. The same behavior is
available for standard radio buttons by using the WS_GROUP style, as discussed in
Dialog Boxes.

21.5.2 Notification Messages from Button

When the user clicks a button, its state changes, and the button sends notification
messages to its parent window. For example, a push button control sends the
BN_CLICKED notification message whenever the user chooses the button. In all cases
(except for BCN_HOTITEMCHANGE), the low-order word of the wParam parameter
contains the control identifier, the high-order word of wParam contains the notification
code, and the lParam parameter contains the control window handle.
Both the message and the parent window's response depend on the type, style, and
current state of the button. Following are the button notification messages an application
should monitor and process.

Message Description

BCN_HOTITEMCHANGE Microsoft® Windows® XP: The mouse entered or
Using Dialogs and Windows Controls 13
left the client area of a button.
BN_CLICKED The user clicked a button.
BN_DBLCLK or
BN_DOUBLECLICKED The user double-clicked a button.
BN_DISABLE A button is disabled.
BN_PUSHED or BN_HILITE The user pushed a button.
BN_KILLFOCUS The button lost the keyboard focus.
BN_PAINT The button should be painted.
BN_SETFOCUS The button gained the keyboard focus.
BN_UNPUSHED or
BN_UNHILITE The button is no longer pushed.
A button sends the BN_DISABLE, BN_PUSHED, BN_KILLFOCUS, BN_PAINT,
BN_SETFOCUS, and BN_UNPUSHED notification messages only if it has the
BS_NOTIFY style. BN_DBLCLK notification messages are sent automatically for
BS_USERBUTTON, BS_RADIOBUTTON, and BS_OWNERDRAW buttons. Other
button types send BN_DBLCLK only if they have the BS_NOTIFY style. All buttons
send the BN_CLICKED notification message regardless of their button styles.
For automatic buttons, the system changes the push state and paints the button. In this
case, the application typically processes only the BN_CLICKED and BN_DBLCLKnotification messages. For buttons that are not automatic, the application typically
responds to the notification message by sending a message to change the state of the
button.
When the user selects an owner-drawn button, the button sends its parent window a
WM_DRAWITEM message containing the identifier of the control to be drawn and
information about its dimensions and state.

21.5.3 Button Default Message Processing

The window procedure for the predefined button control window class carries out default
processing for all messages that the button control procedure does not process. When the
button control procedure returns FALSE for any message, the predefined window
procedure checks the messages and performs the default actions listed in the following
table.

Message Default action

BM_CLICK
Sends the button a WM_LBUTTONDOWN and a
WM_LBUTTONUP message, and sends the parent window a
BN_CLICKED notification message.
BM_GETCHECK Returns the check state of the button.
Using Dialogs and Windows Controls 14
BM_GETIMAGE Returns a handle to the bitmap or icon associated with the button
or NULL if the button has no bitmap or icon.
BM_GETSTATE Returns the current check state, push state, and focus state of the
button.
BM_SETCHECK
Sets the check state for all styles of radio buttons and check boxes.
If the wParam parameter is greater than zero for radio buttons, the
button is given the WS_TABSTOP style.
BM_SETIMAGE Associates the specified bitmap or icon handle with the button and
returns a handle to the previous bitmap or icon.
BM_SETSTATE
Sets the push state of the button. For owner-drawn buttons, a
WM_DRAWITEM message is sent to the parent window if the
state of the button has changed.
BM_SETSTYLE Sets the button style. If the low-order word of the lParam
parameter is TRUE, the button is redrawn.
WM_CHAR
Checks a check box or automatic check box when the user presses
the plus (+) or equal (=) keys. Clears a check box or automatic
check box when the user presses the minus (–) key.
WM_ENABLE Paints the button.
WM_ERASEBKGND
Erases the background for owner-drawn buttons. The backgrounds
of other buttons are erased as part of the WM_PAINT and
WM_ENABLE processing.
WM_GETDLGCODE Returns values indicating the type of input processed by the
default button procedure, as shown in the following table.

Button style Returns

BS_AUTOCHECKBOX DLGC_WANTCHARS | DLGC_BUTTON
BS_AUTORADIOBUTTON DLGC_RADIOBUTTON
BS_CHECKBOX DLGC_WANTCHARS | DLGC_BUTTON
BS_DEFPUSHBUTTON DLGC_DEFPUSHBUTTON
BS_GROUPBOX DLGC_STATIC
BS_PUSHBUTTON DLGC_UNDEFPUSHBUTTON
BS_RADIOBUTTON DLGC_RADIOBUTTON

Message Default action

WM_GETFONT Returns a handle to the current font.
WM_KEYDOWN Pushes the button if the user presses the SPACEBAR.
WM_KEYUP Releases the mouse capture for all cases except the TAB key.
WM_KILLFOCUS
Removes the focus rectangle from a button. For push buttons
and default push buttons, the focus rectangle is invalidated. If
the button has the mouse capture, the capture is released, the
button is not clicked, and any push state is removed.
Using Dialogs and Windows Controls 15
WM_LBUTTONDBLCLK
Sends a BN_DBLCLK notification message to the parent
window for radio buttons and owner-drawn buttons. For
other buttons, a double-click is processed as a
WM_LBUTTONDOWN message.
WM_LBUTTONDOWN Highlights the button if the position of the mouse cursor is
within the button's client rectangle.
WM_LBUTTONUP Releases the mouse capture if the button had the mouse
capture.
WM_MOUSEMOVE
Performs the same action as WM_LBUTTONDOWN, if the
button has the mouse capture. Otherwise, no action is
performed.
WM_NCCREATE Turns any BS_OWNERDRAW button into a
BS_PUSHBUTTON button.
WM_NCHITTEST Returns HTTRANSPARENT, if the button control is a group
box.
WM_PAINT Draws the button according to its style and current state.
WM_SETFOCUS
Draws a focus rectangle on the button getting the focus. For
radio buttons and automatic radio buttons, the parent window
is sent a BN_CLICKED notification message.
WM_SETFONT Sets a new font and optionally updates the window.
WM_SETTEXT
Sets the text of the button. In the case of a group box, the
message paints over the preexisting text before repainting the
group box with the new text.
WM_SYSKEYUP Releases the mouse capture for all cases except the TAB key.
The predefined window procedure passes all other messages to the DefWindowProc
function for default processing.

21.6 List Box

List box items can be represented by text strings, bitmaps, or both. If the list box is not
large enough to display all the list box items at once, the list box provides a scroll bar.
The user scrolls through the list box items, and applies or removes selection status as
necessary. Selection style of a list box item or its visual appearance can be changed in
Operating system metrics. When the user selects or deselects an item, the system sends a
notification message to the parent window of the list box.
A dialog box procedure is responsible for initializing and monitoring its child windows,
including any list boxes. The dialog box procedure communicates with the list box by
sending messages to it and by processing the notification messages sent by the list box.
Using Dialogs and Windows Controls 16

21.6.1 List Box types and styles

There are two types of list boxes: single-selection (the default) and multiple-selection. In
a single-selection list box, the user can select only one item at a time. In a multipleselection
list box
, the user can select more than one item at a time. To create a multipleselection
list box, specify the LBS_MULTIPLESEL or the LBS_EXTENDEDSEL style.
There are many list box styles and window styles that control the appearance and
operation of a list box. These styles indicate whether list box items are sorted, arranged in
multiple columns, drawn by the application, and so on. The dimensions and styles of a
list box are typically defined in a dialog box template included in an application's
resources.
To create a list box by using the CreateWindow or CreateWindowEx function, use the
LISTBOX class, appropriate window style constants, and the following style constants to
define the list box. After the control has been created, these styles cannot be modified,
except as noted.

LBS_DISABLENOSCROLL:

Shows a disabled vertical scroll bar for the list box when the box does not contain
enough items to scroll. If you do not specify this style, the scroll bar is hidden
when the list box does not contain enough items.

LBS_EXTENDEDSEL:

This style allows multiple items to be selected by using the SHIFT key and the
mouse or special key combinations.

LBS_HASSTRINGS:

This style specifies that a list box contains items consisting of strings. The list box
maintains the memory and addresses for the strings so that the application can use
the LB_GETTEXT message to retrieve the text for a particular item. By default,
all list boxes except owner-drawn list boxes have this style. You can create an
owner-drawn list box either with or without this style.

LBS_MULTICOLUMN:

This style specifies a multi column list box that is scrolled horizontally. The
LB_SETCOLUMNWIDTH message sets the width of the columns.

LBS_MULTIPLESEL:

Turns string selection on or off each time the user clicks or double-clicks a string
in the list box. The user can select any number of strings.

LBS_NODATA:

This style specifies a no-data list box. Specify this style when the count of items
in the list box will exceed one thousand. A no-data list box must also have the
LBS_OWNERDRAWFIXED style, but must not have the LBS_SORT or
LBS_HASSTRINGS style.
A no-data list box resembles an owner-drawn list box except that it contains no
string or bitmap data for an item. Commands to add, insert, or delete an item
always ignore any specified item data; requests to find a string within the list box
Using Dialogs and Windows Controls 17
always fail. The system sends the WM_DRAWITEM message to the owner
window when an item must be drawn. The itemID member of the
DRAWITEMSTRUCT structure passed with the WM_DRAWITEM message
specifies the line number of the item to be drawn. A no-data list box does not send
a WM_DELETEITEM message.

LBS_NOINTEGRALHEIGHT:

This style specifies that the size of the list box is exactly the size specified by the
application when it created the list box. Normally, the system sizes a list box so
that the list box does not display partial items.
LBS_NOREDRAW:This style specifies that the list box's appearance is not updated when changes are
made.
To change the redraw state of the control, use the WM_SETREDRAW message.
LBS_NOSEL:This style specifies that the list box contains items that can be viewed but not
selected.
LBS_NOTIFY:This style notifies the parent window with an input message whenever the user
clicks or double-clicks a string in the list box.
LBS_OWNERDRAWFIXED:This style specifies that the owner of the list box is responsible for drawing its
contents and that the items in the list box are the same height. The owner window
receives a WM_MEASUREITEM message when the list box is created and a
WM_DRAWITEM message when a visual aspect of the list box has changed.
LBS_OWNERDRAWVARIABLE:Specifies that the owner of the list box is responsible for drawing its contents and
that the items in the list box are variable in height. The owner window receives a
WM_MEASUREITEM message for each item in the combo box when the
combo box is created and a WM_DRAWITEM message when a visual aspect of
the combo box has changed.

LBS_SORT

Sorts strings in the list box alphabetically.

LBS_STANDARD

Sorts strings in the list box alphabetically. The parent window receives an input
message whenever the user clicks or double-clicks a string. The list box has
borders on all sides.

LBS_USETABSTOPS

Enables a list box to recognize and expand tab characters when drawing its
strings. You can use the LB_SETTABSTOPS message to specify tab stop
positions. The default tab positions are 32 dialog template units apart. Dialog
template units are the device-independent units used in dialog box templates. To
convert measurements from dialog template units to screen units (pixels), use the
MapDialogRect function.
Using Dialogs and Windows Controls 18

LBS_WANTKEYBOARDINPUT

This style specifies that the owner of the list box receives WM_VKEYTOITEM
messages whenever the user presses a key and the list box has the input focus.
This enables an application to perform special processing on the keyboard input.
Note: the description of the controls including list box has been taken from Microsoft
Help Desk.

21.6.2 Notification Messages from List Boxes

When an event occurs in a list box, the list box sends a notification message to the dialog
box procedure of the owner window. List box notification messages are sent when a user
selects, double-clicks, or cancels a list box item; when the list box receives or loses the
keyboard focus; and when the system cannot allocate enough memory for a list box
request. A notification message is sent as a WM_COMMAND message in which the loworder
word of the wParam parameter contains the list box identifier, the high-order word
of wParam contains the notification message, and the lParam parameter contains the
control window handle.
A dialog box procedure is not required to process these messages; the default window
procedure processes them.
An application should monitor and process the following list box notification messages.

Notification message Description

LBN_DBLCLK The user double-clicks an item in the list box.
LBN_ERRSPACE The list box cannot allocate enough memory to fulfill a request.
LBN_KILLFOCUS The list box loses the keyboard focus.
LBN_SELCANCEL The user cancels the selection of an item in the list box.
LBN_SELCHANGE The selection in a list box is about to change.
LBN_SETFOCUS The list box receives the keyboard focus.

21.6.3 Messages to List Boxes

A dialog box procedure can send messages to a list box to add, delete, examine, and
change list box items. For example, a dialog box procedure could send an
LB_ADDSTRING message to a list box to add an item, and an LB_GETSEL message to
determine whether the item is selected. Other messages set and retrieve information about
the size, appearance, and behavior of the list box. For example, the
LB_SETHORIZONTALEXTENT message sets the scrollable width of a list box. A
dialog box procedure can send any message to a list box by using the SendMessage or
SendDlgItemMessage function.
Using Dialogs and Windows Controls 19
A list box item is often referenced by its index, an integer that represents the item's
position in the list box. The index of the first item in a list box is zero; the index of the
second item is one, and so on.
The following table describes how the predefined list box procedure responds to list box
messages.

Message Response

LB_ADDFILE
Inserts a file into a directory list box filled by the
DlgDirList function and retrieves the list box index
of the inserted item.
LB_ADDSTRING Adds a string to a list box and returns its index.
LB_DELETESTRING Removes a string from a list box and returns the
number of strings remaining in the list.
LB_DIR Adds a list of filenames to a list box and returns the
index of the last filename added.
LB_FINDSTRING Returns the index of the first string in the list box that
begins with a specified string..
LB_FINDSTRINGEXACT Returns the index of the string in the list box that is
equal to a specified string.
LB_GETANCHORINDEX Returns the index of the item that the mouse last
selected.
LB_GETCARETINDEX Returns the index of the item that has the focus
rectangle.
LB_GETCOUNT Returns the number of items in the list box.
LB_GETCURSEL Returns the index of the currently selected item.
LB_GETHORIZONTALEXTENT Returns the scrollable width, in pixels, of a list box.
LB_GETITEMDATA Returns the value associated with the specified item.
LB_GETITEMHEIGHT Returns the height, in pixels, of an item in a list box.
LB_GETITEMRECT Retrieves the client coordinates of the specified list
box item.
LB_GETLOCALE
Retrieves the locale of the list box. The high-order
word contains the country/region code and the loworder
word contains the language identifier.
LB_GETSEL Returns the selection state of a list box item.
LB_GETSELCOUNT Returns the number of selected items in a multipleselection
list box.
LB_GETSELITEMS
Creates an array of the indexes of all selected items in
a multiple-selection list box and returns the total
number of selected items.
LB_GETTEXT Retrieves the string associated with a specified item
and the length of the string.
Using Dialogs and Windows Controls 20
LB_GETTEXTLEN Returns the length, in characters, of the string
associated with a specified item.
LB_GETTOPINDEX Returns the index of the first visible item in a list box.
LB_INITSTORAGE Allocates memory for the specified number of items
and their associated strings.
LB_INSERTSTRING Inserts a string at a specified index in a list box.
LB_ITEMFROMPOINT Retrieves the zero-based index of the item nearest the
specified point in a list box.
LB_RESETCONTENT Removes all items from a list box.
LB_SELECTSTRING Selects the first string it finds that matches a specified
prefix.
LB_SELITEMRANGE Selects a specified range of items in a list box.
LB_SELITEMRANGEEX
Selects a specified range of items if the index of the
first item in the range is less than the index of the last
item in the range. Cancels the selection in the range if
the index of the first item is greater than the last.
LB_SETANCHORINDEX Sets the item that the mouse last selected to a
specified item.
LB_SETCARETINDEX Sets the focus rectangle to a specified list box item.
LB_SETCOLUMNWIDTH Sets the width, in pixels, of all columns in a list box.
LB_SETCOUNT Sets the number of items in a list box.
LB_SETCURSEL Selects a specified list box item.
LB_SETHORIZONTALEXTENT Sets the scrollable width, in pixels, of a list box.
LB_SETITEMDATA Associates a value with a list box item.
LB_SETITEMHEIGHT Sets the height, in pixels, of an item or items in a list
box.
LB_SETLOCALE Sets the locale of a list box and returns the previous
locale identifier.
LB_SETSEL Selects an item in a multiple-selection list box.
LB_SETTABSTOPS Sets the tab stops to those specified in a specified
array.
LB_SETTOPINDEX Scrolls the list box so the specified item is at the top
of the visible range.
The predefined list box procedure passes all other messages to DefWindowProc for
default processing.
Using Dialogs and Windows Controls 21

21.7 Example Application

The following components will be used in our application

21.7.1 Modeless Dialogs

Dialog box is designed in resource edit provided by Visual Studio

21.7.2 Choose Color Dialogs

Choose color is built resource in windows.
Using Dialogs and Windows Controls 22

21.7.3 About Dialogs

About dialog is designed in resource editor.

21.7.4 Creating Windows used in Application

hWndMain = CreateWindow(windowClassName,
windowName,
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
CW_USEDEFAULT, 1, CW_USEDEFAULT, 1,
NULL, NULL, hInstance, NULL
);
if(!hWndMain)
{
return 0;
}

21.7.5 Creating Dialogs

hCommandDialog = CreateDialog(hInstance,
MAKEINTRESOURCE(IDD_DIALOG_DRAW),
hWndMain, commandDialogProc
);
Using Dialogs and Windows Controls 23
if(!hCommandDialog)
{
return 0;
}
ShowWindow(hCommandDialog, SW_SHOWNORMAL);
commandDialogShown = TRUE;
CheckMenuItem(GetMenu(hWndMain), ID_VIEW_SHOWCOMMANDDIALOG,
MF_CHECKED | MF_BYCOMMAND);

21.7.6 Message Loop

while(GetMessage(&msg, NULL, 0, 0) > 0)
{
if(!IsDialogMessage(hCommandDialog, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}

21.7.7 Menu Command

Case ID_VIEW_SHOWCOMMANDDIALOG:
if(commandDialogShown) // already visible?
{
ShowWindow(hCommandDialog, SW_HIDE); // hide it
CheckMenuItem(GetMenu(hWnd),
ID_VIEW_SHOWCOMMANDDIALOG, MF_UNCHECKED |
MF_BYCOMMAND); // uncheck
commandDialogShown = FALSE;
}
else
{
}

21.7.8 Command Dialog Procedure

Using Dialogs and Windows Controls 24
Static COLORREF textColour, brushColour;
case WM_INITDIALOG:
CheckDlgButton(hDlg, IDC_RADIO_RECTANGLE, BST_CHECKED); //
BM_SETCHECK message: check rectangle button
EnableWindow(GetDlgItem(hDlg, IDC_EDIT_TEXT), FALSE); // disable edit control
SendDlgItemMessage(hDlg, IDC_EDIT_TEXT, EM_LIMITTEXT, TEXT_LIMIT, 0);
// set text limit
SetWindowText(GetDlgItem(hDlg, IDC_EDIT_TEXT), "This is Virtual University");
brushColour = RGB_BRUSH_COLOR; //RGB(255, 255, 160)
textColour = RGB_TEXT_COLOR; //RGB(0, 50, 220)
return TRUE; // system should set focus
wNotificationCode = HIWORD(wParam);
wID = LOWORD(wParam);
if(wNotificationCode == BN_CLICKED)
{
switch(wID)
{
case IDC_RADIO_RECTANGLE:
EnableWindow(GetDlgItem(hDlg, IDC_EDIT_TEXT), FALSE);
// disable edit control similarly in IDC_RADIO_CIRCLE
case IDC_RADIO_TEXT:
EnableWindow(GetDlgItem(hDlg, IDC_EDIT_TEXT), TRUE);
SendDlgItemMessage(hDlg, IDC_EDIT_TEXT, EM_SETSEL, 0, -1);
SetFocus(GetDlgItem(hDlg, IDC_EDIT_TEXT));
//Now handlingo of WM_CTLCOLORSTATIC
case WM_CTLCOLORSTATIC:
switch(GetDlgCtrlID((HWND)lParam))
{
case IDC_STATIC_TEXT_COLOR:
if(hBrush) // if some brush was created before
DeleteObject(hBrush);
hBrush = CreateSolidBrush(textColour); // create a brush
return (BOOL)hBrush;
break;
Using Dialogs and Windows Controls 25
case IDC_STATIC_BRUSH_COLOR:
if(hBrush) // if some brush was created before
DeleteObject(hBrush);
hBrush = CreateSolidBrush(brushColour); // create a brush
return (BOOL)hBrush;
break;
default:
return FALSE; // perform default message handling

21.7.9 Messages Used in Our Application

BM_SETCHECK:
wParam: check-state either BST_CHECKED or BST_UNCHECKED
EM_LIMITTEXT: wParam: text length
EM_SETSEL:
wParam: starting pos
lParam: ending pos.
0&-1:All selected, start:-1: current selection deselected

21.7.10 The WM_CTRLCOLORSTATIC Message

A static control, or an edit control that is read-only or disabled, sends the
WM_CTLCOLORSTATIC message to its parent window when the control is about to
be drawn. By responding to this message, the parent window can use the specified device
context handle to set the text and background colors of the static control.
A window receives this message through its WindowProc function.
WM_CTLCOLORSTATIC
WPARAM wParam
LPARAM lParam;
wParam:
Handle to the device context for the static control window.
lParam:
Handle to the static control.
Return Value:
Using Dialogs and Windows Controls 26
If an application processes this message, the return value is a handle to a brush
that the system uses to paint the background of the static control.
By default, the DefWindowProc function selects the default system colors for the static
control.
Edit controls that are not read-only or disabled do not send the
WM_CTLCOLORSTATIC message; instead, they send the WM_CTLCOLOREDIT
message.
The system does not automatically destroy the returned brush. It is the application's
responsibility to destroy the brush when it is no longer needed.
The WM_CTLCOLORSTATIC message is never sent between threads; it is sent only
within the same thread.
If a dialog box procedure handles this message, it should cast the desired return value to a
BOOL and return the value directly. If the dialog box procedure returns FALSE, then
default message handling is performed. The DWL_MSGRESULT value set by the
SetWindowLong function is ignored.

Summary

Windows controls are basic controls that are pre-registered in windows. We have
discussed some of them like button, list box and edit box controls. These controls are
helpful to display information in a very organized manner in a dialog box or in a window.
Edit box control is simple to use. It has few message and notifications messages. Sending
message to edit box window we can limit text in edit box, set text and get text etc. Button
is another ubiquitous control in windows. Button is used almost in every user interactive
application. Button is sent messages like edit box and list box, and also send notification
messages to its parent window. List View is another useful control in windows systems.
List view control list the items in its window. These items can be selected and clicked on
each click list box send notification message to its parent window.

Exercises

1. Create a Medical Store data base form. This form should be a Modal/Modeless
dialog box containing all the controls needed for the medical store keeper to enter
data.
2. Create Owner draw list box, which has green selection rectangle and white text
instead of blue (default) selection rectangle.

<Previous Lesson

Visual Programming

Next Lesson>

Home

Lesson Plan

Topics

Go to Top

Next Lesson
Previous Lesson
Lesson Plan
Topics
Home
Go to Top