Controls

A control is a child window an application uses in conjunction with another window to perform simple input and output (I/O) tasks. Controls are most often used within dialog boxes, but they can also be used in other windows. Controls within dialog boxes provide the user with the means to type text, choose options, and direct a dialog box to complete its action. Controls in other windows provide a variety of services, such as letting the user choose commands, view status, and view and edit text.


About Controls

Controls, like other windows, each belong to a window class, either predefined or application defined. The window class and the corresponding window procedure define the properties of the control, its appearance, behavior, and purpose. An application can create controls individually by specifying the name of the window class when calling the CreateWindowEx function. An application can also direct the system to create controls for a dialog box by specifying the controls in the dialog box template.

Controls are child windows. When the system creates controls for a dialog box, each control is the child of the dialog box. When an application creates a control, the control is the child of a window identified by the application. This relationship is important because a control sends messages, called notification messages, to its parent window when events, such as input from the user, occur in the control. The application relies on these notification messages to determine what action the user wants the application to take.

Because controls are windows, an application can manipulate them by using the window-management functions, such as the ShowWindow and EnableWindow functions. If the window class for a control supports control messages, an application can also manipulate a control of that class by using the SendMessage function to send these messages to the control. The purpose and function of each control message is specific to the window class and is defined by the control's window procedure.


Predefined Controls

The system provides several predefined window classes for controls. Controls belonging to these window classes are called predefined controls. An application creates a predefined control of a particular type by specifying the appropriate window class name in either the CreateWindowEx function or the dialog box template. The following are the predefined window classes.

Name | Description
BUTTON | Creates button controls. These controls typically notify the parent window when the user chooses the control. For more information, see Buttons.
COMBOBOX | Creates combo boxes. These controls are a combination of list boxes and edit controls, letting the user choose and edit items. For more information, see Combo Boxes.
EDIT | Creates edit controls. These controls let the user view and edit text. For more information, see Edit Controls.
LISTBOX | Creates list boxes. These controls display a list from which the user can select one or more items. For more information, see List Boxes.
RichEdit | Creates Rich Edit version 1.0 controls. These controls let the user view and edit text with character and paragraph formatting, and can include embedded COM objects. For more information, see Rich Edit Controls.
RICHEDIT_CLASS | Creates Rich Edit version 2.0 controls. These controls let the user view and edit text with character and paragraph formatting, and can include embedded COM objects. For more information, see Rich Edit Controls.
SCROLLBAR | Creates scroll bar controls. These controls let the user choose the direction and distance to scroll information in a related window. For more information, see Scroll Bars.
STATIC | Creates static controls. These controls often act as labels for other controls. For more information, see Static Controls.

Each predefined window class has a corresponding set of control styles that enable an application to vary the appearance and behavior of the controls it creates. For example, the BUTTON class supports styles to create push buttons, radio buttons, check boxes, and group boxes. An application specifies the style when creating the control.

Each predefined window class has a corresponding set of notification and control messages. Applications rely on the notification messages to determine when the user has provided input to the controls. For example, a push button sends a BN_CLICKED message to the parent window when the user clicks the button. Applications use the control messages to retrieve information from the controls and to manipulate the appearance and behavior of the controls. For example, an application can send a BM_GETCHECK message to a check box to determine whether it currently contains a check mark.

Most applications make extensive use of predefined controls in dialog boxes and other windows. Because predefined controls offer many capabilities, a full discussion of each is beyond the scope of this topic.


Custom Controls

Applications can create custom controls to perform tasks not supported by predefined controls. The Win32 API provides the following ways to create custom controls:

  • Using owner-drawn controls
  • Subclassing the window class of an existing control
  • Implementing an application-defined window class

Using Owner-Drawn Controls

Buttons, list boxes, and combo boxes have owner-drawn styles available that direct the control to send a message to the parent window whenever the control must be drawn. This feature permits an application to alter the appearance of a control. For buttons, the owner-drawn style affects how the system draws the entire control. For list boxes and combo boxes, the parent window draws the items within the control, and the control draws its own outline. For example, an application can customize a list box so that it displays a small bitmap next to each item in the list.

An application can designate list boxes, combo boxes, and buttons as owner-drawn controls by creating them with the appropriate style. When a control has the owner-drawn style, the system handles the user's interaction with the control as usual, performing such tasks as detecting when a user has chosen a button and notifying the button's owner of the event. However, because the control is owner drawn, the parent window of the control is responsible for the visual appearance of the control. For more information about owner-drawn controls, see owner-drawn buttons, owner-drawn list boxes, and owner-drawn combo boxes.

Subclassing the Window Class of an Existing Control

Subclassing an existing control is another way to create a custom control. The subclass procedure can alter selected behaviors of the control by processing those messages that affect the selected behaviors. All other messages pass to the original window procedure for the control. For example, an application can display a small bitmap next to the text in a read-only, single-line edit control by subclassing the control and processing the WM_PAINT message. For more information, see Window Procedure Subclassing.

Although an application may subclass a predefined control, it relies on the window procedure of the control to provide all other aspects of the control's behavior. For more information about a control's behavior, see the individual topic for the predefined controls.

Implementing an Application-defined Window Class

The process for registering an application-defined window class for a custom control is the same as for registering a class for an ordinary window. To create a custom control, specifying the name of the window class in the CreateWindowEx function or in a dialog box template. Each class must have a unique name, a corresponding window procedure, and other information.

At a minimum, the window procedure draws the control. If an application uses the control to let the user type information, the window procedure also processes input messages from the keyboard and mouse and sends notification messages to the parent window. In addition, if the control supports control messages, the window procedure processes messages sent to it by the parent window or other windows. For example, controls often process the WM_GETDLGCODE message sent by dialog boxes to direct a dialog box to process keyboard input in a given way.


Control Notification Messages

A control should send a notification message to its parent window to notify the parent about user input or changes to the control. The notification message is a WM_COMMAND message that includes a control identifier and a notification code identifying the nature of the event. A control identifier is a unique number the application uses to identify the control sending the message. The application sets the identifier for a control when it creates the control. The application specifies the identifier either in the hMenu parameter of the CreateWindowEx function or in the id member of the DLGITEMTEMPLATEEX structure.

Because the control does not set the control identifier, the control must retrieve the identifier before it can send notification messages. A control must use the GetDlgCtrlID function to retrieve its own control identifier. Although the control identifier is specified as the menu handle when the control is created, the GetMenu function cannot be used to retrieve the identifier. Alternatively, a control can retrieve the identifier from the hMenu member in the CREATESTRUCT structure while processing the WM_CREATE message.


Control Messages

A parent window or other windows send control messages to direct a control to perform specific tasks. The window procedure processes these messages and carries out the requested action.

Control messages can be predefined or application defined. The system has several predefined messages, such as WM_GETTEXT and WM_GETDLGCODE, that it sends to controls. These messages typically correspond to window-management functions that carry out actions on windows. In general, the window procedure for an application-defined control should process any predefined control message in the following table if the message affects the operation of the control.

Message | Recommendation
WM_GETDLGCODE | Process if the control uses the enter, esc, tab, or arrow keys. The IsDialogMessage function sends this message to controls in a dialog box to determine whether to process the keys or pass them to the control.
WM_GETFONT | Process if the WM_SETFONT message is also processed.
WM_GETTEXT | Process if the control text is not the same as the title specified by the CreateWindowEx function.
WM_GETTEXTLENGTH | Process if the control text is not the same as the title specified by the CreateWindowEx function.
WM_KILLFOCUS | Process if the control displays a caret, a focus rectangle, or another item to indicate that it has the input focus.
WM_SETFOCUS | Process if the control displays a caret, a focus rectangle, or another item to indicate that it has the input focus.
WM_SETTEXT | Process if the control text is not the same as the title specified by the CreateWindowEx function.
WM_SETFONT | Process if the control displays text. The system sends this message when creating a dialog box that has the DS_SETFONT style.

Application-defined control messages are specific to the given control and must be explicitly sent to the control by using a SendMessage or SendDlgItemMessage function. The numeric value for each message must be unique and must not conflict with the values of other window messages. To ensure that application-defined message values do not conflict, an application should create each value by adding a unique number to the WM_USER value.


Control Reference

The following section lists the messages associated with controls.


Control Messages

The following messages are used with controls.

WM_GETFONT
WM_SETFONT


WM_GETFONT

An application sends a WM_GETFONT message to a control to retrieve the font with which the control is currently drawing its text.

WM_GETFONT
wParam = 0; // not used, must be zero
lParam = 0; // not used, must be zero

Parameters

This message has no parameters.

Return Values

The return value is a handle to the font used by the control, or NULL if the control is using the system font.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Controls Overview, Control Messages, WM_SETFONT


WM_SETFONT

An application sends a WM_SETFONT message to specify the font that a control is to use when drawing text.

WM_SETFONT
wParam = (WPARAM) hfont;            // handle of font
lParam = MAKELPARAM(fRedraw, 0);    // redraw flag

Parameters

hfont
Value of wParam. Handle to the font. If this parameter is NULL, the control uses the default system font to draw text.
fRedraw
Value of lParam. Specifies whether the control should be redrawn immediately upon setting the font. Setting the fRedraw parameter to TRUE causes the control to redraw itself.

Return Values

This message does not return a value.

Remarks

The WM_SETFONT message applies to all controls, not just those in dialog boxes.

The best time for the owner of a dialog box control to set the font of the control is when it receives the WM_INITDIALOG message. The application should call the DeleteObject function to delete the font when it is no longer needed; for example, after it destroys the control.

The size of the control does not change as a result of receiving this message. To avoid clipping text that does not fit within the boundaries of the control, the application should correct the size of the control window before it sets the font.

When a dialog box uses the DS_SETFONT style to set the text in its controls, the system sends the WM_SETFONT message to the dialog box procedure before it creates the controls. An application can create a dialog box that contains the DS_SETFONT style by calling any of the following functions:

  • CreateDialogIndirect
  • CreateDialogIndirectParam
  • DialogBoxIndirect
  • DialogBoxIndirectParam

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Controls Overview, Control Messages, CreateDialogIndirect, CreateDialogIndirectParam, DeleteObject, DialogBoxIndirect, DialogBoxIndirectParam, WM_INITDIALOG, DLGTEMPLATE


Buttons

Dialog boxes and controls support communication between an application and the user. A button is a control the user can click to provide input to an application.


About Buttons

There are several types of buttons and one or more button styles to distinguish among buttons of the same type. The user clicks a button using the mouse or keyboard. Clicking a button typically changes its visual appearance and state (from checked to unchecked, for example). The system, the button, and the application cooperate in changing the button's appearance and state. A button can send messages to its parent window, and a parent window can send messages to a button. Some buttons are painted by the system, some by the application. Buttons can be used alone or in groups and can appear with or without application-defined text (a label). They belong to the BUTTON window class.

Although an application can use buttons in overlapped, pop-up, and child windows, they are designed for use in dialog boxes, where the system standardizes their behavior. If an application uses buttons outside dialog boxes, it increases the risk that the application may behave in a nonstandard fashion. Applications typically either use buttons in dialog boxes or use window subclassing to create customized buttons.

For general information about controls, see Controls. For more information about dialog boxes, see Dialog Boxes.


Button Types and Styles

There are five kinds of buttons:

  • push buttons
  • check boxes
  • radio buttons
  • owner-drawn buttons
  • group boxes

Each type of button has one or more styles. For a table of button styles, see Button Styles.


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 containing the BN_CLICKED notification code. In response, the dialog box typically closes and carries out the operation indicated by the button.


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 (an check mark inside the box) or unchecked (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 unchecked and back again. Repeatedly clicking a three-state check box toggles it from checked to unchecked 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 three-state 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 for those styles. Regardless of the check box style, the system automatically repaints the check box once its state is changed.


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 unchecked (no dot in the button). Repeatedly selecting a radio button (standard or automatic) toggles it from checked to unchecked 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 1for 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 unchecked. The same behavior is available for standard radio buttons by using the WS_GROUP style, as discussed in Dialog Boxes.


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.

For an example of an owner-drawn button, see Using Owner-Drawn Buttons.


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.


Button States

This section discusses how selecting a button changes its state and how the application should respond. The section consists of the following topics:

  • Button Selection
  • Elements of a Button State
  • Changes to a Button State


Button Selection

The user can select a button in three ways: by clicking it with the mouse, by tabbing to it and then pressing the ENTER key, or (if the button is part of a group defined by the WS_GROUP style) by tabbing to the selected button in the group and using the arrow keys to move within that group. The two tabbing methods are part of the predefined keyboard interface provided by the system. For a complete description of this interface, see Dialog Boxes.

Selecting a button typically causes the following events:

  • The system gives the button the keyboard focus.
  • The button sends its parent window a message to notify it of the selection.
  • The parent window (or the system) sends the button a message to change its state.
  • The parent window (or the system) repaints the button to reflect its new state.


Elements of a Button State

A button's state can be characterized by its focus state, push state, and check state.

Focus State

The focus state applies to a check box, radio button, push button, or owner-drawn button. A button receives the keyboard focus when the user selects it and loses the focus when the user selects another control. Only one control can have the keyboard focus at a time.

When a button has the keyboard focus, the system typically highlights the text, icon, or bitmap of a button by surrounding it with a dotted line. In addition, a push button has a heavy dark border when it has the focus. The system automatically changes the highlight for an automatic button, but the application must change the highlight for a non-automatic button by sending messages.

Push State

The push state applies to a push button, check box, radio button, or three-state check box, but does not apply to other buttons. The push state of a button can be either pushed or not pushed. When a push button (or any button with the BS_PUSHLIKE style) is pushed, the button is drawn as a sunken button. When it is not pushed, it is drawn as a raised button. When a check box, radio button, or three-state check box is clicked, the background of the button is grayed. When it is not pushed, the background of the button is not grayed.

Check State

The check state applies to a check box, radio button, or three-state check box, but does not apply to other buttons. The state can be checked, unchecked, or (for three-state check boxes) indeterminate. A check box is checked when it contains a check mark, and is unchecked when it does not. A radio button is checked when it contains a black dot; and is unchecked when it does not. A three-state check box is checked when it contains a check mark, is unchecked when it does not, and is indeterminate when it contains a grayed box. The system automatically changes the check state of an automatic button, but the application must change the check state of a non-automatic button.


Changes to a Button State

When the user selects a button, it is generally necessary to change one or more of the button's state elements. The system automatically changes the focus state for all button types, the push state for push buttons or buttons with the BS_PUSHLIKE style, and the check state for all automatic buttons. The application must make all other state changes, taking into account the button's type, style, and current state. The following list shows the state elements that must be changed for each button type:

  • A check box must change the check state.
  • A radio button must change the check state. It may also be necessary to change the check state of other radio buttons in the same group to ensure the mutually exclusive nature of radio buttons.
  • Because the state of an owner-drawn button is application dependent, what the application must change in the button can vary. No elements of a group box must be changed, because users cannot select group boxes.

An application can determine a button's state by sending it a BM_GETCHECK or BM_GETSTATE message; the application can set a button's state by sending it a BM_SETCHECK or BM_SETSTATE message.


Notification Messages from Buttons

When the user selects 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, 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
BN_CLICKED | The user clicked a button.
BN_DBLCLK | The user double-clicked a button.
BN_DISABLE | A button is disabled.
BN_PUSHED | 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 | 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. It sends the BN_CLICKED and BN_DBLCLK notification messages regardless of the BS_NOTIFY style.

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_DBLCLK notification 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. For information about sending messages to buttons, see Messages to Buttons.

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. For more information about this message, see Using Owner-Drawn Buttons.


Messages to Buttons

A parent window can send messages to a button in an overlapped or child window by using the SendMessage function, or it can send messages to a button in a dialog box by using the SendDlgItemMessage, CheckDlgButton, CheckRadioButton, and IsDlgButtonChecked functions.

An application can use the BM_GETCHECK message to retrieve the check state of check box or radio button. An application can also use the BM_GETSTATE message to retrieve the button's current states (the check state, push state, and focus state). To get information about a specific state, use a bitmask on the returned state value.

The BM_SETCHECK message sets the check state of a check box or radio button; the message returns zero. The BM_SETSTATE message sets the push state of a button; this message also returns zero. The BM_SETSTYLE message changes the style of a button. It is designed for changing button styles within a type (for example, changing a check box to an automatic check box). It is not designed for changing between types (for example, changing a check box to a radio button). An application should not change a button from one type to another.

A button of the BS_BITMAP or BS_ICON style displays a bitmap or icon instead of text. The BM_SETIMAGE message associates a handle to a bitmap or icon with a button. The BM_GETIMAGE message retrieves a handle to the bitmap or icon associated with a button.

An application can also use the DM_GETDEFID message to retrieve the identifier of the default push button control in a dialog box. An application can use the DM_SETDEFID message to set the default push button for a dialog box.

Calling the CheckDlgButton or CheckRadioButton function is equivalent to sending a BM_SETCHECK message. Calling the IsDlgButtonChecked function is equivalent to sending a BM_GETCHECK message.


Button Color Messages

The system provides default color values for buttons. The system sends a WM_CTLCOLORBTN message to a button's parent window before the button is drawn. This message contains a handle to the button's device context and a handle to the child window. The parent window can use these handles to change the button's text and background colors. The following table shows the default button-color values.

Value | Element colored
COLOR_BTNFACE | Button faces.
COLOR_BTNHIGHLIGHT | Highlight area (the top and left edges) of a button.
COLOR_BTNSHADOW | Shadow area (the bottom and right edges) of a button.
COLOR_BTNTEXT | Regular (nongrayed) text in buttons.
COLOR_GRAYTEXT | Disabled (gray) text in buttons. This color is set to 0 if the current display driver does not support a solid gray color.
COLOR_WINDOW | Window backgrounds.
COLOR_WINDOWFRAME | Window frames.
COLOR_WINDOWTEXT | Text in windows.

An application can retrieve the default values for these colors by calling the GetSysColor function, or set the values by calling the SetSysColors function. For more information about system colors, see System Information. For more information about how colors are used with controls, see Controls.


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.
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. Unchecks 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

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.
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.


Using Buttons

The following explain of how to perform the following tasks:

  • Creating a button outside a dialog box
  • Using buttons that are not owner-drawn
  • Using owner-drawn buttons


Creating a Button Outside a Dialog Box

The following example shows how to use the CreateWindow function to create a default push button.

hwndButton = CreateWindow(
    "BUTTON",   // predefined class
    "OK",       // button text
    WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,  // styles

    // Size and position values are given explicitly, because
    // the CW_USEDEFAULT constant gives zero values for buttons.
    10,         // starting x position
    10,         // starting y position
    100,        // button width
    100,        // button height
    hwnd,       // parent window
    NULL,       // No menu
    (HINSTANCE) GetWindowLong(hwnd, GWL_HINSTANCE),
    NULL);      // pointer not needed


Using Buttons that Are Not Owner-Drawn

The example in this section is the window procedure for the dialog box shown in the following illustration.

The check boxes and radio buttons in the Buttons dialog box are automatic. The check boxes are three-state. The Clear Colors button is a default push button. The check boxes, radio buttons, and push buttons are defined in the header file of the application, as follows.

#define IDC_BOX1        101             // first check box
#define IDC_BOX2        102             // second check box
#define IDC_BOX3        103             // third check box
#define IDC_REDBACK     104             // top radio button
#define IDC_BLUEBACK    105             // bottom radio button
#define IDC_CLEARBOXES  107             // top push button
#define IDC_CLEARBACK   108             // bottom push button

Clicking any of these controls results in a change to boxes 1, 2, and 3. You must declare and define the following function to paint boxes 1, 2, and 3.

void BoxPainter(
    HWND hDlg,        // window handle
    UINT uBox,        // box to paint
    LRESULT lState);  // state of box

In the following window procedure, the WM_CTLCOLORDLG message notifies the application that the dialog box is about to be drawn. If the user presses the Clear Colors button (signified by the fClearColor flag), the procedure uses the SendDlgItemMessage function to uncheck the check boxes and radio buttons. The BN_CLICKED notification message contains the identifiers of the button that was clicked.

HBRUSH hbrRed, hbrBlue, hbrWhite;
BOOL fRedBack, fBlueBack, fClearColor;  // background-state flags

BOOL CALLBACK ButtonProc(HWND hDlg, UINT message, WPARAM wParam,
                         LPARAM lParam)
{
    LRESULT lState;

    switch (message)
    {
        case WM_INITDIALOG:
            hbrRed = CreateSolidBrush(RGB(255, 0, 0));
            hbrBlue = CreateSolidBrush(RGB(0, 0, 255));
            hbrWhite = GetStockObject(WHITE_BRUSH);
            return TRUE;

        case WM_CTLCOLORDLG:
            if (fRedBack)
            {
                fRedBack = FALSE;
                return (LRESULT) hbrRed;
            }
            else if (fBlueBack)
            {
                fBlueBack = FALSE;
                return (LRESULT) hbrBlue;
            }
            else if (fClearColor)
            {
                fClearColor = FALSE;

                // Uncheck all check boxes and radio buttons.
                SendDlgItemMessage(hDlg,  // window handle
                    IDC_BOX1,             // button identifier
                    BM_SETCHECK,          // message
                    0,                    // check state unchecked)
                   0);                   // must be zero
                SendDlgItemMessage(hDlg, IDC_BOX2, BM_SETCHECK, 0, 0);
                SendDlgItemMessage(hDlg, IDC_BOX3, BM_SETCHECK, 0, 0);
                SendDlgItemMessage(hDlg,IDC_REDBACK,BM_SETCHECK,0,0);
                SendDlgItemMessage(hDlg,IDC_BLUEBACK,BM_SETCHECK,0,0);
            }
            return (LRESULT) hbrWhite;

        case WM_COMMAND:
                if (wParam == IDOK)
                {
                    EndDialog(hDlg, TRUE);
                    return TRUE;
                }

                if (HIWORD(wParam) == BN_CLICKED)
                {
                    switch (LOWORD(wParam))
                    {
                        case IDC_BOX1:

                            // Retrieve the state of the check box.
                            lState = SendDlgItemMessage(
                                hDlg, IDC_BOX1, BM_GETSTATE,
                                0, 0);

                            BoxPainter(hDlg, 1, lState);
                            break;

                        case IDC_BOX2:
                            lState = SendDlgItemMessage(
                                hDlg, IDC_BOX2, BM_GETSTATE, 0, 0);
                            BoxPainter(hDlg, 2, lState);
                            break;

                        case IDC_BOX3:
                            lState = SendDlgItemMessage(
                                hDlg, IDC_BOX3, BM_GETSTATE, 0, 0);
                            BoxPainter(hDlg, 3, lState);
                            break;

                        case IDC_REDBACK:
                            fRedBack = TRUE;
                            InvalidateRect(hDlg, NULL, TRUE);
                            break;

                        case IDC_BLUEBACK:
                            fBlueBack = TRUE;
                            InvalidateRect(hDlg, NULL, TRUE);
                            break;

                        case IDC_CLEARBACK:
                            fClearColor = TRUE;
                            InvalidateRect(hDlg, NULL, TRUE);
                            break;

                        case IDC_CLEARBOXES:
                            BoxPainter(hDlg, 4, (LRESULT) 0);
                            break;
                    }
                }

        case WM_DESTROY:
            DeleteObject(hbrRed);
            DeleteObject(hbrBlue);

            // Do not delete hbrWhite, because it is a stock object.

            break;

    }
    return FALSE;       // did not process a message
        UNREFERENCED_PARAMETER(lParam);
}


Using Owner-Drawn Buttons

The parent window of an owner-drawn button typically responds to at least three messages for the button: WM_INITDIALOG, WM_COMMAND, and WM_DRAWITEM. It is not necessary to process the WM_MEASUREITEM message for owner-drawn buttons.

When you must paint an owner-drawn button, the system sends the parent window a WM_DRAWITEM message whose lParam points to a DRAWITEMSTRUCT structure. Use this structure with all owner-drawn controls to provide the application with the information it requires to paint the control. The itemAction and itemState members of the DRAWITEMSTRUCT structure define how to paint an owner-drawn button.

The following example shows how to process WM_INITDIALOG, WM_DRAWITEM, and WM_COMMAND messages for owner-drawn buttons. This example demonstrates how to draw one of two bitmaps for a control, depending on whether the control is selected. You would typically use the wParam parameter of the WM_DRAWITEM message to identify the control; in this example, only one control is assumed.

BOOL CALLBACK OwnDrawProc(HWND hDlg, UINT message, WPARAM wParam,
                          LPARAM lParam)
{
    HDC hdcMem;
    LPDRAWITEMSTRUCT lpdis;

    switch (message)
    {
        case WM_INITDIALOG:

            // hinst, hbm1 and hbm2 are defined globally.
            hbm1 = LoadBitmap((HANDLE) hinst, "OwnBit1");
            hbm2 = LoadBitmap((HANDLE) hinst, "OwnBit2");
            return TRUE;

        case WM_DRAWITEM:
            lpdis = (LPDRAWITEMSTRUCT) lParam;
            hdcMem = CreateCompatibleDC(lpdis->hDC);

            if (lpdis->itemState & ODS_SELECTED)  // if selected
                SelectObject(hdcMem, hbm2);
            else
                SelectObject(hdcMem, hbm1);

            // Destination
            StretchBlt(
                lpdis->hDC,         // destination DC
                lpdis->rcItem.left, // x upper left
                lpdis->rcItem.top,  // y upper left

                // The next two lines specify the width and
                // height.
                lpdis->rcItem.right - lpdis->rcItem.left,
                lpdis->rcItem.bottom - lpdis->rcItem.top,
                hdcMem,    // source device context
                0, 0,      // x and y upper left
                32,        // source bitmap width
                32,        // source bitmap height
                SRCCOPY);  // raster operation

            DeleteDC(hdcMem);
            return TRUE;

        case WM_COMMAND:
            if (wParam == IDOK
                || wParam == IDCANCEL)
            {
                EndDialog(hDlg, TRUE);
                return TRUE;
            }
            if (HIWORD(wParam) == BN_CLICKED)
            {
                switch (LOWORD(wParam))
                {
                    case IDC_OWNERDRAW:

                        // application-defined processing

                        break;
                }
            }
            break;

        case WM_DESTROY:
            DeleteObject(hbm1);  // delete bitmaps
            DeleteObject(hbm2);

            break;

    }
    return FALSE;
        UNREFERENCED_PARAMETER(lParam);
}


Button Reference

The following elements are associated with buttons.

  • Button Functions
  • Button Messages
  • Button Styles


Button Functions

The following functions are used with buttons.

CheckDlgButton
CheckRadioButton
IsDlgButtonChecked


CheckDlgButton

The CheckDlgButton function changes the check state of a button control.

BOOL CheckDlgButton(
  HWND hDlg,      // handle to dialog box
  int nIDButton,  // button-control identifier
  UINT uCheck     // check state
);

Parameters

hDlg
Handle to the dialog box that contains the button.
nIDButton
Identifies the button to modify.
uCheck
Specifies the check state of the button. This parameter can be one of the following values:
Value | Meaning
BST_CHECKED | Sets the button state to checked.
BST_INDETERMINATE | Sets the button state to grayed, indicating an indeterminate state. Use this value only if the button has the BS_3STATE or BS_AUTO3STATE style.
BST_UNCHECKED | Sets the button state to unchecked

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The CheckDlgButton function sends a BM_SETCHECK message to the specified button control in the specified dialog box.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Buttons Overview, Button Functions, CheckRadioButton, IsDlgButtonChecked


CheckRadioButton

The CheckRadioButton function adds a check mark to (checks) a specified radio button in a group and removes a check mark from (clears) all other radio buttons in the group.

BOOL CheckRadioButton(
  HWND hDlg,          // handle to dialog box
  int nIDFirstButton, // identifier of first radio button in group
  int nIDLastButton,  // identifier of last radio button in group
  int nIDCheckButton  // identifier of radio button to select
);

Parameters

hDlg
Handle to the dialog box that contains the radio button.
nIDFirstButton
Specifies the identifier of the first radio button in the group.
nIDLastButton
Specifies the identifier of the last radio button in the group.
nIDCheckButton
Specifies the identifier of the radio button to select.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The CheckRadioButton function sends a BM_SETCHECK message to each of the radio buttons in the indicated group.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Buttons Overview, Button Functions, BM_SETCHECK, CheckDlgButton, IsDlgButtonChecked


IsDlgButtonChecked

The IsDlgButtonChecked function determines whether a button control has a check mark next to it or whether a three-state button control is grayed, checked, or neither.

UINT IsDlgButtonChecked(
  HWND hDlg,     // handle to dialog box
  int nIDButton  // button identifier
);

Parameters

hDlg
Handle to the dialog box that contains the button control.
nIDButton
Specifies the integer identifier of the button control.

Return Values

The return value from a button created with the BS_AUTOCHECKBOX, BS_AUTORADIOBUTTON, BS_AUTO3STATE, BS_CHECKBOX, BS_RADIOBUTTON, or BS_3STATE style can be one of the following:

Value | Meaning
BST_CHECKED | Button is checked.
BST_INDETERMINATE | Button is grayed, indicating an indeterminate state (applies only if the button has the BS_3STATE or BS_AUTO3STATE style).
BST_UNCHECKED | Button is unchecked

If the button has any other style, the return value is zero.

Remarks

The IsDlgButtonChecked function sends a BM_GETCHECK message to the specified button control.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Buttons Overview, Button Functions, CheckDlgButton


Button Messages

The following messages are used with buttons.

BM_CLICK
BM_GETCHECK
BM_GETIMAGE
BM_GETSTATE
BM_SETCHECK
BM_SETIMAGE
BM_SETSTATE
BM_SETSTYLE
BN_CLICKED
BN_DBLCLK
BN_DISABLE
BN_DOUBLECLICKED
BN_HILITE
BN_KILLFOCUS
BN_PAINT
BN_PUSHED
BN_SETFOCUS
BN_UNHILITE
BN_UNPUSHED
WM_CTLCOLORBTN


BM_CLICK

An application sends a BM_CLICK message to simulate the user clicking a button. This message causes the button to receive a WM_LBUTTONDOWN and a WM_LBUTTONUP message, and the button's parent window to receive a BN_CLICKED notification message.

BM_CLICK
wParam = 0;     // not used; must be zero
lParam = 0;     // not used; must be zero

Parameters

This message has no parameters.

Return Values

This message does not return a value.

Remarks

If the button is in a dialog box and the dialog box is not active, the BM_CLICK message might fail. To ensure success in this situation, call the SetActiveWindow function to activate the dialog box before sending the BM_CLICK message to the button.

QuickInfo

Windows NT: Requires version 3.5 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Buttons Overview, Button Messages, BN_CLICKED, SetActiveWindow, WM_LBUTTONDOWN, WM_LBUTTONUP


BM_GETCHECK

An application sends a BM_GETCHECK message to retrieve the check state of a radio button or check box.

BM_GETCHECK
wParam = 0;     // not used; must be zero
lParam = 0;     // not used; must be zero

Parameters

This message has no parameters.

Return Values

The return value from a button created with the BS_AUTOCHECKBOX, BS_AUTORADIOBUTTON, BS_AUTO3STATE, BS_CHECKBOX, BS_RADIOBUTTON, or BS_3STATE style can be one of the following:

Value | Meaning
BST_CHECKED | Button is checked.
BST_INDETERMINATE | Button is grayed, indicating an indeterminate state (applies only if the button has the BS_3STATE or BS_AUTO3STATE style).
BST_UNCHECKED | Button is unchecked

If the button has any other style, the return value is zero.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Buttons Overview, Button Messages, BM_GETSTATE, BM_SETCHECK


BM_GETIMAGE

An application sends a BM_GETIMAGE message to retrieve a handle to the image (icon or bitmap) associated with the button.

BM_GETIMAGE
wParam = (WPARAM) fImageType; // image-type flag
lParam = 0;                   // not used, must be zero

Parameters

fImageType
Value of wParam. Specifies the type of image to associate with the button. This parameter can be one of the following values:

IMAGE_BITMAP
IMAGE_ICON

Return Values

The return value is a handle to the image, if any; otherwise, it is NULL.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Buttons Overview, Button Messages, BM_SETIMAGE


BM_GETSTATE

An application sends a BM_GETSTATE message to determine the state of a button or check box.

BM_GETSTATE
wParam = 0;     // not used; must be zero
lParam = 0;     // not used; must be zero

Parameters

This message has no parameters.

Return Values

The return value specifies the current state of the button. You can use the following bitmasks to extract information about the state:

Value | Meaning
0x0003 | Specifies the check state (radio buttons and check boxes only). A value of BST_UNCHECKED indicates the button is unchecked; a value of BST_CHECKED indicates the button is checked. A radio button is checked when it contains a dot; a check box is checked when it contains an X. A value of BST_INDETERMINATE indicates the check state is indeterminate (applies only if the button has the BS_3STATE or BS_AUTO3STATE style). A three-state check box is grayed when its state is indeterminate.
BST_CHECKED | Indicates the button is checked.
BST_FOCUS | Specifies the focus state. A nonzero value indicates that the button has the keyboard focus.
BST_INDETERMINATE | Indicates the button is grayed because the state of the button is indeterminate. This value applies only if the button has the BS_3STATE or BS_AUTO3STATE style.
BST_PUSHED | Specifies the highlight state. A nonzero value indicates that the button is highlighted. A button is automatically highlighted when the user positions the cursor over it and presses and holds the left mouse button. The highlighting is removed when the user releases the mouse button.
BST_UNCHECKED | Indicates the button is unchecked. Same as a return value of zero.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Buttons Overview, Button Messages, BM_GETCHECK, BM_SETSTATE


BM_SETCHECK

An application sends a BM_SETCHECK message to set the check state of a radio button or check box.

BM_SETCHECK
wParam = (WPARAM) fCheck; // check state
lParam = 0;               // not used; must be zero

Parameters

fCheck
Value of wParam. Specifies the check state. This parameter can be one of the following values:
Value | Meaning
BST_CHECKED | Sets the button state to checked.
BST_INDETERMINATE | Sets the button state to grayed, indicating an indeterminate state. Use this value only if the button has the BS_3STATE or BS_AUTO3STATE style.
BST_UNCHECKED | Sets the button state to unchecked

Return Values

This message always returns zero.

Remarks

The BM_SETCHECK message has no effect on push buttons.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Buttons Overview, Button Messages, BM_GETCHECK, BM_GETSTATE, BM_SETSTATE


BM_SETIMAGE

An application sends a BM_SETIMAGE message to associate a new image (icon or bitmap) with the button.

BM_SETIMAGE
wParam = (WPARAM) fImageType;       // image-type flag
lParam = (LPARAM) (HANDLE) hImage;  // handle to the image

Parameters

fImageType
Value of wParam. Specifies the type of image to associate with the button. This parameter can be one of the following values:

IMAGE_BITMAP
IMAGE_ICON

hImage
Value of lParam. Handle to the image to associate with the button.

Return Values

The return value is a handle to the image previously associated with the button, if any; otherwise, it is NULL.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Buttons Overview, Button Messages, BM_GETIMAGE


BM_SETSTATE

An application sends a BM_SETSTATE message to change the highlight state of a button. The highlight state indicates whether the button is highlighted as if the user had pushed it.

BM_SETSTATE
wParam = (WPARAM) fState;   // highlight state
lParam = 0;                 // not used; must be zero

Parameters

fState
Value of wParam. Specifies whether the button is to be highlighted. A value of TRUE highlights the button. A value of FALSE removes any highlighting.

Return Values

This message always returns zero.

Remarks

Highlighting only affects the appearance of a button. It has no effect on the check state of a radio button or check box.

A button is automatically highlighted when the user positions the cursor over it and presses and holds the left mouse button. The highlighting is removed when the user releases the mouse button.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Buttons Overview, Button Messages, BM_GETSTATE, BM_SETCHECK


BM_SETSTYLE

An application sends a BM_SETSTYLE message to change the style of a button.

BM_SETSTYLE
wParam =  (WPARAM) LOWORD(dwStyle); // style
lParam =  MAKELPARAM(fRedraw, 0);   // redraw flag

Parameters

dwStyle
Value of wParam. Specifies the new button style. This parameter can be a combination of button styles. For a table of button styles, see Button Styles.
fRedraw
Value of the low-order word of lParam. Specifies whether the button is to be redrawn. A value of TRUE redraws the button; a value of FALSE does not redraw the button.

Return Values

This message always returns zero.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Buttons Overview, Button Messages


BN_CLICKED

The BN_CLICKED notification message is sent when the user clicks a button. The parent window of the button receives this notification message through the WM_COMMAND message.

BN_CLICKED
idButton = (int) LOWORD(wParam);    // identifier of button
hwndButton = (HWND) lParam;         // handle to button

Remarks

A disabled button does not send a BN_CLICKED notification message to its parent window.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Buttons Overview, Button Messages, WM_COMMAND


BN_DBLCLK

The BN_DBLCLK notification message is sent when the user double-clicks a button that has the BS_OWNERDRAW or BS_RADIOBUTTON style. The parent window of the button receives this notification message through a WM_COMMAND message.

BN_DBLCLK
idButton = (int) LOWORD(wParam);    // identifier of button
hwndButton = (HWND) lParam;         // handle to button

BN_DBLCLK is the same as the BN_DOUBLECLICKED notification message.

Note This notification message is provided for compatibility with applications written for 16-bit versions of Windows earlier than version 3.0. Win32-based applications should use the BS_OWNERDRAW button style and the DRAWITEMSTRUCT structure for this task.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Buttons Overview, Button Messages, BN_CLICKED, BN_DOUBLECLICKED, WM_COMMAND


BN_DISABLE

The BN_DISABLE notification message is sent when a button is disabled. The parent window of the button receives this notification message through the WM_COMMAND message.

BN_DISABLE

Note This notification message is provided for compatibility with applications written for 16-bit versions of Windows earlier than version 3.0. Win32-based applications should use the BS_OWNERDRAW button style and the DRAWITEMSTRUCT structure for this task.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Buttons Overview, Button Messages, DRAWITEMSTRUCT, WM_COMMAND, WM_DRAWITEM


BN_DOUBLECLICKED

The BN_DOUBLECLICKED notification message is sent when the user double-clicks a button that has the BS_OWNERDRAW or BS_RADIOBUTTON style. The parent window of the button receives this notification message through the WM_COMMAND message.

BN_DOUBLECLICKED

BN_DOUBLECLICKED is the same as the BN_DBLCLK notification message.

Note This notification message is provided for compatibility with applications written for 16-bit versions of Windows earlier than version 3.0. Win32-based applications should use the BS_OWNERDRAW button style and the DRAWITEMSTRUCT structure for this task.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Buttons Overview, Button Messages, BN_DBLCLK, DRAWITEMSTRUCT, WM_COMMAND, WM_DRAWITEM


BN_HILITE

The BN_HILITE notification message is sent when the user selects a button. The parent window of the button receives this notification message through the WM_COMMAND message.

BN_HILITE

BN_HILITE is the same as the BN_PUSHED notification message.

Note This notification message is provided for compatibility with applications written for 16-bit versions of Windows earlier than version 3.0. Win32-based applications should use the BS_OWNERDRAW button style and the DRAWITEMSTRUCT structure for this task.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Buttons Overview, Button Messages, BN_PUSHED, BN_UNHILITE, DRAWITEMSTRUCT, WM_COMMAND, WM_DRAWITEM


BN_KILLFOCUS

The BN_KILLFOCUS notification message is sent when a button loses the keyboard focus. The button must have the BS_NOTIFY style to send this notification message. The parent window of the button receives this notification message through the WM_COMMAND message.

BN_KILLFOCUS

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Buttons Overview, Button Messages, BN_SETFOCUS, WM_COMMAND


BN_PAINT

The BN_PAINT notification message is sent when a button should be painted. The parent window of the button receives this notification message through the WM_COMMAND message.

BN_PAINT

Note This notification message is provided for compatibility with applications written for 16-bit versions of Windows earlier than version 3.0. Win32-based applications should use the BS_OWNERDRAW button style and the DRAWITEMSTRUCT structure for this task.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

Buttons Overview, Button Messages, DRAWITEMSTRUCT, WM_COMMAND, WM_DRAWITEM


BN_PUSHED

The BN_PUSHED notification message is sent when the push state of a button is set to pushed. The parent window of the button receives this notification message through the WM_COMMAND message.

BN_PUSHED

BN_PUSHED is the same as the BN_HILITE notification message.

Note This notification message is provided for compatibility with applications written for 16-bit versions of Windows earlier than version 3.0. Win32-based applications should use the BS_OWNERDRAW button style and the DRAWITEMSTRUCT structure for this task.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Buttons Overview, Button Messages, BN_HILITE, BN_UNPUSHED, DRAWITEMSTRUCT, WM_COMMAND, WM_DRAWITEM


BN_SETFOCUS

The BN_SETFOCUS notification message is sent when a button receives the keyboard focus. The button must have the BS_NOTIFY style to send this notification message. The parent window of the button receives this notification message through the WM_COMMAND message.

BN_SETFOCUS

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Buttons Overview, Button Messages, BN_KILLFOCUS, WM_COMMAND


BN_UNHILITE

The BN_UNHILITE notification message is sent when the highlight should be removed from a button. The parent window of the button receives this notification message through the WM_COMMAND message.

BN_HILITE

BN_UNHILITE is the same as the BN_UNPUSHED notification message.

Note This notification message is provided for compatibility with applications written for 16-bit versions of Windows earlier than version 3.0. Win32-based applications should use the BS_OWNERDRAW button style and the DRAWITEMSTRUCT structure for this task.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

Buttons Overview, Button Messages, BN_HILITE, BN_UNPUSHED, DRAWITEMSTRUCT, WM_COMMAND, WM_DRAWITEM


BN_UNPUSHED

The BN_UNPUSHED notification message is sent when the push state of a button is set to unpushed. The parent window of the button receives this notification message through the WM_COMMAND message.

BN_PUSHED

BN_UNPUSHED is the same as the BN_UNHILITE notification message.

Note This notification message is provided for compatibility with applications written for 16-bit versions of Windows earlier than version 3.0. Win32-based applications should use the BS_OWNERDRAW button style and the DRAWITEMSTRUCT structure for this task.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Buttons Overview, Button Messages, BN_PUSHED, DRAWITEMSTRUCT, WM_COMMAND, WM_DRAWITEM


WM_CTLCOLORBTN

The WM_CTLCOLORBTN message is sent to the parent window of a button when the button is about to be drawn. By responding to this message, the parent window can set a button's text and background colors.

WM_CTLCOLORBTN
hdcButton = (HDC) wParam;   // handle to the button display context
hwndButton = (HWND) lParam; // handle to the button

Parameters

hdcButton
Value of wParam. Handle to the display context for the button.
hwndButton
Value of lParam. Handle to the button.

Return Values

If an application processes this message, it must return a handle to a brush. The system uses the brush to paint the background of the button.

Default Action

The DefWindowProc function selects the default system colors for the button.

Remarks

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_CTLCOLORBTN message is never sent between threads. It is sent only within one thread.

The text color of a check box or radio button applies to the box or button, its check mark, and the text. The focus rectangle for these buttons remains the system default color (typically black). The text color of a group box applies to the text but not to the line that defines the box. The text color of a push button applies only to its focus rectangle; it does not affect the color of the text.

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.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

Buttons Overview, Button Messages, DefWindowProc, RealizePalette, SelectPalette, WM_CTLCOLORDLG, WM_CTLCOLOREDIT, WM_CTLCOLORLISTBOX, WM_CTLCOLORMSGBOX, WM_CTLCOLORSCROLLBAR, WM_CTLCOLORSTATIC


Button Styles

If you create a button by specifying the BUTTON class with the CreateWindow or CreateWindowEx function, you can specify a combination of the button styles in the following table.

Style | Meaning
BS_3STATE | Creates a button that is the same as a check box, except that the box can be grayed as well as checked or unchecked. Use the grayed state to show that the state of the check box is not determined.
BS_AUTO3STATE | Creates a button that is the same as a three-state check box, except that the box changes its state when the user selects it. The state cycles through checked, grayed, and unchecked.
BS_AUTOCHECKBOX | Creates a button that is the same as a check box, except that the check state automatically toggles between checked and unchecked each time the user selects the check box.
BS_AUTORADIOBUTTON | Creates a button that is the same as a radio button, except that when the user selects it, The system automatically sets the button's check state to checked and automatically sets the check state for all other buttons in the same group to unchecked.
BS_CHECKBOX | Creates a small, empty check box with text. By default, the text is displayed to the right of the check box. To display the text to the left of the check box, combine this flag with the BS_LEFTTEXT style (or with the equivalent BS_RIGHTBUTTON style).
BS_DEFPUSHBUTTON | Creates a push button that behaves like a BS_PUSHBUTTON style button, but also has a heavy black border. If the button is in a dialog box, the user can select the button by pressing the enter key, even when the button does not have the input focus. This style is useful for enabling the user to quickly select the most likely (default) option.
BS_GROUPBOX | Creates a rectangle in which other controls can be grouped. Any text associated with this style is displayed in the rectangle's upper left corner.
BS_LEFTTEXT | Places text on the left side of the radio button or check box when combined with a radio button or check box style. Same as the BS_RIGHTBUTTON style.
BS_OWNERDRAW | Creates an owner-drawn button. The owner window receives a WM_MEASUREITEM message when the button is created and a WM_DRAWITEM message when a visual aspect of the button has changed. Do not combine the BS_OWNERDRAW style with any other button styles.
BS_PUSHBUTTON | Creates a push button that posts a WM_COMMAND message to the owner window when the user selects the button.
BS_RADIOBUTTON | Creates a small circle with text. By default, the text is displayed to the right of the circle. To display the text to the left of the circle, combine this flag with the BS_LEFTTEXT style (or with the equivalent BS_RIGHTBUTTON style). Use radio buttons for groups of related, but mutually exclusive choices.
BS_USERBUTTON | Obsolete, but provided for compatibility with 16-bit versions of Windows. Win32-based applications should use BS_OWNERDRAW instead.
BS_BITMAP | Specifies that the button displays a bitmap.
BS_BOTTOM | Places text at the bottom of the button rectangle.
BS_CENTER | Centers text horizontally in the button rectangle.
BS_ICON | Specifies that the button displays an icon.
BS_FLAT | Specifies that the button is two-dimensional; it does not use the default shading to create a 3-D image.
BS_LEFT | Left-justifies the text in the button rectangle. However, if the button is a check box or radio button that does not have the BS_RIGHTBUTTON style, the text is left justified on the right side of the check box or radio button.
BS_MULTILINE | Wraps the button text to multiple lines if the text string is too long to fit on a single line in the button rectangle.
BS_NOTIFY | Enables a button to send BN_DBLCLK, BN_KILLFOCUS, and BN_SETFOCUS notification messages to its parent window. Note that buttons send the BN_CLICKED notification message regardless of whether it has this style.
BS_PUSHLIKE | Makes a button (such as a check box, three-state check box, or radio button) look and act like a push button. The button looks raised when it isn't pushed or checked, and sunken when it is pushed or checked.
BS_RIGHT | Right-justifies text in the button rectangle. However, if the button is a check box or radio button that does not have the BS_RIGHTBUTTON style, the text is right justified on the right side of the check box or radio button.
BS_RIGHTBUTTON | Positions a radio button's circle or a check box's square on the right side of the button rectangle. Same as the BS_LEFTTEXT style.
BS_TEXT | Specifies that the button displays text.
BS_TOP | Places text at the top of the button rectangle.
BS_VCENTER | Places text in the middle (vertically) of the button rectangle.


Combo Boxes

A combo box is a unique type of control, defined by the COMBOBOX class, that combines much of the functionality of a list box and an edit control.

This overview describes the types and styles of combo box, the parts of a combo box, the use of an owner-drawn combo box, and how to subclass a combo box. Additional features of combo boxes are also discussed.


About Combo Boxes

The Win32 API provides three types of combo box: simple combo boxes (CBS_SIMPLE), drop-down combo boxes (CBS_DROPDOWN), and drop-down list boxes (CBS_DROPDOWNLIST).

There are also a number of combo box styles that define specific properties. For example, two styles enable an application to create an owner-drawn combo box, making the application responsible for displaying information in the control.

A combo box consists of a list and a selection field. The list presents the options a user can select and the selection field displays the current selection. Except in drop-down list boxes, the selection field is an edit control and can be used to enter text not in the list.


Combo Box Types and Styles

Combo boxes can be characterized by type and style. Combo box types determine whether the combo box list is a drop-down list and whether the selection field is an edit control. A drop-down list appears only when the user opens it, so it uses less screen space than a list that is always visible. If the selection field is an edit control, the user can enter information not in the list; otherwise, the user can only select items in the list.

The following table shows the three combo box types and indicates whether each includes a drop-down list and an edit control:

Combo box type | Drop-down list | Edit control
Drop-down combo box | Yes | Yes
Drop-down list box | Yes | No
Simple combo box | No | Yes

Combo box styles define specific properties of a combo box. You can combine styles; however some styles only apply to certain combo box types. For a table of combo box styles, see Combo Box Styles.


Combo Box List

A list is the portion of a combo box that displays the items a user can select. Typically, an application initializes the contents of the list when it creates a combo box. Any list item selected by the user is the current selection. In simple and drop-down combo boxes, the user can type in the selection field instead of selecting a list item. In these cases, there is no current selection. For more information, see Current Selection.


List Contents

When an application creates a combo box, it typically initializes the combo box by adding one or more items to the list. Later, an application may add or delete list items, reinitialize the list, or retrieve item information from it.

An application adds list items to a combo box by sending the CB_ADDSTRING message to it. The specified item is added to the end of the list or, in a sorted combo box, in its correct sorted position based on the item's string. In an unsorted combo box, an application can use the CB_INSERTSTRING message to insert an item at a specific position. Once added, a list item is identified by its position.

By using the CB_FINDSTRING or CB_FINDSTRINGEXACT message, an application can determine the position of a list item. CB_FINDSTRING finds an item whose string begins with the specified string. CB_FINDSTRINGEXACT finds an item whose string matches the string exactly. Neither message is case sensitive.

An application can remove a list item by using the CB_DELETESTRING message. If an application needs to reinitialize the combo box list, it can first clear its entire contents by using the CB_RESETCONTENT message. When adding multiple items to the list after a combo box has already been shown, an application can clear the redraw flag to prevent the combo box from being repainted after each item is added. For more information about redrawing, see the description of the WM_SETREDRAW message.

To retrieve the string associated with a list item, an application can use the CB_GETLBTEXT message. The item's string is copied to the buffer specified by the application. To ensure that the buffer is large enough to receive the string, the application can first use the CB_GETLBTEXTLEN message to determine the length of the string. To get the number of list items in a combo box, an application can use the CB_GETCOUNT message.


Current Selection

The current selection is a list item the user has selected; the selected text appears in the selection field of the combo box. However, in the case of a simple combo box or a drop down combo box, the current selection is only one form of possible user input in a combo box. The user can also type text in the selection field.

The current selection is identified by the zero-based index of the selected list item. An application can set and retrieve it at any time. The parent window or dialog box procedure receives notifications when user changes the current selection for a combo box. The parent window or dialog box is not notified when the application changes the selection.

When a combo box is created, there is no current selection. This is also true for a simple or drop-down combo box, if the user has edited the contents of the selection field. To set the current selection, an application sends the CB_SETCURSEL message to the combo box. An application can also use the CB_SELECTSTRING message to set the current selection to a list item whose string begins with a specified string. To determine the current selection, an application sends the CB_GETCURSEL message to the combo box. If there is no current selection, this message returns CB_ERR.

When the user changes the current selection in a combo box, the parent window or dialog-box procedure receives a WM_COMMAND message with the notification message CBN_SELCHANGE in the high-order word of the wParam parameter. This notification message is not sent when the current selection is set using the CB_SETCURSEL message.

A drop-down combo box or drop-down list box sends the CBN_CLOSEUP notification to the parent window or dialog-box procedure when the drop-down list closes. If the user changed the current selection, the combo box also sends the CBN_SELCHANGE notification when the drop-down list closes. To execute a specific process each time the user selects a list item, you can handle either the CBN_SELCHANGE or CBN_CLOSEUP notification message. Typically, you would wait for the CBN_CLOSEUP notification before processing a change in the current selection. This can be particularly important if a significant amount of processing is required.

An application could also process the notification messages CBN_SELENDOK and CBN_SELENDCANCEL. The system sends CBN_SELENDOK when the user selects a list item, or selects an item and then closes the list. This indicates the user has finished, and the selection should be processed. CBN_SELENDCANCEL is sent when the user selects an item, but then selects another control, presses the escape key while the drop-down list is open, or closes the dialog box. This indicates the user's selection should be ignored. In a simple combo box, CBN_SELENDOK is sent before every CBN_SELCHANGE message. If the WS_EX_NOPARENTNOTIFY window style is specified for the combo box, the system does not send CBN_SELENDOK and CBN_SELENDCANCEL messages.

In a simple combo box, the system sends the CBN_DBLCLK notification message when the user double-clicks a list item. In a drop-down combo box or drop-down list, a single click hides the list so it is not possible to double-click an item.


Drop-Down Lists

Certain notifications and messages apply only to combo boxes containing drop-down lists. When a drop-down list is open or closed, the parent window of a combo box receives a notification in the form of a WM_COMMAND message. If the list is being opened, the high-order word of wParam is CBN_DROPDOWN. If the list is being closed, it is CBN_CLOSEUP.

An application can open the list of a drop-down combo box or drop-down list box by using the CB_SHOWDROPDOWN message. It can determine whether the list is open by using the CB_GETDROPPEDSTATE message and can determine the coordinates of a drop-down list by using the CB_GETDROPPEDCONTROLRECT message. An application can also increase the width of a drop-down list by using the CB_SETDROPPEDWIDTH message.


Edit Control Selection Fields

The selection field is the portion of a combo box that displays the currently selected list item. In simple and drop-down combo boxes, the selection field is an edit control and can be used to enter text that is not in the list.

An application can retrieve or set the contents of the selection field and can determine or set the edit selection. The application can also limit the amount of text a user can type in the selection field. When the contents of the selection field change, the system sends notification messages to the parent window or dialog box procedure.

To retrieve the content of the selection field, an application can send the WM_GETTEXT message to the combo box. To set the contents of the selection field of a simple or drop-down combo box, an application can send the WM_SETTEXT message to the combo box.

The edit selection is the range of selected text, if any, in the selection field of a simple or drop-down combo box. An application can determine the starting and ending character positions of the current selection by using the CB_GETEDITSEL message. It can also select characters in the edit selection by using the CB_SETEDITSEL message.

Initially, the amount of text that the user can type into the selection field is limited by the size of the selection field. However, if the combobox has the CBS_AUTOHSCROLL style, the text can continue beyond the size of the selection field. An application can use the CB_LIMITTEXT message to limit the amount of text a user can type into the selection field, regardless of whether the control has the CBS_AUTOHSCROLL style.

When the user edits the content of the selection field, the parent window or dialog box procedure receives notification messages. CBN_EDITUPDATE is sent first, indicating that the text in the selection field has been edited. After the altered text is displayed, the system sends CBN_EDITCHANGE. When the selection field content changes as the result of a list item being selected, these messages are not sent.


Owner-Drawn Combo Boxes

An application can create an owner-drawn combo box to take responsibility for painting list items. The parent window or dialog box of an owner-drawn combo box (its owner) receives WM_DRAWITEM messages when a portion of the combo box needs to be painted. An owner-drawn combo box can list information other than, or in addition to, text strings. Owner-drawn combo boxes can be of any type. However, the edit control in a simple or drop-down combo box can only display text, while the owner paints the selection field in a drop-down list box.

The owner of an owner-drawn combo box must process the WM_DRAWITEM message. This message is sent whenever a portion of the combo box must be redrawn. The owner may need to process other messages, depending on the styles specified for the combo box.

An application can create an owner-drawn combo box by specifying the CBS_OWNERDRAWFIXED or CBS_OWNERDRAWVARIABLE style. If all list items in the combo box are the same height, such as strings or icons, an application can use the CBS_OWNERDRAWFIXED style. If list items are of varying height, bitmaps of different size, for example, an application can use the CBS_OWNERDRAWVARIABLE style.

The owner of an owner-drawn combo box can process a WM_MEASUREITEM message to specify the dimensions of list items in the combo box. If the application creates the combo box by using the CBS_OWNERDRAWFIXED style, the system sends the WM_MEASUREITEM message only once. The dimensions specified by the owner are used for all list items. If the CBS_OWNERDRAWVARIABLE style is used, the system sends a WM_MEASUREITEM message for each list item added to the combo box. The owner can determine or set the height of a list item at any time by using the CB_GETITEMHEIGHT and CB_SETITEMHEIGHT messages, respectively.

If the information displayed in an owner-drawn combo box includes text, an application can keep track of the text for each list item by specifying the CBS_HASSTRINGS style. Combo boxes with the CBS_SORT style are sorted based on this text. If a combo box is sorted and not of the CBS_HASSTRINGS style, the owner must process the WM_COMPAREITEM message.

In an owner-drawn combo box, the owner must keep track of list items containing information other than or in addition to text. One convenient way to do this is to save the handle to the information as item data. For more information about item data, see Data Associated with List Items. To free data objects associated with items in a combo box, the owner can process the WM_DELETEITEM message.

For an example of an owner-drawn combo box, see Creating an Owner-Drawn Combo Box.


Subclassed Combo Boxes

Subclassing is a procedure that allows an application to intercept and process messages sent or posted to a window. By using subclassing, an application can substitute its own processing for certain messages, while leaving most message processing to the class-defined window procedure.

When the operating system creates a window, it saves information about it in an internal data structure that includes the address of the window procedure. To subclass a window, an application calls the SetClassLong function to replace the address of that procedure with the instance address of an application-defined subclass procedure. Thereafter, all messages to the window are sent to the subclass procedure. This procedure then uses the CallWindowProc function to pass unprocessed messages to the original window procedure. For a description of the message processing performed by the COMBOBOX class window procedure, see Default Combo Box Behavior.

When the combo box is outside a dialog box, an application cannot process the tab, enter, and escape keys unless it uses a subclass procedure. When a simple or drop-down combo box receives the input focus, it immediately sets the focus to its child edit control. Therefore, an application must subclass the edit control to intercept keyboard input for a simple or drop-down combo box. For an example of this, see Subclassing a Combo Box.

If a subclass procedure processes the WM_PAINT message, it must use the BeginPaint function to prepare for painting. Before calling the EndPaint function, it passes the device-context (DC) handle as the wParam parameter for the window procedure. If EndPaint is called first, the class window procedure does no painting because EndPaint validates the entire window.

A technique related to subclassing is superclassing. A superclass resembles any other class except that its window procedure does not call DefWindowProc to handle unprocessed messages. Instead, it passes unprocessed messages to the window procedure for the parent window class. Follow the guidelines in Window Procedures to avoid problems that can occur with subclassing and superclassing.


Special Combo Box Features

The Win32 API provides special-purpose messages and functions that enable an application to display a directory listing in a combo box, associate data with list items in a combo box, and change the keyboard interface for a drop-down combo box or drop-down list box.


Directory Lists

An application can add the names of files or subdirectories to a combo box by sending the CB_DIR message to it. The wParam parameter for the window procedure specifies the attributes of the files to add, and the lParam parameter points to the text string that defines the file specification.

Within a dialog box, an application can also use DlgDirListComboBox. If the specified filename includes a drive, path, or both, DlgDirListComboBox changes the current drive or directory and removes the drive and path from the filename string. To show the directory name, the function updates the specified static control, if any. It then resets the contents of the combo box, and sends the CB_DIR message to the combo box to add the specified filenames.

To remove the selected filename, directory name, or drive letter from a combo box that has been filled by using DlgDirListComboBox, an application can use the DlgDirSelectComboBoxEx function.

The DlgDirListComboBox and DlgDirSelectComboBoxEx functions and the CB_DIR message are similar to the DlgDirList and DlgDirSelectEx functions and the LB_DIR message used with list boxes.


Data Associated with List Items

An application can associate data with the list items in a combo box. The CB_SETITEMDATA message associates a DWORD value with a list item, and the CB_GETITEMDATA retrieves the value associated with a list item.

The example in Creating an Owner-Drawn Combo Box uses item data to associate a constant with each item in a drop-down list box. Such a unique value identifies each item independent of its sorted position.

Other applications might use item data to associate a handle or pointer with a list item. If so, an application can process a WM_DELETEITEM message to delete or free the specified object when the list item is deleted.


The Extended User Interface

Drop-down combo boxes and drop-down list boxes support an alternative keyboard interface called the extended user interface. By default, the f4 key opens or closes the list, and the down arrow changes the current selection. In a combo box with the extended user interface, however, the f4 key is disabled and pressing the down arrow key opens the drop-down list.

To select the user interface for a combo box, an application can send the CB_SETEXTENDEDUI message to the combo box. A TRUE value for the wParam parameter enables the extended user interface; a FALSE value sets the default user interface. To determine whether a combo box uses the extended user interface, an application can send the CB_GETEXTENDEDUI message to the combo box.


Combo Box Notifications

Messages from combo boxes are sent as notifications in the form of WM_COMMAND messages. The notification message is stored in the high word of the wParam parameter, and an application can process the following combo box notification messages.

Notification message | Description
CBN_CLOSEUP | Indicates the list in a drop-down combo box or drop-down list box is about to close.
CBN_DBLCLK | Indicates the user has double-clicked a list item in a simple combo box.
CBN_DROPDOWN | Indicates the list in a drop-down combo box or drop-down list box is about to open.
CBN_EDITCHANGE | Indicates the user has changed the text in the edit control of a simple or drop-down combo box. This notification message is sent after the altered text is displayed.
CBN_EDITUPDATE | Indicates the user has changed the text in the edit control of a simple or drop-down combo box. This notification message is sent before the altered text is displayed.
CBN_ERRSPACE | Indicates the combo box cannot allocate enough memory to carry out a request, such as adding a list item.
CBN_KILLFOCUS | Indicates the combo box is about to lose the input focus.
CBN_SELCHANGE | Indicates the current selection has changed.
CBN_SELENDCANCEL | Indicates that the selection made in the drop down list, while it was dropped down, should be ignored.
CBN_SELENDOK | Indicates that the selection made drop down list, while it was dropped down, should be accepted.
CBN_SETFOCUS | Indicates the combo box has received the input focus.


Default Combo Box Behavior

This section contains a table that describes the messages specifically handled by the predefined COMBOBOX class window procedure.

Message | Description
CB_ADDSTRING | Sends an LB_ADDSTRING message to the list window to add a list item.
CB_DELETESTRING | Sends an LB_DELETESTRING message to the list window to delete a list item.
CB_DIR | Adds the filenames matching the specified attributes and path to the list.
CB_FINDSTRING | Sends an LB_FINDSTRING message to the list window. This message returns the index of the first list item that begins with the specified text.
CB_FINDSTRINGEXACT | Sends an LB_FINDSTRING message to the list window. This message returns the index of the first list item exactly matching the specified text.
CB_GETCOUNT | Sends an LB_GETCOUNT message to the list window. It returns the number of list items.
CB_GETCURSEL | Sends an LB_GETCURSEL message to the list window. It returns the index of the currently selected item, if any.
CB_GETDROPPEDCONTROLRECT | Fills the specified rectangle structure with the screen coordinates of a drop-down list.
CB_GETDROPPEDSTATE | Returns TRUE if a drop-down list is open; otherwise, it returns FALSE.
CB_GETDROPPEDWIDTH | Returns the minimum allowable width, in pixels, of the drop down list.
CB_GETEDITSEL | Sends an EM_GETSEL message to the edit control, and it returns the starting and ending position of the current selection. In drop-down list boxes, the window procedure returns CB_ERR.
CB_GETEXTENDEDUI | Returns TRUE if the combo box is a drop-down combo box or drop-down list box and the extend user-interface flag is set; otherwise, it returns FALSE.
CB_GETHORIZONTALEXTENT | Sends an LB_GETHORIZONTALEXTENT message to the list window. It returns the scrollable width, in pixels, of the drop down list.
CB_GETITEMDATA | Sends an LB_GETITEMDATA message to the list window. It returns the 32-bit value associated with the specified list item.
CB_GETITEMHEIGHT | Sends an LB_GETITEMHEIGHT message to the list window. It returns the height, in pixels, of the specified owner-drawn list item.
CB_GETLBTEXT | Sends an LB_GETTEXT message to the list window. It copies the specified list text to the specified buffer.
CB_GETLBTEXTLEN | Sends an LB_GETTEXTLEN message to the list window. It returns the length, in bytes, of the specified list text.
CB_GETLOCALE | Sends an LB_GETLOCALE message to the list window. It returns the current locale for the list.
CB_GETTOPINDEX | Sends an LB_GETTOPINDEX message to the list window. It returns the index of the first visible item in the drop down list.
CB_INITSTORAGE | Sends an LB_INITSTORAGE message to the list window. It initializes space for the specified number of items and the specified number of bytes for item strings.
CB_INSERTSTRING | Sends an LB_INSERTSTRING message to the list window. It inserts a list item at the specified position.
CB_LIMITTEXT | Sends an EM_LIMITTEXT message to the edit control. It sets the maximum number of characters a user can enter in the edit control. In drop-down list boxes, the window procedure returns CB_ERR.
CB_RESETCONTENT | Sends an LB_RESETCONTENT message to the list window, and it removes the contents of the list.
CB_SELECTSTRING | Sends an LB_SELECTSTRING message to the list window. It selects the first list item, if any, that begins with the characters in the specified text.
CB_SETCURSEL | Sends an LB_SETCURSEL message to the list window, and it sets the current selection.
CB_SETDROPPEDWIDTH | Sets the minimum allowable width, in pixels, of the drop down list.
CB_SETEDITSEL | Sends an EM_SETSEL message to the edit control. It selects the specified range of text. In drop-down list boxes, the window procedure returns CB_ERR.
CB_SETEXTENDEDUI | Sets or clears the extended user-interface flag. This flag changes the keys that open and close the list in a drop-down combo box or drop-down list box. If the combo box is a simple combo box, the window procedure returns CB_ERR.
CB_SETHORIZONTALEXTENT | Sends an LB_SETHORIZONTALEXTENT message to the list window. It sets the scrollable width, in pixels, of the drop down list.
CB_SETITEMDATA | Sends an LB_SETITEMDATA message to the list window. It associates the specified 32-bit value with a list item.
CB_SETITEMHEIGHT | Sends an LB_SETITEMHEIGHT message to the list window. It sets the height of the specified owner-drawn list item or the selection field.
CB_SETLOCALE | Sends an LB_SETLOCALE message to the list window, and it sets the current locale for the list. The locale affects how the list is sorted if it has the CBS_SORT style and strings are added using CB_ADDSTRING.
CB_SETTOPINDEX | Sends an LB_SETTOPINDEX message to the list window. It scrolls the drop down list so the specified item is at the top of the visible range.
CB_SHOWDROPDOWN | Shows or hides the drop-down list. This message has no effect on simple combo boxes.
WM_CHAR | Processes character input. In drop-down list boxes, this message is passed to the list window, which moves the selection to the first item beginning with the specified character. In simple and drop-down combo boxes, this message is passed to the edit control.
WM_CLEAR | Deletes the edit selection. In simple and drop-down combo boxes, the edit control processes this message. In drop-down list boxes, the window procedure returns CB_ERR.
WM_COMMAND | Processes notification messages from the edit control and list window and sends corresponding combo box notification messages to the parent window.
For edit control notifications, the window procedure may update the list window's current selection, caret index, and top index. For list notification messages, the window procedure may update the content of the selection field.
WM_COMPAREITEM | Passes the message to the parent window, enabling the application to specify the relative sort position of two owner-drawn list items. The combo box window receives this message from the list window.
WM_COPY | Copies the edit selection to the clipboard. In simple and drop-down combo boxes, the edit control processes this message. In drop-down list boxes, the window procedure returns CB_ERR.
WM_CREATE | Initializes the combo box.
WM_CUT | Deletes the edit selection and places it on the clipboard. In simple and drop-down combo boxes, the edit control processes this message. In drop-down list boxes, the window procedure returns CB_ERR.
WM_DELETEITEM | Passes the message to the parent window, notifying the application that a list item has been deleted. The combo box window receives this message from the list window.
WM_DRAWITEM | Passes the message on to the parent window enabling the application to paint the specified list item. The combo box window receives this message from the list window. The window procedure can also originate this message to have the application paint the selection field of a drop-down list box.
WM_ENABLE | Sets the state to enable or prohibit mouse and keyboard input.
WM_ERASEBKGND | Returns 1, indicating that the background is erased.
WM_GETDLGCODE | Returns a combination of the DLG_WANTCHARS and DLGC_WANTARROWS values.
WM_GETFONT | Returns the handle to the current font with which the combo box will draw its text.
WM_GETTEXT | Copies the contents of the selection field to the specified buffer. In simple and drop-down combo boxes, the edit control processes this message.
WM_GETTEXTLENGTH | Returns the length, in characters, of the text in the selection field. In simple and drop-down combo boxes, the edit control processes this message.
WM_KEYDOWN | Processes noncharacter keyboard input. In drop-down list boxes, this message is sent to the list window, which may show or hide itself, or change its current selection or caret index. In simple and drop-down combo boxes, this message is passed to the edit control. The edit control passes certain keys to the list window, such as the up and down arrow keys and the f4 key.
WM_KILLFOCUS | Hides the highlight in the selection field and closes the drop-down list, if necessary. If the window receiving the input focus is part of the combo box (for example, the edit control), this message is ignored.
WM_LBUTTONDBLCLK | Same as WM_LBUTTONDOWN.
WM_LBUTTONDOWN | Sets the focus to the combo box and, for drop-down combo boxes and drop-down lists, can open or close the list. If it opens the list, the window procedure captures the mouse to enable selection by dragging and releasing the mouse button.
WM_LBUTTONUP | Releases the mouse capture if the mouse opened the list.
WM_MEASUREITEM | Posts the message to the parent window, enabling the application to modify the contents of the specified MEASUREITEMSTRUCT structure. The combo box window receives this message from the list window.
WM_MOUSEMOVE | Posts the message to the list window if the mouse has opened the list and the mouse button is still down. This enables a user to select an item by dragging the mouse pointer to a list item and then releasing the button.
WM_NCCREATE | Allocates an internal data structure used by the combo box window procedure.
WM_NCDESTROY | Frees resources allocated in response to the WM_NCCREATE message.
WM_PAINT | Paints the invalid region of the combo box. If wParam is not NULL, it is assumed to be a DC handle passed from a subclass function. The window procedure uses the specified DC instead of calling BeginPaint and EndPaint.
WM_PASTE | Replaces the edit selection with the contents of the clipboard. In simple and drop-down combo boxes, the edit control processes this message. In drop-down list boxes, the window procedure returns CB_ERR.
WM_SETFOCUS | Sets the focus to the edit control or, in drop-down list boxes, inverts the selection field and turns on the caret in the list window.
WM_SETFONT | Saves the specified font handle in an internal structure, adjusts the dimensions of the selection field and list, and invalidates the combo box window. Text in the selection field and the list is displayed in the saved font.
WM_SETREDRAW | Sets or clears the redraw flag. If the redraw flag is cleared, the combo box is not repainted until the flag is set again.
WM_SETTEXT | Sets the contents of the edit control. In simple and drop-down combo boxes, the edit control processes this message. In drop-down list boxes, the window procedure returns CB_ERR.
WM_SIZE | Resizes the child windows, if necessary.
WM_SYSKEYDOWN | Opens or closes the drop-down list depending on which arrow key the user pressed.

All other messages are passed to the DefWindowProc function for default processing.


Using Combo Boxes

  • Creating a simple combo box
  • Creating an owner-drawn combo box
  • Subclassing a combo box


Creating a Simple Combo Box

This section describes how to use a simple combo box in a dialog box. The example in Creating a Spell Dialog Box uses a simple combo box in a dialog box for a spelling checker. When it finds a misspelled word, the spelling checker suggests alternative spellings. The user can ignore the misspelling, change to one of the suggested spellings, or type a spelling not suggested. A simple combo box is well suited for receiving this kind of user input.


Creating the Simple Dialog Box

The dialog box template defines the window styles and control identifier for the combo box. In this example, the combo box uses the CBS_SIMPLE, CBS_SORT, WS_VSCROLL, and WS_TABSTOP styles.

The dialog box also contains three buttons: Change (IDOK), Ignore (IDSKIP), and Cancel (IDCANCEL). The IDOK and IDCANCEL constants are defined by the SDK header files. The IDSKIP constant is defined in the application's header file, as is the control identifier for the combo box, IDCOMBO.

For more information about dialog boxes, see Dialog Boxes.


Processing the WM_INITDIALOG and WM_DESTROY Messages in a Simple Dialog Box

When you use a combo box in a dialog box, you usually respond to the WM_INITDIALOG message by initializing the combo box. The code example in Creating a Spell Dialog Box calls the application-defined OpenDictionary function to load the dictionary. It then calls the application-defined SelectNextWord and InitSpellList functions to select the first misspelled word.

SelectNextWord selects the next word in the edit control and copies it to the specified buffer. InitSpellList determines whether the selected word is in the dictionary. If not, it places the word in the selection field of the combo box and adds suggested spellings to the list.

The dialog box procedure processes the WM_DESTROY message to free the resources allocated to the spelling dictionary.


Processing the WM_COMMAND Message in a Simple Dialog Box

When an event occurs in a dialog box control, the control sends a WM_COMMAND message to the dialog box procedure. The high-order word of the wParam parameter is a notification code, indicating the type of event that occurred. The low-order word of wParam is a constant identifying the control. The lParam parameter is the window handle for the control.

When processing the WM_COMMAND message, the spelling checker example examines the control identifier in the low-order word of wParam to determine the origin of the message. The constants IDCOMBO, IDOK, IDIGNORE, and IDCANCEL identify the combo box, the Change button, the Ignore button, and the Cancel button controls, respectively.

A combo box may send a WM_COMMAND message for a number of different reasons. To determine the type of event, the dialog box procedure examines the notification code in the high-order word of wParam. The example processes only the CBN_DBLCLK notification message, which is sent when the user double-clicks a list item. The dialog box procedure processes this notification message in the same way as a Change button click.

The buttons in this example send WM_COMMAND messages only when they are chosen by the user. When the user chooses the Change button, the dialog box procedure replaces the current selection in the application's edit control with the content of the selection field in the combo box. The selection field may contain either the selected list item or text the user has typed. The dialog box procedure then selects the next misspelled word in the same way it processes an Ignore button click.

When the user clicks the Ignore button, the dialog box procedure calls the application-defined SelectNextWord and InitSpellList functions to select the next misspelled word in the application's edit control. InitSpellList places the misspelled word in the selection field of the combo box and adds suggested spellings to the combo box list.

When the user clicks the Cancel button, the dialog box procedure calls the EndDialog function to close the dialog box.


Creating a Spell Dialog Box

Following are the dialog box procedure and supporting functions for the spelling checker dialog box.

HWND hwndMain;
HWND hwndEdit;
char achTemp[256];       // temporary buffer

LPSTR lpstrDict;         // buffer for dictionary file
LPSTR *paLpDict;         // array of pointers to words
UINT  cWords;            // number of words

/********************************************************

    FUNCTION:   SpellDlgProc

    PURPOSE:    Dialog procedure for Spell dialog box.

*********************************************************/

BOOL CALLBACK SpellDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg)
    {
        case WM_INITDIALOG:
            if (!OpenDictionary())
            {
                EndDialog(hwndDlg, 0);
                break;
            }
            SendMessage(hwndEdit, EM_SETSEL, 0, 0);
            do
                if (!SelectNextWord(hwndEdit, achTemp))
                {
                    GlobalFree((HGLOBAL) lpstrDict);
                    LocalFree((HLOCAL) paLpDict);
                    EndDialog(hwndDlg, 0);
                    break;
                }
            while (!InitSpellList(
                GetDlgItem(hwndDlg, IDCOMBO), achTemp));
            break;

        case WM_COMMAND:
            switch (LOWORD(wParam)) {
                case IDCOMBO:
                    if (HIWORD(wParam) != CBN_DBLCLK)
                        break;

                    // For a double-click, process the OK case.

                case IDOK:
                    SendDlgItemMessage(hwndDlg, IDCOMBO,
                        WM_GETTEXT, sizeof(achTemp),
                        (LPARAM) achTemp);
                    SendMessage(hwndEdit, EM_REPLACESEL, 0,
                        (LPARAM) achTemp);

                    // Fall through to get the next word.

                case IDIGNORE:
                    do
                        if (!SelectNextWord(hwndEdit, achTemp))
                        {
                            EndDialog(hwndDlg, 0);
                            break;
                        }
                    while (!InitSpellList(GetDlgItem(hwndDlg,
                        IDCOMBO), achTemp));
                    break;

                case IDCANCEL:
                    EndDialog(hwndDlg, 0);
            }
            break;

        case WM_DESTROY:
            GlobalFree((HGLOBAL) lpstrDict);
            LocalFree((HLOCAL) paLpDict);
            break;

        default:
            return FALSE;
    }
    return TRUE;
}

/********************************************************

    FUNCTION:   InitSpellList

    PURPOSE:    Initializes the selection field and list
                of suggestions for the specified word, if
                it is not in the dictionary.

    RETURNS:    If the list is initialized, the return
                value is TRUE. If an error occurs or the
                word is in the dictionary, the return
                value is FALSE.

*********************************************************/

BOOL PASCAL InitSpellList(HWND hwndCombo, LPSTR lpszWord)
{
    int min = 0;        // beginning of search range
    int max = cWords;   // end of search range
    int n;              // index of word
    int cmp;            // result of comparison
    char ch;            // first character in word

    ch = *lpszWord;
    CharLowerBuff(&ch, 1);

    // Perform a binary search for the word.
    //
    // The global array paLpDict contains pointers to words
    // in the global array lpstrDict. These two variables are
    // initialized by the OpenDictionary function.

    n = max / 2;
    while (min < max)
    {
        cmp = lstrcmpi(lpszWord, paLpDict[n]);
        if (cmp == 0)
            return FALSE;       /* not misspelled */

        if (cmp < 0)
            max = n;
        else
            min = n + 1;
        n = (min + max) / 2;
    }

    // List words beginning with the same letter as lpszWord.

    SendMessage(hwndCombo, CB_RESETCONTENT, 0, 0);
    while (n > 0 && *paLpDict[n - 1] == ch)
        n--;
    while (*paLpDict[n] == ch)
        SendMessage(hwndCombo, CB_ADDSTRING,
            0, (LPARAM) paLpDict[n++]);

    // Place the word in the selection field.

    SendMessage(hwndCombo, WM_SETTEXT, 0, (LPARAM) lpszWord);

    return TRUE;
}


Creating an Owner-Drawn Combo Box

This section describes how to use an owner-drawn combo box. The example in Creating a Square Meal Dialog Box uses an owner-drawn drop-down list box to display the four food groups, each represented by a bitmap and a name. Selecting a food group causes the foods in that group to appear in a list.


Creating the Owner-Drawn Dialog Box

The dialog box template defines the window styles, buttons, and control identifiers for the combo box. The combo box in this example uses the CBS_DROPDOWNLIST, CBS_OWNERDRAWFIXED, CBS_SORT, CBS_HASSTRINGS, WS_VSCROLL, and WS_TABSTOP styles.

The dialog box also contains a list box (IDLIST) and two buttons: OK (IDOK) and Cancel (IDCANCEL). The IDOK and IDCANCEL constants are defined by the SDK header files. The constant IDLIST is defined in the application's header file, as is the control identifier, IDCOMBO.

For more information about dialog boxes, see Dialog Boxes.


Processing the WM_INITDIALOG and WM_DESTROY Messages in an Owner-Drawn Dialog Box

When you use a combo box in a dialog box, you usually respond to a WM_INITDIALOG message by initializing the combo box. The example in Creating a Square Meal Dialog Box loads the bitmaps used for the owner-drawn combo box, then calls the application-defined InitGroupList function to initialize the combo box. It also selects the first list item in the combo box, then calls the application-defined InitFoodList function to initialize the list box.

In the example, the owner-drawn combo box is a drop-down list box containing the names of each of the four food groups. InitGroupList adds the name of each food group, and calls the application-defined SetItemData function to associate a constant with each list item that identifies a corresponding food group.

The list box in the example contains the names of foods in the selected food group. InitFoodList resets the contents of the list box, then adds the names of the current food selection in the current food group drop-down list box.

The dialog box procedure processes the WM_DESTROY message to delete the bitmaps in the owner-drawn combo box.


Processing the WM_MEASUREITEM Message

An owner-drawn combo box sends the WM_MEASUREITEM message to its parent window or dialog box procedure so the application can set the dimensions of each list item. Because the example combo box has the CBS_OWNERDRAWFIXED style, the system sends the WM_MEASUREITEM message only once. Combo boxes with the CBS_OWNERDRAWVARIABLE style send a WM_MEASUREITEM message for each list item.

The lParam parameter points to a MEASUREITEMSTRUCT structure that identifies the control and list item. It also contains the default dimensions of the list item. The example in Creating a Square Meal Dialog Box modifies the itemHeight structure member to ensure that the list items are high enough to accommodate the food-group bitmaps.


Processing the WM_DRAWITEM Message

An owner-drawn combo box sends the WM_DRAWITEM message to its parent window or dialog box procedure each time the application must repaint a list item. The lParam parameter points to a DRAWITEMSTRUCT structure that identifies the control and list item. It also contains information needed to paint the item.

The example in Creating a Square Meal Dialog Box displays the list-item text and the bitmap associated with the food group. If the item has the focus, it also draws a focus rectangle. Before displaying the text, the example sets the foreground and background colors, based on the item selected. Because the combo box has the CBS_HASSTRINGS style, the combo box maintains the text for each list item that can be retrieved using the CB_GETLBTEXT message.

The bitmaps used for the list item depend on the food group. InitGroupList uses the CB_SETITEMDATA message to associate a constant with each list item, identifying the corresponding food group. The window procedure uses this value, contained in the itemData member of the DRAWITEMSTRUCT structure, to determine which bitmaps to display. The system uses two bitmaps for each food group symbol: a monochrome bitmap with the SRCAND raster operation to erase the irregular region behind the image, and a color bitmap with the SRCPAINT raster operation to paint the image.


Processing the WM_COMMAND Message in an Owner-Drawn Dialog Box

When an event occurs in a dialog box control, the control notifies the dialog box procedure by means of a WM_COMMAND message. The example in Creating a Square Meal Dialog Box processes notification messages from the combo box, the list box, and the OK button. The control identifier is in the low-order word of wParam, and the notification message is in the high-order word of wParam.

If the control identifier is IDCOMBO, an event has occurred in the combo box. In response, the dialog box procedure ignores all other combo box events except CBN_SELENDOK, which indicates that a selection was made, the drop down was closed up, and the changes made should be accepted. The dialog box procedure calls InitFoodList to reset the contents of the list box and to add the names of the current selection in the drop-down list box.

If the control identifier is IDLIST, an event has occurred in the list box. This causes the dialog box procedure to ignore all list box events except LBN_DBLCLK, which indicates that the user has double-clicked a list item. This event is processed in the same way as if an OK button has been chosen.

If the control identifier is IDOK, the user has chosen the OK button. In response, the dialog box procedure inserts the name of the selected food into the application's multi-line edit control, then calls the EndDialog function to close the dialog box.

If the control identifier is IDCANCEL, the user has clicked the Cancel button. In response, the dialog box procedure calls EndDialog to close the dialog box.


Creating a Square Meal Dialog Box

Following are the dialog box procedure and supporting functions for the Square Meal dialog box.

HWND hwndMain;
HWND hwndEdit;
char achTemp[256];       // temporary buffer

HBITMAP hbmBread;
HBITMAP hbmDairy;
HBITMAP hbmFruit;
HBITMAP hbmMeat;
HBITMAP hbmBreadMask;
HBITMAP hbmDairyMask;
HBITMAP hbmFruitMask;
HBITMAP hbmMeatMask;

/********************************************************

    FUNCTION:   FoodDlgProc

    PURPOSE:    Dialog procedure for Food dialog box.

*********************************************************/

BOOL CALLBACK FoodDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
    LPMEASUREITEMSTRUCT lpmis;
    LPDRAWITEMSTRUCT lpdis;
    HBITMAP hbmIcon;
    HBITMAP hbmMask;
    COLORREF clrBackground;
    COLORREF clrForeground;
    TEXTMETRIC tm;
    HDC hdc;
    HWND hwnd;
    int x;
    int y;

    switch (msg)
    {
        case WM_INITDIALOG:

            // Call an application-defined function to load
            // bitmap resources.

            if (!LoadIconBitmaps())
            {
                EndDialog(hwndDlg, -1);
                break;
            }

            // Initialize the drop-down list box.

            if (!InitGroupList(hwndDlg))
            {
                DeleteIconBitmaps();
                EndDialog(hwndDlg, -1);
                break;
            }

            // Select the first food group.

            SendDlgItemMessage(hwndDlg, IDCOMBO, CB_SETCURSEL,
                0, 0);

            // List the foods and select the first food.

            InitFoodList(hwndDlg);
            SendDlgItemMessage(hwndDlg, IDLIST, LB_SETCURSEL,
                0, 0);
            break;

        case WM_MEASUREITEM:
            lpmis = (LPMEASUREITEMSTRUCT) lParam;

            if (lpmis->itemHeight < CY_BITMAP + 2)
                lpmis->itemHeight = CY_BITMAP + 2;

            break;

        case WM_DRAWITEM:
            lpdis = (LPDRAWITEMSTRUCT) lParam;
            if (lpdis->itemID == -1)            // empty item
                break;

            // Determine the bitmaps used to draw the icon.

            switch (lpdis->itemData)
            {
                case ID_BREAD:
                    hbmIcon = hbmBread;
                    hbmMask = hbmBreadMask;
                    break;

                case ID_DAIRY:
                    hbmIcon = hbmDairy;
                    hbmMask = hbmDairyMask;
                    break;

                case ID_FRUIT:
                    hbmIcon = hbmFruit;
                    hbmMask = hbmFruitMask;
                    break;

                default:                /* meat */
                    hbmIcon = hbmMeat;
                    hbmMask = hbmMeatMask;
                    break;
            }

            // The colors depend on whether the item is selected.

            clrForeground = SetTextColor(lpdis->hDC,
                GetSysColor(lpdis->itemState & ODS_SELECTED ?
                COLOR_HIGHLIGHTTEXT : COLOR_WINDOWTEXT));

            clrBackground = SetBkColor(lpdis->hDC,
                GetSysColor(lpdis->itemState & ODS_SELECTED ?
                COLOR_HIGHLIGHT : COLOR_WINDOW));

            // Calculate the vertical and horizontal position.

            GetTextMetrics(lpdis->hDC, &tm);
            y = (lpdis->rcItem.bottom + lpdis->rcItem.top -
                tm.tmHeight) / 2;
            x = LOWORD(GetDialogBaseUnits()) / 4;

            // Get and display the text for the list item.

            SendMessage(lpdis->hwndItem, CB_GETLBTEXT,
                lpdis->itemID, (LPARAM) (LPCSTR) achTemp);

            ExtTextOut(lpdis->hDC, CX_BITMAP + 2 * x, y,
                ETO_CLIPPED | ETO_OPAQUE, &lpdis->rcItem,
                achTemp, lstrlen(achTemp), NULL);

            // Restore the previous colors.

            SetTextColor(lpdis->hDC, clrForeground);
            SetBkColor(lpdis->hDC, clrBackground);

            // Show the icon.

            hdc = CreateCompatibleDC(lpdis->hDC);
            if (hdc == NULL)
                break;

            SelectObject(hdc, hbmMask);
            BitBlt(lpdis->hDC, x, lpdis->rcItem.top + 1,
                CX_BITMAP, CY_BITMAP, hdc, 0, 0, SRCAND);

            SelectObject(hdc, hbmIcon);
            BitBlt(lpdis->hDC, x, lpdis->rcItem.top + 1,
                CX_BITMAP, CY_BITMAP, hdc, 0, 0, SRCPAINT);

            DeleteDC(hdc);

            // If the item has the focus, draw focus rectangle.

            if (lpdis->itemState & ODS_FOCUS)
                DrawFocusRect(lpdis->hDC, &lpdis->rcItem);

            break;

        case WM_COMMAND:
            switch (LOWORD(wParam))
            {
                case IDCOMBO:
                    if (HIWORD(wParam) == CBN_SELENDOK)
                    {
                        InitFoodList(hwndDlg);
                        SendDlgItemMessage(hwndDlg, IDLIST,
                            LB_SETCURSEL, 0, 0);
                    }
                    break;

                case IDLIST:
                    if (HIWORD(wParam) != LBN_DBLCLK)
                        break;

                    // For a double-click, process the OK case.

                case IDOK:

                    // Get the text for the selected list item.

                    hwnd = GetDlgItem(hwndDlg, IDLIST);
                    SendMessage(hwnd, LB_GETTEXT,
                        SendMessage(hwnd, LB_GETCURSEL, 0, 0),
                        (LPARAM) achTemp);

                    // Insert the text into the edit window.

                    SendMessage(hwndEdit, EM_REPLACESEL, 0,
                        (LPARAM) achTemp);

                    EndDialog(hwndDlg, 0);
                    break;

                case IDCANCEL:
                    hwnd = GetDlgItem(hwndDlg, IDCOMBO);
                    if (SendMessage(hwnd, CB_GETDROPPEDSTATE, 0, 0))
                        SendMessage(hwnd, CB_SHOWDROPDOWN, FALSE, 0);
                    else EndDialog(hwndDlg, 0);
            }
            break;

        case WM_DESTROY:

            // Call the application-defined function to free the
            // bitmap resources.

            DeleteIconBitmaps();
            break;

        default:
            return FALSE;
    }
    return TRUE;
}

/********************************************************

    FUNCTION:   InitGroupList

    PURPOSE:    Initializes the "food groups" drop-down
                list box.

    COMMENTS:   The ID of the food group associated with
                each list item is saved as item data.

*********************************************************/

BOOL PASCAL InitGroupList(HWND hwndDlg)
{
    HWND hwndCombo = GetDlgItem(hwndDlg, IDCOMBO);
    DWORD dwIndex;

    // Add an item for each food group.

    LoadString(hinst, ID_BREAD, achTemp, sizeof(achTemp));
    dwIndex = SendMessage(hwndCombo, CB_ADDSTRING, 0,
        (LPARAM) (LPCSTR) achTemp);
    SendMessage(hwndCombo, CB_SETITEMDATA, dwIndex, ID_BREAD);

    LoadString(hinst, ID_DAIRY, achTemp, sizeof(achTemp));
    dwIndex = SendMessage(hwndCombo, CB_ADDSTRING, 0,
        (LPARAM) (LPCSTR) achTemp);
    SendMessage(hwndCombo, CB_SETITEMDATA, dwIndex, ID_DAIRY);

    LoadString(hinst, ID_FRUIT, achTemp, sizeof(achTemp));
    dwIndex = SendMessage(hwndCombo, CB_ADDSTRING, 0,
        (LPARAM) (LPCSTR) achTemp);
    SendMessage(hwndCombo, CB_SETITEMDATA, dwIndex, ID_FRUIT);

    LoadString(hinst, ID_MEAT, achTemp, sizeof(achTemp));
    dwIndex = SendMessage(hwndCombo, CB_ADDSTRING, 0,
        (LPARAM) (LPCSTR) achTemp);
    SendMessage(hwndCombo, CB_SETITEMDATA, dwIndex, ID_MEAT);

    return TRUE;
}

/********************************************************

    FUNCTION:   InitFoodList

    PURPOSE:    Clears the contents of the food list, and
                adds the names of foods for the current
                food group.

*********************************************************/

void PASCAL InitFoodList(HWND hwndDlg)
{
    HWND hwndCombo = GetDlgItem(hwndDlg, IDCOMBO);
    HWND hwndList = GetDlgItem(hwndDlg, IDLIST);
    UINT idFoodGroup;
    LPSTR lpsz;
    LPSTR lpszEnd;

    // Determine the current food group.

    idFoodGroup = SendMessage(
        hwndCombo,
        CB_GETITEMDATA,
        SendMessage(hwndCombo, CB_GETCURSEL, 0, 0),
        0
    );

    // Clear the list contents.

    SendMessage(hwndList, LB_RESETCONTENT, 0, 0);

   // .
   // . Add food names for the current food group.
   // .

}


Subclassing a Combo Box

This section demonstrates how to subclass combo boxes so your application can use them outside a dialog box. The example in Creating a Combo-box Toolbar shows the window procedure for a toolbar window containing two combo boxes. By subclassing the edit controls within the combo boxes, the toolbar window intercepts tab, enter, and esc keys that would otherwise be ignored.

The following illustration shows the toolbar window.


Processing the WM_CREATE Message

The example in Creating a Combo-box Toolbar processes the WM_CREATE message to create two combo box controls as child windows. It then subclasses the edit controls (selection fields) in each combo box because they receive the character input for simple and drop-down combo box. The application gets the handle to each edit control by using the ChildWindowFromPoint function.

To subclass the edit controls, the application calls the SetWindowLong function, replacing the address of the class window procedure with the address of the application-defined SubClassProc function. The address of the original window procedure is saved in the global variable lpfnEditWndProc.

SubClassProc intercepts tab, esc, and enter keys and notifies the toolbar window by sending application-defined messages (WM_TAB, WM_ESC, and WM_ENTER). SubClassProc uses the CallWindowProc function to pass most messages to the original window procedure, lpfnEditWndProc.


Processing the WM_SETFOCUS Message

When the toolbar window receives the input focus, it immediately sets the focus to the first combo box in the toolbar. To do so, the example in Creating a Combo-box Toolbar calls the SetFocus function in response to the WM_SETFOCUS message.


Processing the Application-Defined Messages

In the example in Creating a Combo-box Toolbar SubClassProc sends application-defined messages to the toolbar window when the user presses the tab, esc, or enter key in a combo box. The WM_TAB message is sent for the tab key, the WM_ESC message for the esc key, and the WM_ENTER message for the enter key.

The example processes the WM_TAB message by setting the focus to the next combo box in the toolbar. It processes the WM_ESC message by setting the focus to the main application window.

In response to the WM_ENTER message, the example ensures that the current selection for the combo box is valid and then sets the focus to the main application window. If the combo box contains no current selection, the example uses the CB_FINDSTRINGEXACT message to search for a list item that matches the contents of the selection field. If there is a match, the example sets the current selection; otherwise, it adds a new list item.


Creating a Combo-box Toolbar

Following are the window procedure for the toolbar and the subclass procedure for the two combo boxes.

#define WM_TAB (WM_USER)
#define WM_ESC (WM_USER + 1)
#define WM_ENTER (WM_USER + 2)

// Global variables

HWND    hwndMain;
WNDPROC lpfnEditWndProc; // original wndproc for the combo box

// Prototypes

LRESULT CALLBACK SubClassProc( HWND, UINT, WPARAM, LPARAM );

/********************************************************

    FUNCTION:   ToolbarWindowProc

    PURPOSE:    Window procedure for the toolbar window

*********************************************************/

LRESULT CALLBACK ToolbarWindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    static HWND   hwndEdit1;
    static HWND   hwndEdit2;
    static HWND   hwndCombo1;
    static HWND   hwndCombo2;

    POINT       pt;
    DWORD       dwBaseUnits;
    HWND        hwndCombo;
    DWORD       dwIndex;

    char achTemp[256];       // temporary buffer

    switch (msg)
    {
        case WM_CREATE:

            // Create two combo box child windows.

            dwBaseUnits = GetDialogBaseUnits();

            hwndCombo1 = CreateWindow("COMBOBOX", "",
                CBS_DROPDOWN | WS_CHILD | WS_VISIBLE,
                (6 * LOWORD(dwBaseUnits)) / 4,
                (2 * HIWORD(dwBaseUnits)) / 8,
                (100 * LOWORD(dwBaseUnits)) / 4,
                (50 * HIWORD(dwBaseUnits)) / 8,
                hwnd, NULL, hinst, NULL);

            hwndCombo2 = CreateWindow("COMBOBOX", "",
                CBS_DROPDOWN | WS_CHILD | WS_VISIBLE,
                (112 * LOWORD(dwBaseUnits)) / 4,
                (2 * HIWORD(dwBaseUnits)) / 8,
                (100 * LOWORD(dwBaseUnits)) / 4,
                (50 * HIWORD(dwBaseUnits)) / 8,
                hwnd, NULL, hinst, NULL);

            // Get the edit window handle for each combo box.

            pt.x = 1;
            pt.y = 1;
            hwndEdit1 = ChildWindowFromPoint(hwndCombo1, pt);
            hwndEdit2 = ChildWindowFromPoint(hwndCombo2, pt);

            // Change the window procedure for both edit windows
            // to the subclass procedure.

            lpfnEditWndProc = (WNDPROC) SetWindowLong(hwndEdit1,
                GWL_WNDPROC, (DWORD) SubClassProc);

            SetWindowLong(hwndEdit2, GWL_WNDPROC,
                (DWORD) SubClassProc);

            break;

        case WM_SETFOCUS:
            SetFocus(hwndCombo1);
            break;

        case WM_TAB:
            if (GetFocus() == hwndEdit1)
                SetFocus(hwndCombo2);
            else
                SetFocus(hwndCombo1);
            break;

        case WM_ESC:

            hwndCombo = GetFocus() == hwndEdit1 ?
                hwndCombo1 : hwndCombo2;

            // Clear the current selection.

            SendMessage(hwndCombo, CB_SETCURSEL,
                (WPARAM) (-1), 0);

            // Set the focus to the main window.

            SetFocus(hwndMain);
            break;

        case WM_ENTER:
            hwndCombo = GetFocus() == hwndEdit1 ?
                hwndCombo1 : hwndCombo2;
            SetFocus(hwndMain);

            // If there is no current selection, set one.

            if (SendMessage(hwndCombo, CB_GETCURSEL, 0, 0)
                    == CB_ERR)
            {
                if (SendMessage(hwndCombo, WM_GETTEXT,
                        sizeof(achTemp), (LPARAM) achTemp) == 0)
                    break;      // empty selection field
                dwIndex = SendMessage(hwndCombo,
                    CB_FINDSTRINGEXACT, (WPARAM) (-1),
                    (LPARAM) achTemp);

                // Add the string, if necessary, and select it.

                if (dwIndex == CB_ERR)
                    dwIndex = SendMessage(hwndCombo, CB_ADDSTRING,
                        0, (LPARAM) achTemp);
                if (dwIndex != CB_ERR)
                    SendMessage(hwndCombo, CB_SETCURSEL,
                        dwIndex, 0);
            }
            break;

            // .
            // .  Process additional messages.
            // .

        default:
            return DefWindowProc(hwnd, msg, wParam, lParam);
    }
    return 0;
}

/********************************************************

    FUNCTION:   SubClassProc

    PURPOSE:    Process TAB and ESCAPE keys, and pass all
                other messages to the class window
                procedure.

*********************************************************/

LRESULT CALLBACK SubClassProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg)
    {
        case WM_KEYDOWN:
            switch (wParam)
            {
                case VK_TAB:
                    SendMessage(hwndMain, WM_TAB, 0, 0);
                    return 0;
                case VK_ESCAPE:
                    SendMessage(hwndMain, WM_ESC, 0, 0);
                    return 0;
                case VK_RETURN:
                    SendMessage(hwndMain, WM_ENTER, 0, 0);
                    return 0;
            }
            break;

        case WM_KEYUP:
        case WM_CHAR:
            switch (wParam)
            {
                case VK_TAB:
                case VK_ESCAPE:
                case VK_RETURN:
                    return 0;
            }
    }

    // Call the original window procedure for default processing.

    return CallWindowProc(lpfnEditWndProc, hwnd,
        msg, wParam, lParam);
}


Combo Box Reference

The following elements are used with combo boxes.

  • Combo Box Functions
  • Combo Box Structures
  • Combo Box Messages
  • Combo Box Styles


Combo Box Functions

The following functions are used with combo boxes.

DlgDirListComboBox
DlgDirSelectEx
DlgDirSelectComboBoxEx


DlgDirListComboBox

The DlgDirListComboBox function fills the specified combo box with a directory listing. It fills the list with the names of all files, drives, and subdirectories that match the specified attributes and path string.

int DlgDirListComboBox(
  HWND hDlg,          // handle to dialog box with combo box
  LPTSTR lpPathSpec,  // pointer to path or filename string
  int nIDComboBox,    // identifier of combo box
  int nIDStaticPath,  // identifier of static control
  UINT uFiletype      // file attributes to display
);

Parameters

hDlg
Handle to the dialog box that contains the combo box.
lpPathSpec
Pointer to a null-terminated string of the following form:

[drive:][\]][directory\[...]][filename]

If the specified string includes a drive or directory path, the DlgDirListComboBox function changes the current drive and directory before filling the list. After the list is filled, the drive and directory path are removed from the string specified by the lpPathSpec parameter.

nIDComboBox
Specifies the identifier of a combo box control in a dialog box. If nIDComboBox is zero, the DlgDirListComboBox function assumes no combo box exists and does not attempt to fill it.
nIDStaticPath
Specifies the identifier of the static text control in which the DlgDirListComboBox function is to display the current directory. If nIDStaticPath is zero, DlgDirListComboBox assumes no such control is present.
uFiletype
Specifies the attributes of the files to be displayed. It can be any combination of the following values:
Value | Meaning
DDL_ARCHIVE | Includes archived files.
DDL_DIRECTORY | Includes subdirectories. Subdirectory names are enclosed in square brackets ([ ]).
DDL_DRIVES | Includes drives. Drives are listed in the form [-x-], where x is the drive letter.
DDL_EXCLUSIVE | Includes only files with the specified attributes. By default, read-write files are listed even if DDL_READWRITE is not specified.
DDL_HIDDEN | Includes hidden files.
DDL_READONLY | Includes read-only files.
DDL_READWRITE | Includes read-write files with no additional attributes.
DDL_SYSTEM | Includes system files.
DDL_POSTMSGS | Posts messages to the application's message queue. By default, the DlgDirList function sends messages directly to the dialog box procedure.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. For example, if the string specified by lpPathSpec is not a valid path, the function fails. To get extended error information, call GetLastError.

Remarks

If the lpszPathSpec parameter points to a zero-length string or to a string specifying a drive, directory, or both — but no filename — the filename *.* (wildcards) is assumed.

Windows NT:
The directory listing displays long filenames, if any.
Windows 95:
The directory listing displays short filenames (the 8.3 form). You can use the SHGetFileInfo or GetFullPathName functions to get the corresponding long filename.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Combo Boxes Overview, Combo Box Functions, DlgDirList, DlgDirSelectComboBoxEx, GetFullPathName, SHGetFileInfo


DlgDirSelectComboBoxEx

The DlgDirSelectComboBoxEx function retrieves the current selection from a combo box filled by using the DlgDirListComboBox function. The selection is interpreted as a drive letter, a file, or a directory name.

BOOL DlgDirSelectComboBoxEx(
  HWND hDlg,        // handle to dialog box with list box
  LPTSTR lpString,  // pointer to buffer for path string
  int nCount,       // number of characters in path string
  int nIDComboBox   // identifier of combo box
);

Parameters

hDlg
Handle to the dialog box that contains the combo box.
lpString
Pointer to the buffer that is to receive the selected path.
nCount
Specifies the length, in characters, of the buffer pointed to by the lpString parameter.
nIDComboBox
Specifies the integer identifier of the combo box control in the dialog box.

Return Values

If the current selection is a directory name, the return value is nonzero.

If the current selection is not a directory name, the return value is zero. To get extended error information, call GetLastError.

Remarks

If the current selection specifies a directory name or drive letter, the DlgDirSelectComboBoxEx function removes the enclosing square brackets (and hyphens for drive letters) so the name or letter is ready to be inserted into a new path or filename. If there is no selection, the contents of the buffer pointed to by lpString do not change.

The DlgDirSelectComboBox function does not allow more than one filename to be returned from a combo box.

DlgDirSelectComboBoxEx sends CB_GETCURSEL and CB_GETLBTEXT messages to the combo box.

In the Win32 API, you can use this function with all three types of combo boxes (CBS_SIMPLE, CBS_DROPDOWN, and CBS_DROPDOWNLIST).

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Combo Boxes Overview, Combo Box Functions, CB_GETCURSEL, CB_GETLBTEXT, DlgDirListComboBox, DlgDirSelectEx


DlgDirSelectEx

The DlgDirSelectEx function retrieves the current selection from a single-selection list box. It assumes that the list box has been filled by the DlgDirList function and that the selection is a drive letter, filename, or directory name.

BOOL DlgDirSelectEx(
  HWND hDlg,       // handle to dialog box with list box
  LPTSTR lpString, // pointer to buffer for path string
  int nCount,      // number of characters in path string
  int nIDListBox   // identifier of list box
);

Parameters

hDlg
Handle to the dialog box that contains the list box.
lpString
Pointer to a buffer that is to receive the selected path.
nCount
Specifies the length, in characters, of the buffer pointed to by lpString.
nIDListBox
Specifies the integer identifier of a list box in the dialog box.

Return Values

If the current selection is a directory name, the return value is nonzero.

If the current selection is not a directory name, the return value is zero. To get extended error information, call GetLastError.

Remarks

The DlgDirSelectEx function copies the selection to the buffer pointed to by the lpString parameter. If the current selection is a directory name or drive letter, DlgDirSelectEx removes the enclosing square brackets (and hyphens, for drive letters), so that the name or letter is ready to be inserted into a new path. If there is no selection, lpString does not change.

DlgDirSelectEx sends LB_GETCURSEL and LB_GETTEXT messages to the list box. The function does not allow more than one filename to be returned from a list box. The list box must not be a multiple-selection list box. If it is, this function does not return a zero value and lpString remains unchanged.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Combo Boxes Overview, Combo Box Functions, DlgDirList, DlgDirListComboBox, DlgDirSelectComboBoxEx, LB_GETCURSEL, LB_GETTEXT


Combo Box Structures

The following structures are used with combo boxes.

COMPAREITEMSTRUCT
DRAWITEMSTRUCT
MEASUREITEMSTRUCT


COMPAREITEMSTRUCT

The COMPAREITEMSTRUCT structure supplies the identifiers and application-supplied data for two items in a sorted, owner-drawn list box or combo box.

Whenever an application adds a new item to an owner-drawn list box or combo box created with the CBS_SORT or LBS_SORT style, the system sends the owner a WM_COMPAREITEM message. The lParam parameter of the message contains a long pointer to a COMPAREITEMSTRUCT structure. Upon receiving the message, the owner compares the two items and returns a value indicating which item sorts before the other.

typedef struct tagCOMPAREITEMSTRUCT { // cis
    UINT  CtlType;
    UINT  CtlID;
    HWND  hwndItem;
    UINT  itemID1;
    DWORD itemData1;
    UINT  itemID2;
    DWORD itemData2;
} COMPAREITEMSTRUCT;

Members

CtlType
Specifies ODT_LISTBOX (an owner-drawn list box) or ODT_COMBOBOX (an owner-drawn combo box).
CtlID
Specifies the identifier of the list box or combo box.
hwndItem
Handle to the control.
itemID1
Specifies the index of the first item in the list box or combo box being compared.

This member will be –1 if the item has not been inserted or when searching for a potential item in the list box or combo box.

itemData1
Specifies application-supplied data for the first item being compared. (This value was passed as the lParam parameter of the message that added the item to the list box or combo box.)
itemID2
Specifies the index of the second item in the list box or combo box being compared.
itemData2
Specifies application-supplied data for the second item being compared. This value was passed as the lParam parameter of the message that added the item to the list box or combo box.

This member will be –1 if the item has not been inserted or when searching for a potential item in the list box or combo box.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Structures, WM_COMPAREITEM


DRAWITEMSTRUCT

The DRAWITEMSTRUCT structure provides information the owner window must have to determine how to paint an owner-drawn control or menu item. The owner window of the owner-drawn control or menu item receives a pointer to this structure as the lParam parameter of the WM_DRAWITEM message.

typedef struct tagDRAWITEMSTRUCT {  // dis
    UINT  CtlType;
    UINT  CtlID;
    UINT  itemID;
    UINT  itemAction;
    UINT  itemState;
    HWND  hwndItem;
    HDC   hDC;
    RECT  rcItem;
    DWORD itemData;
} DRAWITEMSTRUCT;

Members

CtlType
Specifies the control type. This member can be one of the following values:
Value | Meaning
ODT_BUTTON | Owner-drawn button
ODT_COMBOBOX | Owner-drawn combo box
ODT_LISTBOX | Owner-drawn list box
ODT_LISTVIEW | List view control
ODT_MENU | Owner-drawn menu item
ODT_STATIC | Owner-drawn static control
ODT_TAB | Tab control

CtlID
Specifies the identifier of the combo box, list box, button, or static control. This member is not used for a menu item.
itemID
Specifies the menu item identifier for a menu item or the index of the item in a list box or combo box. For an empty list box or combo box, this member can be –1. This allows the application to draw only the focus rectangle at the coordinates specified by the rcItem member even though there are no items in the control. This indicates to the user whether the list box or combo box has the focus. How the bits are set in the itemAction member determines whether the rectangle is to be drawn as though the list box or combo box has the focus.
itemAction
Specifies the drawing action required. This member can be one or more of the following values:
Value | Meaning
ODA_DRAWENTIRE | The entire control needs to be drawn.
ODA_FOCUS | The control has lost or gained the keyboard focus. The itemState member should be checked to determine whether the control has the focus.
ODA_SELECT | The selection status has changed. The itemState member should be checked to determine the new selection state.

itemState
Specifies the visual state of the item after the current drawing action takes place. This member can be a combination of the following values:
Value | Meaning
ODS_CHECKED | The menu item is to be checked. This bit is used only in a menu.
ODS_COMBOBOXEDIT | The drawing takes place in the selection field (edit control) of an owner-drawn combo box.
ODS_DEFAULT | The item is the default item.
ODS_DISABLED | The item is to be drawn as disabled.
ODS_FOCUS | The item has the keyboard focus.
ODS_GRAYED | The item is to be grayed. This bit is used only in a menu.
ODS_SELECTED | The menu item's status is selected.

hwndItem
Handle to the control for combo boxes, list boxes, buttons, and static controls. For menus, this member identifies the menu containing the item.
hDC
Handle to a device context; this device context must be used when performing drawing operations on the control.
rcItem
Specifies a rectangle that defines the boundaries of the control to be drawn. This rectangle is in the device context specified by the hDC member. The system automatically clips anything the owner window draws in the device context for combo boxes, list boxes, and buttons, but does not clip menu items. When drawing menu items, the owner window must not draw outside the boundaries of the rectangle defined by the rcItem member.
itemData
Specifies the application-defined 32-bit value associated with the menu item. For a control, this parameter specifies the value last assigned to the list box or combo box by the LB_SETITEMDATA or CB_SETITEMDATA message. If the list box or combo box has the LBS_HASSTRINGS or CBS_HASSTRINGS style, this value is initially zero. Otherwise, this value is initially the value that was passed to the list box or combo box in the lParam parameter of one of the following messages:
  • CB_ADDSTRING
  • CB_INSERTSTRING
  • LB_ADDSTRING
  • LB_INSERTSTRING

If ctlType is ODT_BUTTON or ODT_STATIC, itemData is zero.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Structures, CB_ADDSTRING, CB_INSERTSTRING, CB_SETITEMDATA, LB_ADDSTRING, LB_INSERTSTRING, LB_SETITEMDATA, WM_DRAWITEM


MEASUREITEMSTRUCT

The MEASUREITEMSTRUCT structure informs the system of the dimensions of an owner-drawn control or menu item. This allows the system to process user interaction with the control correctly.

typedef struct tagMEASUREITEMSTRUCT {   // mis
    UINT  CtlType;      // type of control
    UINT  CtlID;        // combo box, list box, or button identifier
    UINT  itemID;       // menu item, variable-height list box,
                        // or combo box identifier
    UINT  itemWidth;    // width of menu item, in pixels
    UINT  itemHeight;   // height of single item in list box menu,
                        // in pixels
    DWORD itemData;     // application-defined 32-bit value
} MEASUREITEMSTRUCT;

Members

CtlType
Specifies the control type. This member can be one of the following values:
Value | Meaning
ODT_BUTTON | Owner-drawn button
ODT_COMBOBOX | Owner-drawn combo box
ODT_LISTBOX | Owner-drawn list box
ODT_LISTVIEW | Owner-draw list view control
ODT_MENU | Owner-drawn menu

CtlID
Specifies the identifier of the combo box, list box, or button. This member is not used for a menu.
itemID
Specifies the identifier for a menu item or the position of a list box or combo box item. This value is specified for a list box only if it has the LBS_OWNERDRAWVARIABLE style; this value is specified for a combo box only if it has the CBS_OWNERDRAWVARIABLE style.
itemWidth
Specifies the width, in pixels, of a menu item. Before returning from the message, the owner of the owner-drawn menu item must fill this member.
itemHeight
Specifies the height, in pixels, of an individual item in a list box or a menu. Before returning from the message, the owner of the owner-drawn combo box, list box, or menu item must fill out this member.
itemData
Specifies the application-defined 32-bit value associated with the menu item. For a control, this member specifies the value last assigned to the list box or combo box by the LB_SETITEMDATA or CB_SETITEMDATA message. If the list box or combo box has the LB_HASSTRINGS or CB_HASSTRINGS style, this value is initially zero. Otherwise, this value is initially the value passed to the list box or combo box in the lParam parameter of one of the following messages:
  • CB_ADDSTRING
  • CB_INSERTSTRING
  • LB_ADDSTRING
  • LB_INSERTSTRING

Remarks

The owner window of an owner-drawn control receives a pointer to the MEASUREITEMSTRUCT structure as the lParam parameter of a WM_MEASUREITEM message. The owner-drawn control sends this message to its owner window when the control is created. The owner then fills in the appropriate members in the structure for the control and returns. This structure is common to all owner-drawn controls.

If an application does not fill the appropriate members of MEASUREITEMSTRUCT, the control or menu item may not be drawn properly.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Structures, CB_ADDSTRING, CB_INSERTSTRING, CB_SETITEMDATA, LB_ADDSTRING, LB_INSERTSTRING, LB_SETITEMDATA, WM_MEASUREITEM


Combo Box Messages

The following messages are used with combo boxes.

CB_ADDSTRING
CB_DELETESTRING
CB_DIR
CB_FINDSTRING
CB_FINDSTRINGEXACT
CB_GETCOUNT
CB_GETCURSEL
CB_GETDROPPEDCONTROLRECT
CB_GETDROPPEDSTATE
CB_GETDROPPEDWIDTH
CB_GETEDITSEL
CB_GETEXTENDEDUI
CB_GETHORIZONTALEXTENT
CB_GETITEMDATA
CB_GETITEMHEIGHT
CB_GETLBTEXT
CB_GETLBTEXTLEN
CB_GETLOCALE
CB_GETTOPINDEX
CB_INITSTORAGE
CB_INSERTSTRING
CB_LIMITTEXT
CB_RESETCONTENT
CB_SELECTSTRING
CB_SETCURSEL
CB_SETDROPPEDWIDTH
CB_SETEDITSEL
CB_SETEXTENDEDUI
CB_SETHORIZONTALEXTENT
CB_SETITEMDATA
CB_SETITEMHEIGHT
CB_SETLOCALE
CB_SETTOPINDEX
CB_SHOWDROPDOWN
CBN_CLOSEUP
CBN_DBLCLK
CBN_DROPDOWN
CBN_EDITCHANGE
CBN_EDITUPDATE
CBN_ERRSPACE
CBN_KILLFOCUS
CBN_SELCHANGE
CBN_SELENDCANCEL
CBN_SELENDOK
CBN_SETFOCUS
WM_COMPAREITEM
WM_DRAWITEM
WM_MEASUREITEM


CB_ADDSTRING

An application sends a CB_ADDSTRING message to add a string to the list box of a combo box. If the combo box does not have the CBS_SORT style, the string is added to the end of the list. Otherwise, the string is inserted into the list, and the list is sorted.

CB_ADDSTRING
wParam = 0;                         // not used; must be zero
lParam = (LPARAM) (LPCTSTR) lpsz;    // address of string to add

Parameters

lpsz
Value of lParam. Pointer to the null-terminated string to be added. If you create the combo box with an owner-drawn style but without the CBS_HASSTRINGS style, the value of the lpsz parameter is stored as item data rather than the string it would otherwise point to. The item data can be retrieved or modified by sending the CB_GETITEMDATA or CB_SETITEMDATA message.

Return Values

The return value is the zero-based index to the string in the list box of the combo box. If an error occurs, the return value is CB_ERR. If insufficient space is available to store the new string, it is CB_ERRSPACE.

Remarks

If you create an owner-drawn combo box with the CBS_SORT style but without the CBS_HASSTRINGS style, the WM_COMPAREITEM message is sent one or more times to the owner of the combo box so the new item can be properly placed in the list.

To insert a string at a specific location within the list, use the CB_INSERTSTRING message.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_DIR, CB_INSERTSTRING, WM_COMPAREITEM


CB_DELETESTRING

An application sends a CB_DELETESTRING message to delete a string in the list box of a combo box.

CB_DELETESTRING
wParam = (WPARAM) index;  // item to delete
lParam = 0;               // not used; must be zero

Parameters

index
Value of wParam. Specifies the zero-based index of the string to delete.

Return Values

The return value is a count of the strings remaining in the list. If the index parameter specifies an index greater than the number of items in the list, the return value is CB_ERR.

Remarks

If you create the combo box with an owner-drawn style but without the CBS_HASSTRINGS style, the system sends a WM_DELETEITEM message to the owner of the combo box so the application can free any additional data associated with the item.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_RESETCONTENT, WM_DELETEITEM


CB_DIR

An application sends a CB_DIR message to add a list of filenames to the list box of a combo box.

CB_DIR
wParam = (WPARAM) (UINT) uAttrs;          // file attributes
lParam = (LPARAM) (LPCTSTR) lpszFileSpec; // address of filename

Parameters

uAttrs
Value of wParam. Specifies the attributes of the files to be added to the list box. It can be any combination of the following values:
Value | Meaning
DDL_ARCHIVE | Includes archived files.
DDL_DIRECTORY | Includes subdirectories. Subdirectory names are enclosed in square brackets ([ ]).
DDL_DRIVES | Includes drives. Drives are listed in the form [-x-], where x is the drive letter.
DDL_EXCLUSIVE | Includes only files with the specified attributes. By default, read-write files are listed even if DDL_READWRITE is not specified.
DDL_HIDDEN | Includes hidden files.
DDL_READONLY | Includes read-only files.
DDL_READWRITE | Includes read-write files with no additional attributes.
DDL_SYSTEM | Includes system files.

lpszFileSpec
Value of lParam. Pointer to the null-terminated string that specifies the filename to add to the list. If the filename contains any wildcards (for example, *.*), all files that match and have the attributes specified by the uAttrs parameter are added to the list.

Return Values

The return value is the zero-based index of the last filename added to the list. If an error occurs, the return value is CB_ERR. If insufficient space is available to store the new strings, it is CB_ERRSPACE.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_ADDSTRING, CB_INSERTSTRING, DlgDirList, DlgDirListComboBox


CB_FINDSTRING

An application sends a CB_FINDSTRING message to search the list box of a combo box for an item beginning with the characters in a specified string.

CB_FINDSTRING
wParam = (WPARAM) indexStart;        // item before start of search
lParam = (LPARAM) (LPCSTR) lpszFind  // prefix string address

Parameters

indexStart
Value of wParam. Specifies the zero-based index of the item preceding the first item to be searched. When the search reaches the bottom of the list box, it continues from the top of the list box back to the item specified by the indexStart parameter. If indexStart is –1, the entire list box is searched from the beginning.
lpszFind
Value of lParam. Pointer to the null-terminated string that contains the prefix to search for. The search is not case sensitive, so this string can contain any combination of uppercase and lowercase letters.

Return Values

The return value is the zero-based index of the matching item. If the search is unsuccessful, it is CB_ERR.

Remarks

If you create the combo box with an owner-drawn style but without the CBS_HASSTRINGS style, what the CB_FINDSTRING message does depends on whether your application uses the CBS_SORT style. If you use the CBS_SORT style, WM_COMPAREITEM messages are sent to the owner of the combo box to determine which item matches the specified string. If you do not use the CBS_SORT style, the CB_FINDSTRING message searches for a list item that matches the value of the lpszFind parameter.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_FINDSTRINGEXACT, CB_SELECTSTRING, CB_SETCURSEL, WM_COMPAREITEM


CB_FINDSTRINGEXACT

An application sends a CB_FINDSTRINGEXACT message to find the first list box string in a combo box that matches the string specified in the lpszFind parameter.

CB_FINDSTRINGEXACT
wParam = (WPARAM) indexStart;      // item before start of search
lParam = (LPARAM)(LPCSTR)lpszFind; // address of string to search for

Parameters

indexStart
Value of wParam. Specifies the zero-based index of the item preceding the first item to be searched. When the search reaches the bottom of the list box, it continues from the top of the list box back to the item specified by the indexStart parameter. If indexStart is –1, the entire list box is searched from the beginning.
lpszFind
Value of lParam. Pointer to the null-terminated string to search for. This string can contain a complete filename, including the extension. The search is not case sensitive, so this string can contain any combination of uppercase and lowercase letters.

Return Values

The return value is the zero-based index of the matching item. If the search is unsuccessful, it is CB_ERR.

Remarks

If you create the combo box with an owner-drawn style but without the CBS_HASSTRINGS style, what the CB_FINDSTRINGEXACT message does depends on whether your application uses the CBS_SORT style. If you use the CBS_SORT style, WM_COMPAREITEM messages are sent to the owner of the combo box to determine which item matches the specified string. If you do not use the CBS_SORT style, the CB_FINDSTRINGEXACT message searches for a list item that matches the value of the lpszFind parameter.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_FINDSTRING, CB_SELECTSTRING, WM_COMPAREITEM


CB_GETCOUNT

An application sends a CB_GETCOUNT message to retrieve the number of items in the list box of a combo box.

CB_GETCOUNT
wParam = 0;     // not used; must be zero
lParam = 0;     // not used; must be zero

Parameters

This message has no parameters.

Return Values

The return value is the number of items in the list box. If an error occurs, it is CB_ERR.

Remarks

The index is zero-based, so the returned count is one greater than the index value of the last item.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages


CB_GETCURSEL

An application sends a CB_GETCURSEL message to retrieve the index of the currently selected item, if any, in the list box of a combo box.

CB_GETCURSEL
wParam = 0;     // not used; must be zero
lParam = 0;     // not used; must be zero

Parameters

This message has no parameters.

Return Values

The return value is the zero-based index of the currently selected item. If no item is selected, it is CB_ERR.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_SELECTSTRING, CB_SETCURSEL


CB_GETDROPPEDCONTROLRECT

An application sends a CB_GETDROPPEDCONTROLRECT message to retrieve the screen coordinates of the drop-down list box of a combo box.

CB_GETDROPPEDCONTROLRECT
wParam = 0;                         // not used; must be zero
lParam = (LPARAM) (RECT FAR*) lprc; // address of RECT structure

Parameters

lprc
Value of lParam. Pointer to the RECT structure that is to receive the coordinates.

Return Values

If the message succeeds, the return value is nonzero.

If the message fails, the return value is zero.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, RECT


CB_GETDROPPEDSTATE

An application sends a CB_GETDROPPEDSTATE message to determine whether the list box of a combo box is dropped down.

CB_GETDROPPEDSTATE
wParam = 0;     // not used; must be zero
lParam = 0;     // not used; must be zero

Parameters

This message has no parameters.

Return Values

If the list box is visible, the return value is TRUE; otherwise, it is FALSE.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_SHOWDROPDOWN


CB_GETDROPPEDWIDTH

An application sends the CB_GETDROPPEDWIDTH message to retrieve the minimum allowable width, in pixels, of the list box of a combo box with the CBS_DROPDOWN or CBS_DROPDOWNLIST style.

CB_GETDROPPEDWIDTH
wParam = 0;     // not used, must be zero
lParam = 0;     // not used, must be zero

Parameters

This message has no parameters.

Return Values

If the message succeeds, the return value is the width, in pixels.

If the message fails, the return value is CB_ERR.

Remarks

By default, the minimum allowable width of the drop-down list box is 0. The width of the list box is either the minimum allowable width or the combo box width, whichever is larger.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_SETDROPPEDWIDTH


CB_GETEDITSEL

An application sends a CB_GETEDITSEL message to get the starting and ending character positions of the current selection in the edit control of a combo box.

CB_GETEDITSEL
wParam = (WPARAM) (LPDWORD) lpdwStart; // receives starting position
lParam = (LPARAM) (LPDWORD) lpdwEnd;   // receives ending position

Parameters

lpdwStart
Value of wParam. Pointer to a 32-bit value that receives the starting position of the selection. This parameter can be set to NULL.
lpdwEnd
Value of lParam. Pointer to a 32-bit value that receives the ending position of the selection. This parameter can be set to NULL.

Return Values

The return value is a zero-based 32-bit value with the starting position of the selection in the low-order word and with the ending position of the first character after the last selected character in the high-order word.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_SETEDITSEL


CB_GETEXTENDEDUI

An application sends a CB_GETEXTENDEDUI message to determine whether a combo box has the default user interface or the extended user interface.

CB_GETEXTENDEDUI
wParam = 0;     // not used; must be zero
lParam = 0;     // not used; must be zero

Parameters

This message has no parameters.

Return Values

If the combo box has the extended user interface, the return value is TRUE; otherwise, it is FALSE.

Remarks

By default, the f4 key opens or closes the list and the down arrow changes the current selection. In a combo box with the extended user interface, the f4 key is disabled and pressing the down arrow key opens the drop-down list.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_SETEXTENDEDUI


CB_GETHORIZONTALEXTENT

An application sends the CB_GETHORIZONTALEXTENT message to retrieve from a combo box the width, in pixels, by which the list box can be scrolled horizontally (the scrollable width). This is applicable only if the list box has a horizontal scroll bar.

CB_GETHORIZONTALEXTENT
wParam = 0;     // not used, must be zero
lParam = 0;     // not used, must be zero

Parameters

This message has no parameters.

Return Values

The return value is the scrollable width, in pixels.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_SETHORIZONTALEXTENT


CB_GETITEMDATA

An application sends a CB_GETITEMDATA message to a combo box to retrieve the application-supplied 32-bit value associated with the specified item in the combo box.

CB_GETITEMDATA
wParam = (WPARAM) index;  // item index
lParam = 0;               // not used; must be zero

Parameters

index
Value of wParam. Specifies the zero-based index of the item.

Return Values

The return value is the 32-bit value associated with the item. If an error occurs, it is CB_ERR.

If the item is in an owner-drawn combo box created without the CBS_HASSTRINGS style, the return value is the 32-bit value contained in the lParam parameter of the CB_ADDSTRING or CB_INSERTSTRING message that added the item to the combo box. If the CBS_HASSTRINGS style was not used, the return value is the lParam parameter contained in a CB_SETITEMDATA message.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_ADDSTRING, CB_INSERTSTRING, CB_SETITEMDATA


CB_GETITEMHEIGHT

An application sends a CB_GETITEMHEIGHT message to determine the height of list items or the selection field in a combo box.

CB_GETITEMHEIGHT
wParam = (WPARAM) index;  // item index
lParam = 0;               // not used; must be zero

Parameters

index
Value of wParam. Specifies the combo box component whose height is to be retrieved.

This parameter must be –1 to retrieve the height of the selection field. It must be zero to retrieve the height of list items, unless the combo box has the CBS_OWNERDRAWVARIABLE style. In that case, the index parameter is the zero-based index of a specific list item.

Return Values

The return value is the height, in pixels, of the list items in a combo box. If the combo box has the CBS_OWNERDRAWVARIABLE style, it is is the height of the item specified by the index parameter. If index is –1, the return value is the height of the edit control (or static-text) portion of the combo box. If an error occurs, the return value is CB_ERR.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_SETITEMHEIGHT, WM_MEASUREITEM


CB_GETLBTEXT

An application sends a CB_GETLBTEXT message to retrieve a string from the list of a combo box.

CB_GETLBTEXT
wParam = (WPARAM) index;                // item index
lParam = (LPARAM) (LPCSTR) lpszBuffer;  // address of buffer

Parameters

index
Value of wParam. Specifies the zero-based index of the string to retrieve.
lpszBuffer
Value of lParam. Pointer to the buffer that receives the string. The buffer must have sufficient space for the string and a terminating null character. You can send a CB_GETLBTEXTLEN message prior to the CB_GETLBTEXT message to retrieve the length, in bytes, of the string.

Return Values

The return value is the length of the string, in bytes, excluding the terminating null character. If the index parameter does not specify a valid index, the return value is CB_ERR.

Remarks

If you create the combo box with an owner-drawn style but without the CBS_HASSTRINGS style, the buffer pointed to by the lpszBuffer parameter of the message receives the 32-bit value associated with the item (the item data).

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_GETLBTEXTLEN


CB_GETLBTEXTLEN

An application sends a CB_GETLBTEXTLEN message to retrieve the length, in characters, of a string in the list of a combo box.

CB_GETLBTEXTLEN
wParam = (WPARAM) index;  // item index
lParam = 0;               // not used; must be zero

Parameters

index
Value of wParam. Specifies the zero-based index of the string.

Return Values

The return value is the length of the string, in characters, excluding the terminating null character. Under certain conditions, this value may actually be greater than the length of the text. For more information, see the following Remarks section.

If the index parameter does not specify a valid index, the return value is CB_ERR.

Remarks

Under certain conditions, the return value is larger than the actual length of the text. This occurs with certain mixtures of ANSI and Unicode, and is due to the operating system allowing for the possible existence of double-byte character set (DBCS) characters within the text. The return value, however, will always be at least as large as the actual length of the text; so you can always use it to guide buffer allocation. This behavior can occur when an application uses both ANSI functions and common dialogs, which use Unicode.

To obtain the exact length of the text, use the WM_GETTEXT, LB_GETTEXT, or CB_GETLBTEXT messages, or the GetWindowText function.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_GETLBTEXT, GetWindowText, LB_GETTEXT, WM_GETTEXT


CB_GETLOCALE

An application sends a CB_GETLOCALE message to retrieve the current locale of the combo box. The locale is used to determine the correct sorting order of displayed text for combo boxes with the CBS_SORT style and text added by using the CB_ADDSTRING message.

CB_GETLOCALE
wParam = 0; // not used; must be zero
lParam = 0; // not used; must be zero

Parameters

This message has no parameters.

Return Values

The return value is a 32-bit value that specifies the current locale of the combo box. The high word contains the country code and the low-order word contains the language identifier.

Remarks

The language identifier is made up of a sublanguage identifier and a primary language identifier. The PRIMARYLANGID macro obtains the primary language identifier and the SUBLANGID macro obtains the sublanguage identifier.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_ADDSTRING, CB_SETLOCALE, PRIMARYLANGID, SUBLANGID


CB_GETTOPINDEX

An application sends the CB_GETTOPINDEX message to retrieve the zero-based index of the first visible item in the list box portion of a combo box. Initially the item with index 0 is at the top of the list box, but if the list box contents have been scrolled, another item may be at the top.

CB_GETTOPINDEX
wParam = 0;     // not used, must be zero
lParam = 0;     // not used, must be zero

Parameters

This message has no parameters.

Return Values

If the message is successful, the return value is the index of the first visible item in the list box of the combo box.

If the message fails, the return value is CB_ERR.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_SETTOPINDEX


CB_INITSTORAGE

[This is preliminary documentation and subject to change.]

An application sends the CB_INITSTORAGE message before adding a large number of items to the list box portion of a combo box. This message allocates memory for storing list box items.

CB_INITSTORAGE
wParam = (WPARAM) (int) cItems;  // number of items to add
lParam = (LPARAM) (DWORD) cb;    // amount of memory to allocate, in bytes

Parameters

cItems
Specifies the number of items to add.
cb
Specifies the amount of memory to allocate for item strings, in bytes.

Return Values

If the message is successful, the return value is the total number of items for which memory has been pre-allocated, that is, the total number of items added by all successful CB_INITSTORAGE messages.

If the message fails, the return value is CB_ERRSPACE.

Windows NT: For Windows NT version 4.0, this message does not allocate the specified amount of memory; however, it always returns the value specified in the cItems parameter. For Windows NT version 5.0, the message allocates memory and returns the success and error values described above.

Remarks

The CB_INITSTORAGE message helps speed up the initialization of combo boxes that have a large number of items (over 100). It reserves the specified amount of memory so that subsequent CB_ADDSTRING, CB_INSERTSTRING, and CB_DIR messages take the shortest possible time. You can use estimates for the cItems and cb parameters. If you overestimate, the extra memory is allocated, if you underestimate, the normal allocation is used for items that exceed the requested amount.

QuickInfo

Windows NT: Requires version 5.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_ADDSTRING, CB_DIR, CB_INSERTSTRING


CB_INSERTSTRING

An application sends a CB_INSERTSTRING message to insert a string into the list box of a combo box. Unlike the CB_ADDSTRING message, the CB_INSERTSTRING message does not cause a list with the CBS_SORT style to be sorted.

CB_INSERTSTRING
wParam = (WPARAM) index;          // item index
lParam = (LPARAM) (LPCTSTR) lpsz; // address of string to insert

Parameters

index
Value of wParam. Specifies the zero-based index of the position at which to insert the string. If this parameter is –1, the string is added to the end of the list.
lpsz
Value of lParam. Pointer to the null-terminated string to be inserted. If you create the combo box with an owner-drawn style but without the CBS_HASSTRINGS style, the value of the lpsz parameter is stored rather than the string it would otherwise point to.

Return Values

The return value is the index of the position at which the string was inserted. If an error occurs, the return value is CB_ERR. If there is insufficient space available to store the new string, it is CB_ERRSPACE.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_ADDSTRING, CB_DIR


CB_LIMITTEXT

An application sends a CB_LIMITTEXT message to limit the length of the text the user may type into the edit control of a combo box.

CB_LIMITTEXT
wParam = (WPARAM) cchLimit;   // maximum number of characters
lParam = 0;                   // not used; must be zero

Parameters

cchLimit
Value of wParam. Specifies the maximum number of characters the user can enter. If this parameter is zero, the text length is set to 0x7FFFFFFE characters.

Return Values

The return value is always TRUE.

Remarks

If the combo box does not have the CBS_AUTOHSCROLL style, setting the text limit to be larger than the size of the edit control has no effect.

The CB_LIMITTEXT message limits only the text the user can enter. It has no effect on any text already in the edit control when the message is sent, nor does it affect the length of the text copied to the edit control when a string in the list box is selected.

The default limit to the text a user can enter in the edit control is 30,000 characters.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages


CB_RESETCONTENT

An application sends a CB_RESETCONTENT message to remove all items from the list box and edit control of a combo box.

CB_RESETCONTENT
wParam = 0;     // not used; must be zero
lParam = 0;     // not used; must be zero

Parameters

This message has no parameters.

Return Values

This message always returns CB_OKAY.

Remarks

If you create the combo box with an owner-drawn style but without the CBS_HASSTRINGS style, the owner of the combo box receives a WM_DELETEITEM message for each item in the combo box.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_DELETESTRING, WM_DELETEITEM


CB_SELECTSTRING

An application sends a CB_SELECTSTRING message to search the list of a combo box for an item that begins with the characters in a specified string. If a matching item is found, it is selected and copied to the edit control.

CB_SELECTSTRING
wParam = (WPARAM) indexStart;          // item before first selection
lParam = (LPARAM) (LPCSTR) lpszSelect; // address of prefix string

Parameters

indexStart
Value of wParam. Specifies the zero-based index of the item preceding the first item to be searched. When the search reaches the bottom of the list, it continues from the top of the list back to the item specified by the indexStart parameter. If indexStart is –1, the entire list is searched from the beginning.
lpszSelect
Value of lParam. Pointer to the null-terminated string that contains the prefix to search for. The search is not case sensitive, so this string can contain any combination of uppercase and lowercase letters.

Return Values

If the string is found, the return value is the index of the selected item. If the search is unsuccessful, the return value is CB_ERR and the current selection is not changed.

Remarks

A string is selected only if the characters from the starting point match the characters in the prefix string.

If you create the combo box with an owner-drawn style but without the CBS_HASSTRINGS style, what the CB_SELECTSTRING message does depends on whether you use the CBS_SORT style. If the CBS_SORT style is used, the system sends WM_COMPAREITEM messages to the owner of the combo box to determine which item matches the specified string. If you do not use the CBS_SORT style, CB_SELECTSTRING attempts to match the DWORD value against the value of the lpszSelect parameter.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_FINDSTRING, CB_FINDSTRINGEXACT, CB_SETCURSEL, WM_COMPAREITEM


CB_SETCURSEL

An application sends a CB_SETCURSEL message to select a string in the list of a combo box. If necessary, the list scrolls the string into view. The text in the edit control of the combo box changes to reflect the new selection, and any previous selection in the list is removed.

CB_SETCURSEL
wParam = (WPARAM) index;  // item index
lParam = 0;               // not used; must be zero

Parameters

index
Value of wParam. Specifies the zero-based index of the string to select. If the index parameter is –1, any current selection in the list is removed and the edit control is cleared.

Return Values

If the message is successful, the return value is the index of the item selected. If index is greater than the number of items in the list or if index is set to –1, the return value is CB_ERR and the selection is cleared.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_FINDSTRING, CB_GETCURSEL, CB_SELECTSTRING


CB_SETDROPPEDWIDTH

An application sends the CB_SETDROPPEDWIDTH message to set the maximum allowable width, in pixels, of the list box of a combo box with the CBS_DROPDOWN or CBS_DROPDOWNLIST style.

CB_SETDROPPEDWIDTH
wParam = (WPARAM) wWidth,     // width of list box, in pixels
lParam = 0,                   // not used, must be zero

Parameters

wWidth
Specifies the width of the list box, in pixels.

Return Values

If the message is successful, The return value is the new width of the list box.

If the message fails, the return value is CB_ERR.

Remarks

By default, the minimum allowable width of the drop-zdown list box is 0. The width of the list box is either the minimum allowable width or the combo box width, whichever is larger.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_GETDROPPEDWIDTH


CB_SETEDITSEL

An application sends a CB_SETEDITSEL message to select characters in the edit control of a combo box.

CB_SETEDITSEL
wParam = 0;                                // not used; must be zero
lParam = MAKELPARAM((ichStart), (ichEnd);  // start and end position

Parameters

ichStart
Value of the low-order word of lParam; this specifies the starting position. If this parameter is set to –1, the selection, if any, is removed.
ichEnd
Value of the high-order word of lParam; this specifies the ending position. If this parameter is set to –1, all text from the starting position to the last character in the edit control is selected.

Return Values

If the message succeeds, the return value is TRUE. If the message is sent to a combo box with the CBS_DROPDOWNLIST style, it is CB_ERR.

Remarks

The positions are zero-based. The first character of the edit control is in the zero position. The first character after the last selected character is in the ending position. For example, to select the first four characters of the edit control, use a starting position of 0 and an ending position of 4.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_GETEDITSEL


CB_SETEXTENDEDUI

An application sends a CB_SETEXTENDEDUI message to select either the default user interface or the extended user interface for a combo box that has the CBS_DROPDOWN or CBS_DROPDOWNLIST style.

CB_SETEXTENDEDUI
wParam = (WPARAM) (BOOL) fExtended;    // extended user interface flag
lParam = 0;                            // not used; must be zero

Parameters

fExtended
Value of wParam. Specifies whether the combo box uses the extended user interface or the default user interface. A value of TRUE selects the extended user interface; a value of FALSE selects the standard user interface.

Return Values

If the operation succeeds, the return value is CB_OKAY. If an error occurs, it is CB_ERR.

Remarks

By default, the f4 key opens or closes the list and the down arrow changes the current selection. In the extended user interface, the f4 key is disabled and the down arrow key opens the drop-down list.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_GETEXTENDEDUI


CB_SETHORIZONTALEXTENT

An application sends the CB_SETHORIZONTALEXTENT message to set the width, in pixels, by which a list box can be scrolled horizontally (the scrollable width). If the width of the list box is smaller than this value, the horizontal scroll bar horizontally scrolls items in the list box. If the width of the list box is equal to or greater than this value, the horizontal scroll bar is hidden or, if the combo box has the CBS_DISABLENOSCROLL style, disabled.

CB_SETHORIZONTALEXTENT
wParam = (WPARAM) cxExtent;            // scrollable width of list box, in pixels
lParam = 0;                            // not used, must be zero

Parameters

cxExtent
Specifies the scrollable width of the list box, in pixels.

Return Values

No return value.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_GETHORIZONTALEXTENT


CB_SETITEMDATA

An application sends a CB_SETITEMDATA message to set the 32-bit value associated with the specified item in a combo box.

CB_SETITEMDATA
wParam = (WPARAM) index;            // item index
lParam = (LPARAM) (DWORD) dwData;   // item data

Parameters

index
Value of wParam. Specifies the item's zero-based index.
dwData
Value of lParam. Specifies the new value to be associated with the item.

Return Values

If an error occurs, the return value is CB_ERR.

Remarks

If the specified item is in an owner-drawn combo box created without the CBS_HASSTRINGS style, this message replaces the 32-bit value in the lParam parameter of the CB_ADDSTRING or CB_INSERTSTRING message that added the item to the combo box.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_ADDSTRING, CB_GETITEMDATA, CB_INSERTSTRING


CB_SETITEMHEIGHT

An application sends a CB_SETITEMHEIGHT message to set the height of list items or the selection field in a combo box.

CB_SETITEMHEIGHT
wParam = (WPARAM) index;        // item index
lParam = (LPARAM) (int) height; // item height

Parameters

index
Value of wParam. Specifies the component of the combo box for which to set the height.

This parameter must be –1 to set the height of the selection field. It must be zero to set the height of list items, unless the combo box has the CBS_OWNERDRAWVARIABLE style. In that case, the index parameter is the zero-based index of a specific list item.

height
Value of lParam. Specifies the height, in pixels, of the combo box component identified by index.

Return Values

If the index or height is invalid, the return value is CB_ERR.

Remarks

The selection field height in a combo box is set independently of the height of the list items. An application must ensure that the height of the selection field is not smaller than the height of a particular list item.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_GETITEMHEIGHT, WM_MEASUREITEM


CB_SETLOCALE

An application sends a CB_SETLOCALE message to set the current locale of the combo box. If the combo box has the CBS_SORT style and strings are added using CB_ADDSTRING, the locale of a combo box affects how list items are sorted.

CB_SETLOCALE
wParam = (WPARAM) (WORD) wLocaleID; // locale identifier
lParam = 0;                         // not used; must be zero

Parameters

wLocaleID
Value of wParam. Specifies the locale identifier for the combo box to use for sorting when adding text.

Return Values

The return value is the previous locale identifier. If wParam specifies a locale not installed on the system, the return value is CB_ERR and the current combo box locale is not changed.

Remarks

Use the MAKELCID macro to construct a locale identifier and the MAKELANGID macro to construct a language identifier. The language identifier is made up of a primary language identifier and a sublanguage identifier.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_ADDSTRING, CB_GETLOCALE, MAKELANGID, MAKELCID


CB_SETTOPINDEX

An application sends the CB_SETTOPINDEX message to ensure that a particular item is visible in the list box of a combo box. The system scrolls the list box contents so that either the specified item appears at the top of the list box or the maximum scroll range has been reached.

CB_SETTOPINDEX
wParam = (WPARAM) index;            // zero-based index of item list
lParam = 0;                         // not used, must be zero

Parameters

index
Specifies the zero-based index of the list item.

Return Values

If the message is successful, the return value is zero.

If the message fails, the return value is CB_ERR.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_GETTOPINDEX


CB_SHOWDROPDOWN

An application sends a CB_SHOWDROPDOWN message to show or hide the list box of a combo box that has the CBS_DROPDOWN or CBS_DROPDOWNLIST style.

CB_SHOWDROPDOWN
wParam = (WPARAM) (BOOL) fShow;     // the show/hide flag
lParam = 0;                         // not used; must be zero

Parameters

fShow
Value of wParam. Specifies whether the drop-down list box is to be shown or hidden. A value of TRUE shows the list box; a value of FALSE hides it.

Return Values

The return value is always TRUE.

Remarks

This message has no effect on a combo box created with the CBS_SIMPLE style.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_GETDROPPEDSTATE


CBN_CLOSEUP

The CBN_CLOSEUP notification message is sent when the list box of a combo box has been closed. The parent window of the combo box receives this notification message through the WM_COMMAND message.

CBN_CLOSEUP
idComboBox = (int) LOWORD(wParam);  // identifier of combo box
hwndComboBox = (HWND) lParam;       // handle to combo box

Remarks

If the user changed the current selection, the combo box also sends the CBN_SELCHANGE notification when the drop-down list closes. In general, you cannot predict the order in which notifications will be sent. In particular, a CBN_SELCHANGE notification message may occur either before or after a CBN_CLOSEUP notification message.

To execute a specific process each time the user selects a list item, you can handle either the CBN_SELCHANGE or CBN_CLOSEUP notification message. Typically, you would wait for the CBN_CLOSEUP notification before processing a change in the current selection. This can be particularly important if a significant amount of processing is required.

This notification message is not sent to a combo box that has the CBS_SIMPLE style.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CBN_DROPDOWN, CBN_SELCHANGE, WM_COMMAND


CBN_DBLCLK

The CBN_DBLCLK notification message is sent when the user double-clicks a string in the list box of a combo box. The parent window of the combo box receives this notification message through the WM_COMMAND message.

CBN_DBLCLK
idComboBox = (int) LOWORD(wParam);  // identifier of combo box
hwndComboBox = (HWND) lParam;       // handle to combo box

Remarks

This notification message occurs only for a combo box with the CBS_SIMPLE style. In a combo box with the CBS_DROPDOWN or CBS_DROPDOWNLIST style, a double-click cannot occur because a single click closes the list box.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CBN_SELCHANGE, WM_COMMAND


CBN_DROPDOWN

The CBN_DROPDOWN notification message is sent when the list box of a combo box is about to be made visible. The parent window of the combo box receives this notification message through the WM_COMMAND message.

CBN_DROPDOWN
idComboBox = (int) LOWORD(wParam);  // identifier of combo box
hwndComboBox = (HWND) lParam;       // handle to combo box

Remarks

This notification message can occur only for a combo box with the CBS_DROPDOWN or CBS_DROPDOWNLIST style.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CBN_CLOSEUP, WM_COMMAND


CBN_EDITCHANGE

The CBN_EDITCHANGE notification message is sent after the user has taken an action that may have altered the text in the edit control portion of a combo box. Unlike the CBN_EDITUPDATE notification message, this notification message is sent after the system updates the screen. The parent window of the combo box receives this notification message through the WM_COMMAND message.

CBN_EDITCHANGE
idComboBox = (int) LOWORD(wParam);  // identifier of combo box
hwndComboBox = (HWND)lParam;        // handle to combo box

Remarks

If the combo box has the CBS_DROPDOWNLIST style, this notification message does not occur.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CBN_EDITUPDATE, WM_COMMAND


CBN_EDITUPDATE

The CBN_EDITUPDATE notification message is sent when the edit control portion of a combo box is about to display altered text. This notification message is sent after the control has formatted the text, but before it displays the text. The parent window of the combo box receives this notification message through the WM_COMMAND message.

CBN_EDITUPDATE
idComboBox = (int) LOWORD(wParam);  // identifier of combo box
hwndComboBox = (HWND) lParam;       // handle to combo box

Remarks

If the combo box has the CBS_DROPDOWNLIST style, this notification message does not occur.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CBN_EDITCHANGE, WM_COMMAND


CBN_ERRSPACE

The CBN_ERRSPACE notification message is sent when a combo box cannot allocate enough memory to meet a specific request. The parent window of the combo box receives this notification message through the WM_COMMAND message.

CBN_ERRSPACE
idComboBox = (int) LOWORD(wParam);  // identifier of combo box
hwndComboBox = (HWND) lParam;       // handle to combo box

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, WM_COMMAND


CBN_KILLFOCUS

The CBN_KILLFOCUS notification message is sent when a combo box loses the keyboard focus. The parent window of the combo box receives this notification message through the WM_COMMAND message.

CBN_KILLFOCUS
idComboBox = (int) LOWORD(wParam);  // identifier of combo box
hwndComboBox = (HWND) lParam;       // handle to combo box

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CBN_SETFOCUS, WM_COMMAND


CBN_SELCHANGE

The CBN_SELCHANGE notification message is sent when the user changes the current selection in the list box of a combo box. The user can change the selection by clicking in the list box or by using the arrow keys. The parent window of the combo box receives this notification in the form of a WM_COMMAND message with CBN_SELCHANGE in the high-order word of the wParam parameter.

CBN_SELCHANGE
idComboBox = (int) LOWORD(wParam);  // identifier of combo box
hwndComboBox = (HWND) lParam;       // handle to combo box

Remarks

To get the index of the current selection, send the CB_GETCURSEL message to the control.

The CBN_SELCHANGE notification message is not sent when the current selection is set using the CB_SETCURSEL message.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CBN_CLOSEUP, CBN_DBLCLK, WM_COMMAND


CBN_SELENDCANCEL

The CBN_SELENDCANCEL notification message is sent when the user selects an item, but then selects another control or closes the dialog box. It indicates the user's initial selection is to be ignored. The parent window of the combo box receives this notification message through the WM_COMMAND message.

CBN_SELENDCANCEL
idComboBox = (int) LOWORD(wParam);  // identifier of combo box
hwndComboBox = (HWND) lParam;       // handle to combo box

Remarks

In a combo box with the CBS_SIMPLE style, the CBN_SELENDCANCEL notification message is not sent. The CBN_SELENDOK notification message is sent immediately before every CBN_SELCHANGE notification message.

If the WS_EX_NOPARENTNOTIFY extended window style is specified for the combo box, the CBN_SELENDCANCEL notification message is not sent.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CBN_SELCHANGE, CBN_SELENDOK, WM_COMMAND


CBN_SELENDOK

The CBN_SELENDOK notification message is sent when the user selects a list item, or selects an item and then closes the list. It indicates that the user's selection is to be processed. The parent window of the combo box receives this notification message through the WM_COMMAND message.

CBN_SELENDOK
idComboBox = (int) LOWORD(wParam);  // identifier of combo box
hwndComboBox = (HWND) lParam;       // handle to combo box

Remarks

In a combo box with the CBS_SIMPLE style, the CBN_SELENDOK notification message is sent immediately before every CBN_SELCHANGE notification message.

If the WS_EX_NOPARENTNOTIFY extended window style is specified for the combo box, the CBN_SELENDOK notification message is not sent.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CBN_SELCHANGE, CBN_SELENDCANCEL, WM_COMMAND


CBN_SETFOCUS

The CBN_SETFOCUS notification message is sent when a combo box receives the keyboard focus. The parent window of the combo box receives this notification message through the WM_COMMAND message.

CBN_SETFOCUS
idComboBox = (int) LOWORD(wParam);  // identifier of combo box
hwndComboBox = (HWND) lParam;       // handle to combo box

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, CBN_KILLFOCUS, WM_COMMAND


WM_COMPAREITEM

The system sends the WM_COMPAREITEM message to determine the relative position of a new item in the sorted list of an owner-drawn combo box or list box. Whenever the application adds a new item, the system sends this message to the owner of a combo box or list box created with the CBS_SORT or LBS_SORT style.

WM_COMPAREITEM
idCtl = wParam;                       // control identifier
lpcis = (LPCOMPAREITEMSTRUCT) lParam; // structure with items

Parameters

idCtl
Value of wParam. Specifies the identifier of the control that sent the WM_COMPAREITEM message.
lpcis
Value of lParam. Pointer to a COMPAREITEMSTRUCT structure that contains the identifiers and application-supplied data for two items in the combo or list box.

Return Values

The return value indicates the relative position of the two items. It may be any of the following:

Value | Meaning
–1 | Item 1 precedes item 2 in the sorted order.
0 | Items 1 and 2 are equivalent in the sorted order.
1 | Item 1 follows item 2 in the sorted order.

Remarks

When the owner of an owner-drawn combo box or list box receives this message, the owner returns a value indicating which of the items specified by the COMPAREITEMSTRUCT structure will appear before the other. Typically, the system sends this message several times until it determines the exact position for the new item.

If a dialog box procedure handles this message, it should cast the desired return value to a BOOL and return the value directly. The DWL_MSGRESULT value set by the SetWindowLong function is ignored.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, COMPAREITEMSTRUCT


WM_DRAWITEM

The WM_DRAWITEM message is sent to the owner window of an owner-drawn button, combo box, list box, or menu when a visual aspect of the button, combo box, list box, or menu has changed.

WM_DRAWITEM
idCtl = (UINT) wParam;             // control identifier
lpdis = (LPDRAWITEMSTRUCT) lParam; // item-drawing information

Parameters

idCtl
Value of wParam. Specifies the identifier of the control that sent the WM_DRAWITEM message. If the message was sent by a menu, this parameter is zero.
lpdis
Value of lParam. Pointer to a DRAWITEMSTRUCT structure containing information about the item to be drawn and the type of drawing required.

Return Values

If an application processes this message, it should return TRUE.

Default Action

The DefWindowProc function draws the focus rectangle for an owner-drawn list box item.

Remarks

The itemAction member of the DRAWITEMSTRUCT structure specifies the drawing operation that an application should perform.

Before returning from processing this message, an application should ensure that the device context identified by the hDC member of the DRAWITEMSTRUCT structure is in the default state.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, DefWindowProc, DRAWITEMSTRUCT


WM_MEASUREITEM

The WM_MEASUREITEM message is sent to the owner window of an owner-drawn button, combo box, list box, list view control, or menu item when the control or menu is created.

WM_MEASUREITEM
idCtl = (UINT) wParam;                // control identifier
lpmis = (LPMEASUREITEMSTRUCT) lParam; // item-size information

Parameters

idCtl
Value of wParam. Contains the value of the CtlID member of the MEASUREITEMSTRUCT structure pointed to by the lpmis parameter. This value identifies the control that sent the WM_MEASUREITEM message.

If the value is zero, the message was sent by a menu. If the value is nonzero, the message was sent by a combo box or by a list box. If the value is nonzero, and the value of the itemID member of the MEASUREITEMSTRUCT pointed to by lpmis is (UINT) –1, the message was sent by a combo edit field.

lpmis
Value of lParam. Pointer to a MEASUREITEMSTRUCT structure that contains the dimensions of the owner-drawn control or menu item.

Return Values

If an application processes this message, it should return TRUE.

Remarks

When the owner window receives the WM_MEASUREITEM message, the owner fills in the MEASUREITEMSTRUCT structure pointed to by the lParam parameter of the message and returns; this informs the system of the dimensions of the control. If a list box or combo box is created with the LBS_OWNERDRAWVARIABLE or CBS_OWNERDRAWVARIABLE style, this message is sent to the owner for each item in the control; otherwise, this message is sent once.

The system sends the WM_MEASUREITEM message to the owner window of combo boxes and list boxes created with the OWNERDRAWFIXED style before sending the WM_INITDIALOG message. As a result, when the owner receives this message, the system has not yet determined the height and width of the font used in the control; function calls and calculations requiring these values should occur in the main function of the application or library.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Combo Boxes Overview, Combo Box Messages, MEASUREITEMSTRUCT, WM_INITDIALOG


Combo Box Styles

To create a combo box using the CreateWindow or CreateWindowEx function, specify the COMBOBOX class, appropriate window style constants, and a combination of the following combo box styles.

Style | Description
CBS_AUTOHSCROLL | Automatically scrolls the text in an edit control to the right when the user types a character at the end of the line. If this style is not set, only text that fits within the rectangular boundary is allowed.
CBS_DISABLENOSCROLL | Shows a disabled vertical scroll bar in the list box when the box does not contain enough items to scroll. Without this style, the scroll bar is hidden when the list box does not contain enough items.
CBS_DROPDOWN | Similar to CBS_SIMPLE, except that the list box is not displayed unless the user selects an icon next to the edit control.
CBS_DROPDOWNLIST | Similar to CBS_DROPDOWN, except that the edit control is replaced by a static text item that displays the current selection in the list box.
CBS_HASSTRINGS | Specifies that an owner-drawn combo box contains items consisting of strings. The combo box maintains the memory and address for the strings so the application can use the CB_GETLBTEXT message to retrieve the text for a particular item.
CBS_LOWERCASE | Converts to lowercase all text in both the selection field and the list.
CBS_NOINTEGRALHEIGHT | Specifies that the size of the combo box is exactly the size specified by the application when it created the combo box. Normally, the system sizes a combo box so that it does not display partial items.
CBS_OEMCONVERT | Converts text entered in the combo box edit control from the Windows character set to the OEM character set and then back to the Windows set. This ensures proper character conversion when the application calls the CharToOem function to convert a Windows string in the combo box to OEM characters. This style is most useful for combo boxes that contain filenames and applies only to combo boxes created with the CBS_SIMPLE or CBS_DROPDOWN style.
CBS_OWNERDRAWFIXED | Specifies that the owner of the list box is responsible for drawing its contents and that the items in the list box are all the same height. The owner window receives a WM_MEASUREITEM message when the combo box is created and a WM_DRAWITEM message when a visual aspect of the combo box has changed.
CBS_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 you create the combo box and a WM_DRAWITEM message when a visual aspect of the combo box has changed.
CBS_SIMPLE | Displays the list box at all times. The current selection in the list box is displayed in the edit control.
CBS_SORT | Automatically sorts strings added to the list box.
CBS_UPPERCASE | Converts to uppercase all text in both the selection field and the list.


Edit Controls

Microsoft® Windows® and Microsoft® Windows NT® provide dialog boxes and controls to support communication between the application and the user. An edit control is a rectangular control window typically used in a dialog box to permit the user to enter and edit text from the keyboard.

The system supports both Unicode text (characters are two bytes), and ANSI (characters are one byte). For more information about Unicode and character sets, see Unicode and Character Sets.


About Edit Controls

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 moved or deleted 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. For more information about messages from an edit control, see Edit Control Notification Messages. A parent window can send messages to an edit control in a dialog box by calling the SendDlgItemMessage function. Each of the messages sent to edit controls are discussed in this overview.

The system provides both single line edit controls (sometime 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. For more information about combo boxes, see Combo Boxes.

Many developers use the dialog boxes provided in the common dialog box library (COMDLG32.DLL) to perform tasks that otherwise might require customized edit controls. For information about common dialog boxes, see Common Dialog Box Library.


Edit Control Types and Styles

There are several edit control styles. An individual edit control can have several styles at the same time. Most developers use tools to develop dialog boxes and so may not need to specify edit control styles explicitly. If an application creates an edit control using the CreateWindow or CreateWindowEx function, however, it must specify these edit control styles. For a table of edit control styles, see Edit Control Styles.

Every edit control specifies a combination of style values that define the appearance and features of the edit control. The style values can establish the appearance of a single-line or multiline edit control, align the text in the control, and determine how, and even if, text appears in the edit control. The number and type of styles the application uses depend on the type and purpose of the edit control.

There are two line styles for edit controls. The default is a single-line edit control that doesn't require an associated style. An application can create a multiline edit control by using the ES_MULTILINE style.

There are three styles that cause the system to align the text in an edit control. The ES_LEFT, ES_CENTER, and ES_RIGHT styles determine whether text is aligned on the left, center, or right, respectively.

An application can use a style to determine how the system displays text that a user enters into an edit control. The ES_LOWERCASE style converts the text into lowercase characters; the ES_UPPERCASE style converts the text into uppercase characters. Some applications may need to convert the text in a string (such as a filename) into a specific character set. The ES_OEMCONVERT style ensures the proper conversion of characters in these instances. For more information about character sets, see Consoles and Character-Mode Support.

When the amount of text to be displayed exceeds the size of the edit control, an application can use two styles to scroll the text through the edit control. The ES_AUTOHSCROLL style automatically scrolls text horizontally in single-line and multiline edit controls. When the application has a multiline edit control, it can also use the ES_AUTOVSCROLL style to automatically scroll text vertically, if necessary.

Other available styles define different aspects of an edit control. The ES_NUMBER style restricts input to the edit control to digits only. The ES_NOHIDESEL style specifies that the selected text is not hidden when the edit control loses the keyboard focus. The ES_READONLY style makes the edit control read-only. The ES_PASSWORD style displays all characters in the edit control as asterisks. (An application can define a different character to display by using the EM_SETPASSWORDCHAR message, as described later in this topic.) In multiline edit controls, an application can specify the ES_WANTRETURN style to request that the system insert a carriage return when the user presses the enter key in the edit control.

By default, an edit control has no border. To give it one, an application can use the WS_BORDER window style.


The Text Buffer

The system stores edit control text in a buffer and copies it to the control, as necessary. The following topics discuss how the system allocates and initializes the buffer and changes its characteristics.

  • Allocating a Text Buffer
  • Initializing a Text Buffer
  • Making a Text Buffer Read-only


Allocating a Text Buffer

When the system creates an edit control, it automatically creates a text buffer, sets its initial size, and increases the size as necessary. The size can be up to a predefined limit of approximately 32 kilobytes for single-line edit controls. Because this limit can change, it is called a soft limit. An application can set a hard limit to the buffer size by sending an EM_SETLIMITTEXT message to the edit control. If the buffer exceeds either limit, the system sends the application an EN_ERRSPACE message. An application can retrieve the current text limit by sending an EM_GETLIMITTEXT message.

The system typically creates an edit control buffer in a dialog box, using memory outside the application's data segment. An application can suppress this default allocation behavior and create the buffer from its local heap by using the DS_LOCALEDIT style when creating the edit control. An application that uses the DS_LOCALEDIT style is responsible for all buffer allocations. To make the initial allocation, an application can call the LocalAlloc function and pass the returned buffer handle to the edit control by sending it an EM_SETHANDLE message. To make subsequent allocations (in response to an EN_ERRSPACE message, for example), an application should save the current buffer content (if necessary) and obtain a new buffer as follows:

  1. Retrieve the handle of the memory currently allocated for the text in a multiline edit control by sending the control an EM_GETHANDLE message.
  2. Free the buffer by calling the LocalFree function.
  3. Obtain a new buffer (and buffer handle) by calling LocalAlloc.
  4. Give the buffer handle to the system by sending the control an EM_SETHANDLE message.

The EM_SETHANDLE and EM_GETHANDLE messages apply only to multiline edit controls.

An application that uses the default allocation behavior (that is, does not use the DS_LOCALEDIT style) must not send EM_SETHANDLE and EM_GETHANDLE messages to the edit control.

Sending an EM_SETHANDLE message has several side effects: it clears the undo flag (making the EM_CANUNDO message return zero), it clears the modify flag (making the EM_GETMODIFY message return zero), and it redraws the edit control window.


Initializing a Text Buffer

An application can initialize or reinitialize an edit control's text buffer by calling the SetDlgItemText function. An application can retrieve the content of a text buffer by calling the GetDlgItemText function.


Making a Text Buffer Read-only

For each edit control, the system maintains a read-only flag that indicates whether the control's text is read-write (the default) or read-only. An application can set the read-write or read-only flag for the text by sending the control an EM_SETREADONLY message. To determine whether an edit control is read-only, an application can call the GetWindowLong function using the GWL_STYLE constant. The EM_SETREADONLY message applies to both single-line and multiline edit controls.


Changing the Formatting Rectangle

The visibility of an edit control's text is governed by the dimensions of its window rectangle and its formatting rectangle. The window rectangle is the client area of the window containing the edit control. The formatting rectangle is a construct maintained by the system for formatting the text displayed in the window rectangle. When an edit control is first displayed, the two rectangles are identical on the screen. An application can make the formatting rectangle larger than the window rectangle (thereby limiting the visibility of the edit control's text) or smaller than the window rectangle (thereby creating extra white space around the text).

An application can set the coordinates of an edit control's formatting rectangle by sending it an EM_SETRECT message. The EM_SETRECT message also automatically redraws the edit control's text. To establish the coordinates of the formatting rectangle without redrawing the control's text, an application can send the control an EM_SETRECTNP message. To retrieve the coordinates of the formatting rectangle, an application can send the control an EM_GETRECT message. These messages apply to multiline edit controls only.


Text Operations

The system automatically processes all user-initiated text operations and notifies the application when the operations are completed. The following topics discuss user-initiated text operations and the application's response.

  • Selecting an Edit Control
  • Selecting Text
  • Replacing Text
  • Changing the Font Used By an Edit Control
  • Cut, Copy, Paste, and Clear Operations
  • Modifying Text
  • Limiting User-Entered Text
  • Character and Line Operations
  • Scrolling Text in an Edit Control
  • Setting Tab Stops and Margins
  • Concealing User Input
  • Using Integers
  • Undoing Text Operations
  • Handling Word Wrap
  • Retrieving Points and Characters


Selecting an Edit Control

The user can select an edit control by clicking it with the mouse or by tabbing to it. The "tabbing" method is part of a predefined keyboard interface that the system provides. For a complete description of this interface, see Dialog Boxes. When the user selects an edit control, the system gives the control the keyboard focus and highlights its text by using reverse video.


Selecting Text

After selecting an edit control, the user can select text in the control by using the mouse or the keyboard. An application can retrieve the starting and ending character positions of the current selection in an edit control by sending the control an EM_GETSEL message. The return value for the ending position is one greater than the last character in the selection (that is, the position of the first character following the last selected character).

An application can also select text in an edit control by sending the control an EM_SETSEL message with the starting and ending character indices for the selection. For example, the application can use EM_SETSEL with EM_REPLACESEL to delete text from an edit control.

These three messages apply to both single-line and multiline edit controls.


Replacing Text

An application can replace selected text in an edit control by sending the control an EM_REPLACESEL message with a pointer to the replacement text. If there is no current selection, EM_REPLACESEL inserts the replacement text at the insertion point. The application may receive an EN_ERRSPACE notification message if the replacement text exceeds the available memory. This message applies to both single-line and multiline edit controls.

An application can use EM_REPLACESEL to replace part of an edit control's text or the SetDlgItemText function to replace all of it.


Changing the Font Used By an Edit Control

An application can change the font that an edit control uses by sending the WM_SETFONT message. Most applications do this while processing the WM_INITDIALOG message. Changing the font does not change the size of the edit control; applications that send the WM_SETFONT message may have to retrieve the font metrics for the text and recalculate the size of the edit control. For more information about fonts and font metrics, see Fonts and Text.


Cut, Copy, Paste, and Clear Operations

The Win32 API provides four messages for moving text between an edit control and the clipboard. The WM_COPY message copies the current selection (if any) from an edit control to the clipboard without deleting it from the edit control. The WM_CUT message deletes the current selection, if any, in the edit control and copies the deleted text to the clipboard. The WM_CLEAR message deletes the current selection (if any) from an edit control, but does not copy it to the clipboard (unless the user pressed the shift key). The WM_PASTE message copies text from the clipboard into an edit control at the insertion point. These four messages apply to both single-line and multiline edit controls.

With Windows NT version 4.0 or later, an edit control includes a built in context menu that makes it easy for the user to move text between the edit control and the clipboard. The context menu appears when the user clicks the control using the right mouse button. The menu items in the context menu include Undo, Cut, Copy, Paste, Delete, and Select All.


Modifying Text

The user can select, delete, or move text in an edit control. The system maintains an internal flag for each edit control indicating whether the content of the control has been modified. The system clears this flag when it creates the control and sets the flag whenever the text in the control is modified. An application can retrieve the modification flag by sending the control an EM_GETMODIFY message and set or clear the modification flag by sending the control an EM_SETMODIFY message. These messages apply to both single-line and multiline edit controls.


Limiting User-Entered Text

The default limit to the amount of text a user can enter in an edit control is 32 kilobytes. An application can change the amount of text the user can enter by sending the control an EM_SETLIMITTEXT message. This message sets a hard limit to the number of bytes the user can enter into an edit control, but affects neither text that is already in the control when the message was sent nor text copied to the control by the SetDlgItemText function or the WM_SETTEXT message. For example, suppose that the application uses the SetDlgItemText function to place 500 bytes in an edit control, and the user also enters 500 bytes (1000 bytes total). If the application then sends an EM_SETLIMITTEXT message limiting user-entered text to 300 bytes, the 1000 bytes already in the edit control remain there, and the user cannot add any more text. On the other hand, if the application sends an EM_SETLIMITTEXT message limiting user-entered text to 1300 bytes, the 1000 bytes remain, but the user can add 300 more bytes.

When the user reaches the character limit of an edit control, the system sends the application a WM_COMMAND message containing an EN_MAXTEXT notification message. This notification message does not mean that memory has been exhausted, but that the limit for user-entered text has been reached; the user cannot enter any more text. To change this limit, an application must send the control a new EM_SETLIMITTEXT message with a higher limit.

As an example of the use of EM_SETLIMITTEXT and EN_MAXTEXT, suppose that the application must limit the user to no more than four characters in an edit control. The application would use EM_SETLIMITTEXT to specify a four-character limit. If the user tried to enter a fifth character, the system would send an EN_MAXTEXT notification message to the application.


Character and Line Operations

TheWin32 API provides several messages that return information about the characters and lines in an edit control. Most of the messages return an index, usually a zero-based number, to refer to a character or line. Given this, a single-line edit control containing n characters, the line index is zero and the characters are indexed from zero to n – 1. In a multiline edit control containing m lines and n characters, the lines are indexed from zero to m – 1, and the characters are indexed from zero to n – 1. Note that character indexing ignores line breaks.

An application can determine the number of characters in an edit control by sending the WM_GETTEXTLENGTH message to the edit control. This message returns the length, in characters (not including the terminating null character), of the text in a single-line or multiline edit control. The EM_LINELENGTH message returns the length, in characters, of a line specified by the character index of a character in the line. The returned length does not include any selected characters. An application can use these messages in a single-line or multiline edit control.

The EM_GETFIRSTVISIBLELINE message returns the zero-based index of the uppermost visible line in a multiline edit control, or the zero-based index of the first visible character in a single-line edit control. An application can copy a line from an edit control to a buffer by sending the EM_GETLINE message to the edit control. The line is specified by its line index and the first word of the receiving buffer contains the maximum number of bytes to be copied to the buffer. The return value is the number of bytes copied. This message can also be used in a single-line or multiline edit control.

There are unique messages available to return the information about a line in a multiline edit control. The EM_GETLINECOUNT message returns the number of lines in an edit control. An application can determine the index of a character in a specific line by using the EM_LINEFROMCHAR and EM_LINEINDEX messages. The EM_LINEFROMCHAR message returns the index of the line containing a specified character index. This message is the reverse of the EM_LINEINDEX message, which returns the index of the first character in a specified line.


Scrolling Text in an Edit Control

To implement scrolling in an edit control, you can use the automatic scrolling styles discussed in Edit Control Types and Styles, or you can explicitly add scroll bars to the edit control. To add a horizontal scroll bar, use the style WS_HSCROLL; to add a vertical scroll bar, use the style WS_VSCROLL. An edit control with scroll bars processes its own scroll bar messages. For detailed information about adding scroll bars to edit controls, see Scroll Bars.

The system provides three messages that an application can send to an edit control with scroll bars. The EM_LINESCROLL message can scroll a multiline edit control both vertically and horizontally. The lParam parameter specifies the number of lines to scroll vertically starting from the current line and the wParam parameter specifies the number of characters to scroll horizontally, starting from the current character. The edit control doesn't acknowledge horizontal scrolling messages if it has the ES_CENTER or ES_RIGHT style. The EM_LINESCROLL message applies to multiline edit controls only.

The EM_SCROLL message scrolls a multiline edit control vertically, which is the same effect as sending a WM_VSCROLL message. The wParam parameter specifies the scrolling action. The EM_SCROLL message applies to multiline edit controls only.

The EM_SCROLLCARET message scrolls the caret into view in an edit control. This was done in 16-bit Windows by specifying wParam = FALSE in an EM_SETSEL message. A Win32-based application should use the EM_SCROLLCARET message for the task.


Setting Tab Stops and Margins

An application can set tab stops in a multiline edit control by using the EM_SETTABSTOPS message. (The default for a tab stop is eight characters.) When an application adds text to the edit control, tab characters in the text automatically generate space up to the next tab stop. The EM_SETTABSTOPS message does not automatically cause the system to redraw the text. To do that, an application can call the InvalidateRect function. The EM_SETTABSTOPS message applies to multiline edit controls only.

An application can set width of the left and right margins for an edit control by using the EM_SETMARGINS message. After sending this message, the system redraws the edit control to reflect the new margin settings. An application can retrieve the width of the left or right margin by sending the EM_GETMARGINS message. By default, the edit control margins are set to be just wide enough to accommodate the largest character horizontal overhang (negative ABC widths) for the font currently in use in the edit control.


Concealing User Input

An application can use a password character in an edit control to conceal user input. When a password character is set, it is displayed in place of each character the user types. When a password character is removed, the control displays the characters the user types. If the application creates an edit control using the style ES_PASSWORD, the default password character is an asterisk (*). An application can use the EM_SETPASSWORDCHAR message to remove or define a different password character and the EM_GETPASSWORDCHAR message to retrieve the current password character. These messages apply to single-line edit controls only.


Using Integers

The Win32 API provides two integer-conversion functions for edit controls designed to contain numbers only. The SetDlgItemInt function creates the string representation of a specified integer (signed or unsigned) and sends the string to an edit control. SetDlgItemInt returns no value. The GetDlgItemInt function creates an integer (signed or unsigned) from its string representation in an edit control. GetDlgItemInt returns the integer (or an error value).


Undoing Text Operations

Every edit control maintains an undo flag that indicates whether an application can reverse (undo) the most recent operation on the edit control (to undo a text deletion, for example). The edit control sets the undo flag to indicate that the operation can be undone and resets it to indicate that the operation cannot be undone. An application can determine the setting of the undo flag by sending the control an EM_CANUNDO message.

An application can undo the most recent operation by sending the control an EM_UNDO message. An operation can be undone provided no other edit control operation occurs first. For example, the user can delete text, replace the text (undo the deletion), and then delete the text again (undo the replacement). The EM_UNDO message applies to both single-line and multiline edit controls and always works for single-line edit controls.

An application can reset an edit control's undo flag by sending the control an EM_EMPTYUNDOBUFFER message. The system automatically resets the undo flag whenever an edit control receives an EM_SETHANDLE or WM_SETTEXT message. The SetDlgItemText function sends a WM_SETTEXT message.


Handling Word Wrap

An application can use word wrap functions with multiline edit controls to locate the word or word fragment that should be wrapped to the next line. Using the default word wrap function provided by the system, lines always end at the spaces between words. An application can specify its own word wrap function by supplying a EditWordBreakProc word wrap function and sending an edit control an EM_SETWORDBREAKPROC message. An application can retrieve the address of the current word wrap function by sending the control an EM_GETWORDBREAKPROC message.

An application may direct a multiline edit control to add or remove a soft line break character (two carriage returns and a linefeed) automatically at the end of wrapped text lines. An application can turn this feature on or off by sending the edit control an EM_FMTLINES message. This message applies only to multiline edit controls and does not affect a line that ends with a hard line break (one carriage return and a linefeed entered by the user).


Retrieving Points and Characters

An application can determine which character is closest to the specified point in an edit control by sending the EM_CHARFROMPOS message. The message returns the character index and line index of the character nearest the point. Similarly, an application can determine the client coordinates of the specified character in an edit control by sending the EM_POSFROMCHAR message. The application specifies the index of a character and the message returns the x and y coordinates of the upper left corner of the character.


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 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 action
EN_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. 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.


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.

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 linefeed) 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 single-line 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.
EM_GETWORDBREAKPROC | Returns the address of the current word wrap 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 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 single-line 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_SETLIMITTEXT Sets the maximum number of characters the user may enter in the edit control.

Windows NT: 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 0xFFFFFFFF or the value of the wParam parameter, whichever is smaller.

Windows 95 and Windows 98: 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.
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_SETRECT | Sets the formatting rectangle for the multiline edit control and redraws the window. It is not processed by single-line edit controls.
EM_SETRECTNP | Sets 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 word wrap function with an application-defined word wrap 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_CHANGE notification 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.
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 single-line edit controls. Returns the enabled state for single-line 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 null- terminating 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 down, extends the selection to the word under the cursor.
WM_LBUTTONDOWN | Changes the current insertion point. If the shift key is down, it 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, it also kills the timer set in the 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_CREATE message 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, it takes no action.
WM_SYSKEYDOWN | Undoes the last action if the user presses alt+backspace; otherwise, it 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.
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.


Using Edit Controls

Edit controls are typically used in dialog boxes, but you can use them in the client area of a standard window as well. Single-line edit controls are useful for retrieving a single string from the user. Multiline edit controls make it easy for your application to implement most of the features of a simple word processor.

  • Simple word processing with an edit control
  • Using single-line edit controls


Simple Word Processing with an Edit Control

The following example implements much of the functionality of a simple word processor by filling the client area of a window with a multiline edit control. The system automatically performs word wrap operations for this edit control and also handles the processing for the vertical scroll bar (created by specifying ES_AUTOVSCROLL in the call to the CreateWindow function). The WM_COMMAND message processes menu items; they allow the user to undo the previous action, cut or copy selections to the clipboard, paste text from the clipboard, and delete the current selection.

LONG APIENTRY MainWndProc(
HWND hwnd,                // window handle
UINT message,             // type of message
WPARAM wParam,            // additional information
LPARAM lParam)            // additional information
{
    static HWND hwndEdit;

    CHAR lpszTrouble[] = "When in the Course of human Events "
                         "it becomes necessary for one People "
                         "to dissolve the Political Bands which "
                         "have connected them with another, and "
                         "to assume among the Powers of the "
                         "Earth, the separate and equal Station "
                         "to which the Laws of Nature and of "
                         "Nature's God entitle them, a decent "
                         "Respect to the Opinions of Mankind "
                         "requires that they should declare the "
                         "causes which impel them to the "
                         "Separation. ";

    switch (message)
    {
        case WM_CREATE:
            hwndEdit = CreateWindow(
                "EDIT",     // predefined class
                NULL,       // no window title
                WS_CHILD | WS_VISIBLE | WS_VSCROLL |
                    ES_LEFT | ES_MULTILINE | ES_AUTOVSCROLL,
                0, 0, 0, 0, // set size in WM_SIZE message
                hwnd,       // parent window
                (HMENU) ID_EDITCHILD, // edit control ID
                (HINSTANCE) GetWindowLong(hwnd, GWL_HINSTANCE),
                NULL);                // pointer not needed

             // Add text to the window.

             SendMessage(hwndEdit, WM_SETTEXT, 0,
                (LPARAM) lpszTrouble);

            return 0;

        case WM_COMMAND:
            switch (wParam)
            {
                case IDM_EDUNDO:

                    // Send WM_UNDO only if there is something
                    // to be undone.

                    if (SendMessage(hwndEdit, EM_CANUNDO, 0, 0))
                        SendMessage(hwndEdit, WM_UNDO, 0, 0);
                    else
                    {
                        MessageBox(hwndEdit,
                            "Nothing to undo.",
                            "Undo notification", MB_OK);
                    }
                    break;

                case IDM_EDCUT:
                    SendMessage(hwndEdit, WM_CUT, 0, 0);
                    break;

                case IDM_EDCOPY:
                    SendMessage(hwndEdit, WM_COPY, 0, 0);
                    break;

                case IDM_EDPASTE:
                    SendMessage(hwndEdit, WM_PASTE, 0, 0);
                    break;

                case IDM_EDDEL:
                    SendMessage(hwndEdit, WM_CLEAR, 0, 0);
                    break;

                case IDM_PASSWORD:
                    DialogBox(hinst, // current instance
                        "PassBox",   // resource to use
                         hwnd,       // parent handle
                         (DLGPROC) PassProc);
                    break;

                case IDM_WRAP:
                    SendMessage(hwndEdit,
                        EM_SETWORDBREAKPROC,
                        (WPARAM) 0,
                        (LPARAM) (EDITWORDBREAKPROC) WordBreakProc);
                    SendMessage(hwndEdit,
                        EM_FMTLINES,
                        (WPARAM) TRUE,
                        (LPARAM) 0);
                    SendMessage(hwndEdit,
                        EM_SETSEL,
                        0, -1); // select all text
                    SendMessage(hwndEdit, WM_CUT, 0, 0);
                    SendMessage(hwndEdit, WM_PASTE, 0, 0);
                    break;

                case IDM_ABOUT:
                    DialogBox(hinst, // current instance
                        "AboutBox",  // resource to use
                         hwnd,       // parent handle
                         (DLGPROC) About);
                    break;

                default:
                    return DefWindowProc(hwnd, message, wParam, lParam);
            }
            break;

        case WM_SETFOCUS:
            SetFocus(hwndEdit);
            return 0;

        case WM_SIZE:

            // Make the edit control the size of the window's
            // client area.

            MoveWindow(hwndEdit,
                0, 0,           // starting x- and y-coordinates
                LOWORD(lParam), // width of client area
                HIWORD(lParam), // height of client area
                TRUE);          // repaint window
            return 0;

        case WM_DESTROY:
            PostQuitMessage(0);
            return 0;

        default:
            return DefWindowProc(hwnd, message, wParam, lParam);
    }
    return NULL;
}


Using Single-Line Edit Controls

The example in this section demonstrates how to use a window procedure to produce a dialog box that prompts the user to enter a password.

The single-line edit control in the Password dialog box has the ES_PASSWORD style. By default, edit controls with this style display an asterisk for each character the user types. This example, however, uses the EM_SETPASSWORDCHAR message to change the default character from an asterisk to a plus sign (+).

This window procedure changes the default push button from Cancel to OK as soon as the user enters text in the edit control. If the user presses the OK button, the window procedure uses the EM_LINELENGTH and EM_GETLINE messages to retrieve the text.

LRESULT CALLBACK PassProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
    CHAR lpszPassword[16];
    WORD cchPassword;

    switch (message)
    {
        case WM_INITDIALOG:

            // Set password character to a plus sign (+)

            SendDlgItemMessage(hDlg,
                IDE_PASSWORDEDIT,
                EM_SETPASSWORDCHAR,
                (WPARAM) '+',
                (LPARAM) 0);

            // Set the default push button to "Cancel."

            SendMessage(hDlg,
                DM_SETDEFID,
                (WPARAM) IDCANCEL,
                (LPARAM) 0);

            return TRUE;

        case WM_COMMAND:

            // Set the default push button to "OK" when the user
            // enters text.

            if(HIWORD (wParam) == EN_CHANGE &&
                    LOWORD(wParam) == IDE_PASSWORDEDIT)
            {
                SendMessage(hDlg,
                    DM_SETDEFID,
                    (WPARAM) IDOK,
                    (LPARAM) 0);
            }

            switch(wParam)
            {
                case IDOK:

                    // Get number of characters.

                    cchPassword = (WORD) SendDlgItemMessage(hDlg,
                        IDE_PASSWORDEDIT,
                        EM_LINELENGTH,
                        (WPARAM) 0,
                        (LPARAM) 0);

                    if (cchPassword >= 16)
                    {
                        MessageBox(hDlg,
                            "Too many characters.",
                            "Error",
                            MB_OK);
                        EndDialog(hDlg, TRUE);
                        return FALSE;
                    }
                    else if (cchPassword == 0)
                    {
                        MessageBox(hDlg,
                            "No characters entered.",
                            "Error",
                            MB_OK);
                        EndDialog(hDlg, TRUE);
                        return FALSE;
                    }

                    // Put the number of characters into first word
                    // of buffer.

                    *((LPWORD)lpszPassword) = cchPassword;

                    // Get the characters.

                    SendDlgItemMessage(hDlg,
                        IDE_PASSWORDEDIT,
                        EM_GETLINE,
                        (WPARAM) 0,       // line 0
                        (LPARAM) lpszPassword);

                    // Null-terminate the string.

                    lpszPassword[cchPassword] = 0;

                    MessageBox(hDlg,
                        lpszPassword,
                        "Did it work?",
                        MB_OK);

                    // Call a local password-parsing function.

                    ParsePassword(lpszPassword);

                    EndDialog(hDlg, TRUE);
                    return TRUE;

                case IDCANCEL:
                    EndDialog(hDlg, TRUE);
                    return TRUE;
            }
            return 0;
    }
    return FALSE;
        UNREFERENCED_PARAMETER(lParam);
}


Edit Control Reference

The following elements are associated with edit controls.

  • Edit Control Functions
  • Edit Control Messages
  • Edit Control Styles


Edit Control Functions

The following function is used with edit controls.

EditWordBreakProc


EditWordBreakProc

The EditWordBreakProc function is an application-defined callback function used with the EM_SETWORDBREAKPROC message. A multiline edit control or a rich edit control calls an EditWordBreakProc function whenever the control must break a line of text.

The EDITWORDBREAKPROC type defines a pointer to this callback function. EditWordBreakProc is a placeholder for the application-defined function name.

int CALLBACK EditWordBreakProc(
  LPTSTR lpch,     // pointer to edit text
  int ichCurrent,  // index of starting point
  int cch,         // length in characters of edit text
  int code         // action to take
);

Parameters

lpch
Pointer to the text of the edit control.
ichCurrent
Specifies an index to a character position in the buffer of text that identifies the point at which the function should begin checking for a word break.
cch
Specifies the number of characters in the edit control text.
code
Specifies the action to be taken by the callback function. This parameter can be one of the following values:
Value | Action
WB_CLASSIFY | Retrieve the character class and word break flags of the character at the specified position. This value is for use with rich edit controls.
WB_ISDELIMITER | Check whether the character at the specified position is a delimiter.
WB_LEFT | Find the beginning of a word to the left of the specified position.
WB_LEFTBREAK | Find the end-of-word delimiter to the left of the specified position. This value is for use with rich edit controls.
WB_MOVEWORDLEFT | Find the beginning of a word to the left of the specified position. This value is used during CTRL+LEFT key processing. This value is for use with rich edit controls.
WB_MOVEWORDRIGHT | Find the beginning of a word to the right of the specified position. This value is used during CTRL+RIGHT key processing. This value is for use with rich edit controls.
WB_RIGHT | Find the beginning of a word to the right of the specified position. (This is useful in right-aligned edit controls.)
WB_RIGHTBREAK | Find the end-of-word delimiter to the right of the specified position. (This is useful in right-aligned edit controls.) This value is for use with rich edit controls.

Return Values

If the code parameter specifies WB_ISDELIMITER, the return value is nonzero (TRUE) if the character at the specified position is a delimiter, or zero if it is not. If the code parameter specifies WB_CLASSIFY, the return value is the character class and word break flags of the character at the specified position. Otherwise, the return value is an index to the beginning of a word in the buffer of text.

Remarks

A carriage return followed by a linefeed must be treated as a single word by the callback function. Two carriage returns followed by a linefeed also must be treated as a single word.

An application must install the callback function by specifying the address of the callback function in an EM_SETWORDBREAKPROC message.

For rich edit controls, you can alternately use the EM_SETWORDBREAKPROCEX message to replace the default extended word break procedure with an EditWordBreakProcEx callback function. This function provides additional information about the text, such as the character set.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: User-defined.
Unicode: Defined as Unicode and ANSI prototypes.

See Also

Edit Controls Overview, Edit Control Functions, EM_FINDWORDBREAK, EM_SETWORDBREAKPROC, EM_SETWORDBREAKPROCEX, EditWordBreakProcEx, SendMessage


Edit Control Messages

The following messages are used with edit controls.

EM_CANUNDO
EM_CHARFROMPOS
EM_EMPTYUNDOBUFFER
EM_FMTLINES
EM_GETFIRSTVISIBLELINE
EM_GETHANDLE
EM_GETIMESTATUS
EM_GETLIMITTEXT
EM_GETLINE
EM_GETLINECOUNT
EM_GETMARGINS
EM_GETMODIFY
EM_GETPASSWORDCHAR
EM_GETRECT
EM_GETSEL
EM_GETTHUMB
EM_GETWORDBREAKPROC
EM_LIMITTEXT
EM_LINEFROMCHAR
EM_LINEINDEX
EM_LINELENGTH
EM_LINESCROLL
EM_POSFROMCHAR
EM_REPLACESEL
EM_SCROLL
EM_SCROLLCARET
EM_SETHANDLE
EM_SETIMESTATUS
EM_SETLIMITTEXT
EM_SETMARGINS
EM_SETMODIFY
EM_SETPASSWORDCHAR
EM_SETREADONLY
EM_SETRECT
EM_SETRECTNP
EM_SETSEL
EM_SETTABSTOPS
EM_SETWORDBREAKPROC
EM_UNDO
EN_CHANGE
EN_ERRSPACE
EN_HSCROLL
EN_KILLFOCUS
EN_MAXTEXT
EN_SETFOCUS
EN_UPDATE
EN_VSCROLL
WM_COMMAND
WM_COPY
WM_CTLCOLOREDIT
WM_CUT
WM_PASTE
WM_UNDO


EM_CANUNDO

An application sends an EM_CANUNDO message to determine whether an edit-control operation can be undone; that is, whether the control can respond to the EM_UNDO message.

EM_CANUNDO
wParam = 0; // not used; must be zero
lParam = 0; // not used; must be zero

Parameters

This message has no parameters.

Return Values

If the edit control can correctly process the EM_UNDO message, the return value is TRUE; otherwise, it is FALSE.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_UNDO


EM_CHARFROMPOS

The EM_CHARFROMPOS message retrieves the character index and line index of the character nearest a specified point in the client area of an edit control. The application can send this message to either an edit control or a rich edit control.

Rich edit controls use the following syntax:

EM_CHARFROMPOS
wParam = 0;                        // not used
lParam = (LPARAM) (POINTL *) lpPoint;
     // pointer to a POINTL structure with the point coordinates

Edit controls use the following syntax:

EM_CHARFROMPOS
wParam = 0;                        // not used
lParam = MAKELPARAM(xPos, yPos);   // coordinates of a point

Parameters

lParam
Specifies the coordinates of a point in the control's client area. The coordinates are in screen units and are relative to the upper-left corner of the control's client area.

Rich edit controls: lParam is a pointer to a POINTL structure that contains the horizontal and vertical coordinates.

Edit controls: The low word of lParam contains the horizontal coordinate. The high word contains the vertical coordinate.

Return Values

The low word of the return value specifies the zero-based index of the character nearest the specified point. This index is relative to the beginning of the control, not the beginning of the line. If the specified point is beyond the last character in the edit control, the return value indicates the last character in the control.

The high word of the return value specifies the zero-based index of the line that contains the character. For single-line edit controls, this value is zero. The index indicates the line delimiter if the specified point is beyond the last visible character in a line.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_POSFROMCHAR, POINTL


EM_EMPTYUNDOBUFFER

An application sends an EM_EMPTYUNDOBUFFER message to reset the undo flag of an edit control. The undo flag is set whenever an operation within the edit control can be undone.

EM_EMPTYUNDOBUFFER
wParam = 0; // not used; must be zero
lParam = 0; // not used; must be zero

Parameters

This message has no parameters.

Return Values

This message does not return a value.

Remarks

The undo flag is automatically reset whenever the edit control receives a WM_SETTEXT or EM_SETHANDLE message.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_CANUNDO, EM_SETHANDLE, EM_UNDO, WM_SETTEXT


EM_FMTLINES

An application sends an EM_FMTLINES message to set the inclusion flag of soft line break characters on or off within a multiline edit control. A soft line break consists of two carriage returns and a linefeed and is inserted at the end of a line that is broken because of word wrapping.

EM_FMTLINES
wParam = (WPARAM) (BOOL) fAddEOL;   // line break flag
lParam = 0;                         // not used; must be zero

Parameters

fAddEOL
Value of wParam. Specifies whether soft-line break characters are to be inserted. A value of TRUE inserts the characters; a value of FALSE removes them.

Return Values

The return value is identical to the fAddEOL parameter.

Remarks

This message affects only the buffer returned by the EM_GETHANDLE message and the text returned by the WM_GETTEXT message. It has no effect on the display of the text within the edit control.

The EM_FMTLINES message does not affect a line that ends with a hard line break. A hard line break consists of one carriage return and a linefeed.

Note that the size of the text changes when this message is processed.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_GETHANDLE, WM_GETTEXT


EM_GETFIRSTVISIBLELINE

An application sends an EM_GETFIRSTVISIBLELINE message to determine the uppermost visible line in an edit control.

EM_GETFIRSTVISIBLELINE
wParam = 0; // not used; must be zero
lParam = 0; // not used; must be zero

Parameters

This message has no parameters.

Return Values

The return value is the zero-based index of the uppermost visible line in a multiline edit control. For single-line edit controls, the return value is the zero-based index of the first visible character.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages


EM_GETHANDLE

An application sends an EM_GETHANDLE message to retrieve a handle of the memory currently allocated for a multiline edit control's text.

EM_GETHANDLE
wParam = 0; // not used; must be zero
lParam = 0; // not used; must be zero

Parameters

This message has no parameters.

Return Values

The return value is a memory handle identifying the buffer that holds the content of the edit control. If an error occurs, such as sending the message to a single-line edit control, the return value is zero.

Remarks

In a 16-bit Windows-based application, the handle is a local memory handle and can be used only by functions that take a local memory handle as a parameter. The application can send this message to a multiline edit control in a dialog box only if it created the dialog box with the DS_LOCALEDIT style flag set. If the DS_LOCALEDIT style is not set, the return value is still nonzero, but the return value will not be meaningful.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_SETHANDLE


EM_GETIMESTATUS

[This is preliminary documentation and subject to change.]

An application sends the EM_GETIMESTATUS message to retrieve status for the edit control's behavior with the IME.

EM_GETIMESTATUS
wParam = (WPARAM) status; // status value to get
lParam = 0;               // must be zero

Parameters

status
Indicates the type of status to retrieve. This parameter can be the following value.
Value | Meaning
EMSIS_COMPOSITIONSTRING | Sets behavior for handling the composition string.

Return Values

Data specific to the type of status to retrieve. With the EMSIS_COMPOSITIONSTRING value for status, this return value is a combination of the following values.

Value | Meaning
EIMES_GETCOMPSTRATONCE | If this flag is set, the edit control hooks the WM_IME_COMPOSITION message and returns the result string immediately. If this flag is not set, the edit control passes the WM_IME_COMPOSITION message to the default window procedure and processes the result string from the WM_CHAR message; this is the default behavior of the edit control.
EIMES_CANCELCOMPSTRINFOCUS | If this flag is set, the edit control cancels the composition string when it receives the WM_SETFOCUS message. If this flag is not set, the edit control does not cancel the composition string; this is the default behavior of the edit control.
EIMES_COMPLETECOMPSTRKILLFOCUS | If this flag is set, the edit control completes the composition string upon receiving the WM_KILLFOCUS message. If this flag is not set, the edit control does not complete the composition string; this is the default behavior of the edit control.

QuickInfo

Windows NT: Requires version 5.0 or later.
Windows: Requires Windows 98.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_SETIMESTATUS


EM_GETLIMITTEXT

An application sends the EM_GETLIMITTEXT message to retrieve the current text limit, in characters, for an edit control.

EM_GETLIMITTEXT
wParam = 0;  // not used, must be zero
lParam = 0;  // not used, must be zero

Parameters

This message has no parameters.

Return Values

  • The return value is the text limit.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_SETLIMITTEXT


EM_GETLINE

An application sends an EM_GETLINE message to copy a line of text from an edit control and place it in a specified buffer.

EM_GETLINE
wParam = (WPARAM) line;          // line number to retrieve
lParam = (LPARAM) (LPCSTR) lpch; // address of buffer for line

Parameters

line
Value of wParam. Specifies the zero-based index of the line to retrieve from a multiline edit control. A value of zero specifies the topmost line. This parameter is ignored by a single-line edit control.
lpch
Value of lParam. Pointer to the buffer that receives a copy of the line. The first word of the buffer specifies the maximum number of characters that can be copied to the buffer.

Return Values

The return value is the number of characters copied. The return value is zero if the line number specified by the line parameter is greater than the number of lines in the edit control.

Remarks

The copied line does not contain a terminating null character.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_LINELENGTH, WM_GETTEXT


EM_GETLINECOUNT

An application sends an EM_GETLINECOUNT message to retrieve the number of lines in a multiline edit control.

EM_GETLINECOUNT
wParam = 0; // not used; must be zero
lParam = 0; // not used; must be zero

Parameters

This message has no parameters.

Return Values

The return value is an integer specifying the number of lines in the multiline edit control. If no text is in the edit control, the return value is 1.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_GETLINE, EM_LINELENGTH


EM_GETMARGINS

An application sends the EM_GETMARGINS message to retrieve the widths of the left and right margins for an edit control.

EM_GETMARGINS
wParam = 0;  // not used, must be zero
lParam = 0;  // not used, must be zero

Parameters

This message has no parameters.

Return Values

Returns the width of the left margin in the low-order word, and the width of the right margin in the high-order word.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_SETMARGINS


EM_GETMODIFY

An application sends an EM_GETMODIFY message to determine whether the content of an edit control has been modified.

EM_GETMODIFY
wParam = 0; // not used; must be zero
lParam = 0; // not used; must be zero

Parameters

This message has no parameters.

Return Values

If the content of edit control has been modified, the return value is TRUE; otherwise, it is FALSE.

Remarks

The system maintains an internal flag indicating whether the content of the edit control has been changed. This flag is cleared when the edit control is first created; alternatively, an application can send an EM_SETMODIFY message to the edit control to clear the flag.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_SETMODIFY


EM_GETPASSWORDCHAR

An application sends an EM_GETPASSWORDCHAR message to retrieve the password character displayed in an edit control when the user enters text.

EM_GETPASSWORDCHAR
wParam = 0; // not used; must be zero
lParam = 0; // not used; must be zero

Parameters

This message has no parameters.

Return Values

The return value specifies the character to be displayed in place of the character typed by the user. The return value is NULL if no password character exists.

Remarks

If the edit control is created with the ES_PASSWORD style, the default password character is set to an asterisk (*).

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_SETPASSWORDCHAR


EM_GETRECT

An application sends an EM_GETRECT message to retrieve the formatting rectangle of an edit control. The formatting rectangle is the limiting rectangle of the text. The limiting rectangle is independent of the size of the edit-control window.

EM_GETRECT
wParam = 0;                    // not used; must be zero
lParam (LPARAM) (LPRECT) lprc; // address of structure for rectangle

Parameters

lprc
Value of lParam. Pointer to the RECT structure that receives the formatting rectangle.

Return Values

The return value is not a meaningful value.

Remarks

You can modify the formatting rectangle of a multiline edit control by using the EM_SETRECT and EM_SETRECTNP messages.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_SETRECT, EM_SETRECTNP, RECT


EM_GETSEL

An application sends an EM_GETSEL message to get the starting and ending character positions of the current selection in an edit control.

EM_GETSEL
wParam = (WPARAM) (LPDWORD) lpdwStart; // receives starting position
lParam = (LPARAM) (LPDWORD) lpdwEnd;   // receives ending position

Parameters

lpdwStart
Value of wParam. Pointer to a 32-bit value that receives the starting position of the selection. This parameter can be NULL.
lpdwEnd
Value of lParam. Pointer to a 32-bit value that receives the position of the first nonselected character after the end of the selection. This parameter can be NULL.

Return Values

The return value is a zero-based 32-bit value with the starting position of the selection in the low-order word and the position of the first character after the last selected character in the high-order word. If either of these values exceeds 65, 535, the return value is -1.

Remarks

In a rich edit control, if the selection is not entirely contained in the first 64K, use the message EM_EXGETSEL.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_EXGETSEL, EM_SETSEL


EM_GETTHUMB

An application sends the EM_GETTHUMB message to retrieve the position of the scroll box (thumb) in a multiline edit control.

EM_GETTHUMB
wParam = 0;  // not used, must be zero
lParam = 0;  // not used, must be zero

Parameters

This message has no parameters.

Return Values

The return value is the position of the scroll box.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages


EM_GETWORDBREAKPROC

An application sends an EM_GETWORDBREAKPROC message to an edit control to retrieve the address of the current word wrap function.

EM_GETWORDBREAKPROC
wParam = 0; // not used; must be zero
lParam = 0; // not used; must be zero

Parameters

This message has no parameters.

Return Values

The return value specifies the address of the application-defined word wrap function. The return value is NULL if no word wrap function exists.

Remarks

A word wrap function scans a text buffer that contains text to be sent to the display, looking for the first word that does not fit on the current display line. The word wrap function places this word at the beginning of the next line on the display. A word wrap function defines the point at which the system should break a line of text for multiline edit controls, usually at a space character that separates two words.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EditWordBreakProc, EM_FMTLINES, EM_SETWORDBREAKPROC


EM_LIMITTEXT

An application sends an EM_LIMITTEXT message to limit the amount of text the user may enter into an edit control.

EM_LIMITTEXT
wParam = (WPARAM) cchMax;   // text length, in characters
lParam = 0;                 // not used; must be zero

Parameters

cchMax
Value of wParam. Specifies the maximum number of characters the user can enter. If this parameter is zero, the text length is set to 0x7FFFFFFE characters for single-line edit controls or 0xFFFFFFFF for multiline edit controls.

Return Values

This message does not return a value.

Remarks

The EM_LIMITTEXT message limits only the text the user can enter. It has no effect on any text already in the edit control when the message is sent, nor does it affect the length of the text copied to the edit control by the WM_SETTEXT message. If an application uses the WM_SETTEXT message to place more text into an edit control than is specified in the EM_LIMITTEXT message, the user can edit the entire contents of the edit control.

The default limit to the amount of text a user can enter in an edit control is 30,000 characters.

In a rich edit control, use the message EM_EXLIMITTEXT for text length values greater than 64K.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_EXLIMITTEXT, WM_SETTEXT


EM_LINEFROMCHAR

An application sends an EM_LINEFROMCHAR message to retrieve the index of the line that contains the specified character index in a multiline edit control. A character index is the number of characters from the beginning of the edit control.

EM_LINEFROMCHAR
wParam = (WPARAM) ich;  // character index
lParam = 0;             // not used; must be zero

Parameters

ich
Value of wParam. Specifies the character index of the character contained in the line whose number is to be retrieved. If the ich parameter is –1, either the line number of the current line (the line containing the caret) is retrieved or, if there is a selection, the line number of the line containing the beginning of the selection is retrieved.

Return Values

The return value is the zero-based line number of the line containing the character index specified by ich.

Remarks

In a rich edit control, if the character index is greater than 64K, use the message EM_EXLINEFROMCHAR.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_EXLINEFROMCHAR, EM_LINEINDEX


EM_LINEINDEX

An application sends an EM_LINEINDEX message to retrieve the character index of a line in a multiline edit control. The character index is the number of characters from the beginning of the edit control to the specified line.

EM_LINEINDEX
wParam = (WPARAM) line; // line number
lParam = 0;             // not used; must be zero

Parameters

line
Value of wParam. Specifies the zero-based line number. A value of –1 specifies the current line number (the line that contains the caret).

Return Values

The return value is the character index of the line specified in the line parameter, or it is –1 if the specified line number is greater than the number of lines in the edit control.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_LINEFROMCHAR


EM_LINELENGTH

An application sends an EM_LINELENGTH message to retrieve the length of a line, in characters, in an edit control.

EM_LINELENGTH
wParam = (WPARAM) ich;  // character index
lParam = 0;             // not used; must be zero

Parameters

ich
Value of wParam. Specifies the character index of a character in the line whose length is to be retrieved when EM_LINELENGTH is sent to a multiline edit control. If this parameter is –1, the message returns the number of unselected characters on lines containing selected characters. For example, if the selection extended from the fourth character of one line through the eighth character from the end of the next line, the return value would be 10 (three characters on the first line and seven on the next).

Return Values

The return value is the length, in characters, of the line specified by the ich parameter when an EM_LINELENGTH message is sent to a multiline edit control. The return value is the length, in characters, of the text in the edit control when an EM_LINELENGTH message is sent to a single-line edit control.

Remarks

Use the EM_LINEINDEX message to retrieve a character index for a given line number within a multiline edit control.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_LINEINDEX


EM_LINESCROLL

An application sends an EM_LINESCROLL message to scroll the text vertically or horizontally in a multiline edit control.

EM_LINESCROLL
wParam = (WPARAM) cxScroll; // characters to scroll horizontally
lParam = (LPARAM) cyScroll; // lines to scroll vertically

Parameters

cxScroll
Value of wParam. Specifies the number of characters to scroll horizontally.
cyScroll
Value of lParam. Specifies the number of lines to scroll vertically.

Return Values

If the message is sent to a multiline edit control, the return value is TRUE; if the message is sent to a single-line edit control, the return value is FALSE.

Remarks

The edit control does not scroll vertically past the last line of text in the edit control. If the current line plus the number of lines specified by the cyScroll parameter exceeds the total number of lines in the edit control, the value is adjusted so that the last line of the edit control is scrolled to the top of the edit-control window.

The EM_LINESCROLL message can be used to scroll horizontally past the last character of any line.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages


EM_POSFROMCHAR

An application sends the EM_POSFROMCHAR message to retrieve the coordinates of the specified character in an edit control.

EM_POSFROMCHAR
wParam = (WPARAM) wCharIndex;    // zero-based index of character
lParam = 0;                      // not used

Parameters

wCharIndex
Value of wParam. Specifies the zero-based index of the character.

Return Values

The return value is the position of the character, (x, y). For a single-line edit control, the y-coordinate is always zero.

Remarks

A returned coordinate can be negative if the character has been scrolled outside the edit control's client area. The coordinates are truncated to integer values.

If wCharIndex is the index of a line delimiter, the returned coordinates are of the position just past the last visible character in the line.

If wCharIndex is greater than the index of the last character in the control, the returned coordinates are of the position just past the last character of the control.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_CHARFROMPOS, POINTL


EM_REPLACESEL

An application sends an EM_REPLACESEL message to replace the current selection in an edit control with the specified text.

EM_REPLACESEL
fCanUndo = (BOOL) wParam ;        // flag that specifies whether replacement can be undone
lpszReplace = (LPCTSTR) lParam ;  // pointer to replacement text string

Parameters

fCanUndo
Value of wParam. Specifies whether the replacement operation can be undone. If this is TRUE, the operation can be undone. If this is FALSE , the operation cannot be undone.
lpszReplace
Value of lParam. Pointer to a null-terminated string containing the replacement text.

Return Values

This message does not return a value.

Remarks

Use the EM_REPLACESEL message to replace only a portion of the text in an edit control. To replace all of the text, use the WM_SETTEXT message.

If there is no current selection, the replacement text is inserted at the current location of the caret.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, WM_SETTEXT


EM_SCROLL

An application sends an EM_SCROLL message to scroll the text vertically in a multiline edit control. This message is equivalent to sending a WM_VSCROLL message to the edit control.

EM_SCROLL
wParam = (WPARAM) (INT) nScroll;    // scroll action
lParam = 0;                         // not used; must be zero

Parameters

nScroll
Value of wParam. Specifies the action the scroll bar is to take. This parameter may be one of the following values:
Value | Meaning
SB_LINEDOWN | Scrolls down one line.
SB_LINEUP | Scrolls up one line.
SB_PAGEDOWN | Scrolls down one page.
SB_PAGEUP | Scrolls up one page.

Return Values

If the message is successful, the high-order word of the return value is TRUE, and the low-order word is the number of lines that the command scrolls. The number returned may not be the same as the actual number of lines scrolled if the scrolling moves to the beginning or the end of the text. If the nScroll parameter specifies an invalid value, the return value is FALSE.

Remarks

An application should use the EM_LINESCROLL message to scroll to a specific line or character position.

An application should use the EM_SCROLLCARET message to scroll the caret into view.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_LINESCROLL, EM_SCROLLCARET, WM_VSCROLL


EM_SCROLLCARET

An application sends an EM_SCROLLCARET message to scroll the caret into view in an edit control.

EM_SCROLLCARET
wParam = 0 ;    // not used now; reserved for future use; must be zero
lParam = 0 ;    // not used now; reserved for future use;  must be zero

Parameters

wParam
This parameter is currently unused. It is reserved for future use. It should be set to zero.
lParam
This parameter is currently unused. It is reserved for future use. It should be set to zero.

Return Values

The return value is nonzero if the message is sent to an edit control.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_SETSEL


EM_SETHANDLE

An application sends an EM_SETHANDLE message to set the handle of the memory that will be used by a multiline edit control.

EM_SETHANDLE
wParam = (WPARAM) (HLOCAL) hloc; // handle of memory buffer
lParam = 0;                      // not used; must be zero

Parameters

hloc
Value of wParam. Handle to the memory the edit control uses to store the currently displayed text instead of allocating its own memory. If necessary, the control reallocates this memory.

Return Values

This message does not return a value.

Remarks

Before an application sets a new memory handle, it should send an EM_GETHANDLE message to retrieve the handle of the current memory buffer and should free that memory.

An edit control automatically reallocates the given buffer whenever it needs additional space for text, or it removes enough text so that additional space is no longer needed.

Sending an EM_SETHANDLE message clears the undo buffer (EM_CANUNDO returns zero) and the internal modification flag (EM_GETMODIFY returns zero). The edit control window is redrawn.

An application can send this message to a multiline edit control in a dialog box only if it has created the dialog box with the DS_LOCALEDIT style flag set.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Unsupported.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_CANUNDO, EM_GETHANDLE, EM_GETMODIFY


EM_SETIMESTATUS

[This is preliminary documentation and subject to change.]

An application sends the EM_SETIMESTATUS message to change the edit control's behavior with the IME.

EM_SETIMESTATUS
wParam = (WPARAM) status;
lParam = (LPARAM) data;

Parameters

status
Indicates the type of status to set. This parameter can be the following value.
Value | Meaning
EMSIS_COMPOSITIONSTRING | Sets behavior for the handling composition string.

data
Data specific to the type of status to set. With the EMSIS_COMPOSITIONSTRING value for status, this parameter can be a combination of the following values.
Value | Meaning
EIMES_GETCOMPSTRATONCE | If this flag is set, the edit control hooks the WM_IME_COMPOSITION message and returns the result string immediately. If this flag is not set, the edit control passes the WM_IME_COMPOSITION message to the default window procedure and handles the result string from the WM_CHAR message; this is the default behavior of the edit control.
EIMES_CANCELCOMPSTRINFOCUS | If this flag is set, the edit control cancels the composition string when it receives the WM_SETFOCUS message. If this flag is not set, the edit control does not cancel the composition string; this is the default behavior of the edit control.
EIMES_COMPLETECOMPSTRKILLFOCUS | If this flag is set, the edit control completes the composition string upon receiving the WM_KILLFOCUS message. If this flag is not set, the edit control does not complete the composition string; this is the default behavior of the edit control.

Return Values

Returns the previous value of the data parameter.

QuickInfo

Windows NT: Requires version 5.0 or later.
Windows: Requires Windows 98.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_GETIMESTATUS


EM_SETLIMITTEXT

An application sends the EM_SETLIMITTEXT message to set the text limit for an edit control. The text limit is the maximum amount of text, in bytes, that the edit control can contain. Remember that in the ANSI character set, each character is one byte, and in the Unicode character set, each character is two bytes.

EM_SETLIMITTEXT
wParam = (WPARAM) cchMax;    // new text limits, in characters
lParam = 0;                  // not used, must be zero

Parameters

cchMax
Value of wParam. Specifies the new text limit, in characters. If this parameter is 0, the system sets the maximum text limit. For more information, see Remarks.

Return Values

This message does not return a value.

Remarks

Windows NT: For single-line edit controls, the text limit is either 0x7FFFFFFE bytes or the value of the wParam parameter, whichever is smaller. For multiline edit controls, this value is either 0xFFFFFFFF bytes or the value of the wParam parameter, whichever is smaller.

Windows 95 and Windows 98: For single-line edit controls, the text limit is either 0x7FFE bytes or the value of the wParam parameter, whichever is smaller. For multiline edit controls, this value is either 0xFFFF bytes or the value of the wParam parameter, whichever is smaller.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_GETLIMITTEXT


EM_SETMARGINS

An application sends the EM_SETMARGINS message to set the widths of the left and right margins for an edit control. The message redraws the control to reflect the new margins.

EM_SETMARGINS
wParam = (WPARAM) fwMargin;                    // left and/or right margins
lParam = (LPARAM) MAKELONG(wLeft, wRight);     // width of left or right margins, in pixels

Parameters

fwMargin
Value of wParam. Specifies the margins to set. This parameter can be a combination of the following values:
Value | Meaning
EC_LEFTMARGIN | Sets the left margin.
EC_RIGHTMARGIN | Sets the right margin.
EC_USEFONTINFO | Uses information about the current font of the edit control to set the margins. For a single-line edit control, margins are set to the average width of characters in the font. For a multiline edit control, the right margin is set to the "A" width of the font (the distance added to the current position before drawing a character), and the left margin is set to the "C" width (the distance added to the current position to provide white space to the right of a character).

If EC_USEFONTINFO is specified, the lParam parameter is ignored.

wLeft
Value of the low-order word of lParam. Specifies the width of the left margin, in pixels. This value is ignored if fwMargin does not include EC_LEFTMARGIN or if EC_USEFONTINFO is specified.
wRight
Value of the high-order word of lParam. Specifies the width of the right margin, in pixels. This value is ignored if fwMargin does not include EC_RIGHTMARGIN or if EC_USEFONTINFO is specified.

Return Values

This message does not return a value.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_GETMARGINS


EM_SETMODIFY

An application sends an EM_SETMODIFY message to set or clear the modification flag for an edit control. The modification flag indicates whether the text within the edit control has been modified. It is automatically set whenever the user changes the text. An EM_GETMODIFY message can be sent to retrieve the value of the modification flag.

EM_SETMODIFY
wParam = (WPARAM) (UINT) fModified;    // modification flag
lParam = 0;                            // not used; must be zero

Parameters

fModified
Value of wParam. Specifies the new value for the modification flag. A value of TRUE indicates the text has been modified, and a value of FALSE indicates it has not been modified.

Return Values

This message does not return a value.

Remarks

In a rich edit control, objects created without the REO_DYNAMICSIZE flag will lock in their extents when the modify flag is set to FALSE.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_GETMODIFY, REOBJECT


EM_SETPASSWORDCHAR

An application sends an EM_SETPASSWORDCHAR message to set or remove the password character for a single-line edit control when the user types text. When a password character is set, that character is displayed in place of each character the user types.

EM_SETPASSWORDCHAR
wParam = (WPARAM) (UINT) ch;    // character to display
lParam = 0;                     // not used; must be zero

Parameters

ch
Value of wParam. Specifies the character to be displayed in place of the character typed by the user. If this parameter is zero, the characters typed by the user are displayed.

Return Values

This message does not return a value.

Remarks

When the EM_SETPASSWORDCHAR message is received by an edit control, the edit control redraws all visible characters by using the character specified by the ch parameter.

If the edit control is created with the ES_PASSWORD style, the default password character is set to an asterisk (*). This style is removed if an EM_SETPASSWORDCHAR message is sent with the ch parameter set to zero.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_GETPASSWORDCHAR


EM_SETREADONLY

An application sends an EM_SETREADONLY message to set or remove the read-only style (ES_READONLY) of an edit control.

EM_SETREADONLY
wParam = (WPARAM) (BOOL) fReadOnly;  // read-only flag
lParam = 0;                          // not used; must be zero

Parameters

fReadOnly
Value of wParam. Specifies whether to set or remove the ES_READONLY style. A value of TRUE sets the ES_READONLY style; a value of FALSE removes the ES_READONLY style.

Return Values

If the operation succeeds, the return value is nonzero; otherwise, it is zero.

Remarks

When an edit control has the ES_READONLY style, the user cannot change the text within the edit control.

To determine whether an edit control has the ES_READONLY style, use the GetWindowLong function with the GWL_STYLE flag.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, GetWindowLong


EM_SETRECT

An application sends an EM_SETRECT message to set the formatting rectangle of a multiline edit control. The formatting rectangle is the limiting rectangle of the text. The limiting rectangle is independent of the size of the edit control window. When the edit control is first created, the formatting rectangle is the same as the client area of the edit control window. By using the EM_SETRECT message, an application can make the formatting rectangle larger or smaller than the edit control window.

This message is processed only by multiline edit controls.

EM_SETRECT
wParam = 0;                         // not used; must be zero
lParam = (LPARAM) (LPRECT) lprc;    // address of new rectangle

Parameters

lprc
Value of lParam. Pointer to a RECT structure that specifies the new dimensions of the rectangle.

Return Values

This message does not return a value.

Remarks

The EM_SETRECT message causes the text of the edit control to be redrawn. To change the size of the formatting rectangle without redrawing the text, use the EM_SETRECTNP message.

If the edit control does not have a horizontal scroll bar, and the formatting rectangle is set to be larger than the edit control window, lines of text exceeding the width of the edit control window (but smaller than the width of the formatting rectangle) are clipped instead of wrapped.

If the edit control contains a border, the formatting rectangle is reduced by the size of the border. If you are adjusting the rectangle returned by an EM_GETRECT message, you must remove the size of the border before using the rectangle with the EM_SETRECT message.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_GETRECT, EM_SETRECTNP, RECT


EM_SETRECTNP

An application sends an EM_SETRECTNP message to set the formatting rectangle of a multiline edit control. The formatting rectangle is the limiting rectangle of the text. The limiting rectangle is independent of the size of the edit control window. When the edit control is first created, the formatting rectangle is the same as the client area of the edit control window. By using the EM_SETRECTNP message, an application can make the formatting rectangle larger or smaller than the edit control window.

The EM_SETRECTNP message is identical to the EM_SETRECT message, except that the edit control window is not redrawn.

This message is processed only by multiline edit controls.

EM_SETRECTNP
wParam = 0;                         // not used; must be zero
lParam = (LPARAM) (LPRECT) lprc;    // address of new rectangle

Parameters

lprc
Value of lParam. Pointer to a RECT structure that specifies the new dimensions of the rectangle.

Return Values

This message does not return a value.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_SETRECT, RECT


EM_SETSEL

An application sends an EM_SETSEL message to select a range of characters in an edit control.

EM_SETSEL
wParam = (WPARAM) (INT) nStart;    // starting position
lParam = (LPARAM) (INT) nEnd;      // ending position

Parameters

nStart
Value of wParam. Specifies the starting character position of the selection.
nEnd
Specifies the ending character position of the selection.

Return Values

This message does not return a value.

Remarks

In a rich edit control, if the selection is not entirely contained in the first 64K, use the message EM_EXSETSEL.

If the nStart parameter is 0 and the nEnd parameter is –1, all the text in the edit control is selected. If nStart is –1, any current selection is removed. The caret is placed at the end of the selection indicated by the greater of the two values nEnd and nStart.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_GETSEL, EM_REPLACESEL, EM_SCROLLCARET, EM_EXSETSEL


EM_SETTABSTOPS

An application sends an EM_SETTABSTOPS message to set the tab stops in a multiline edit control. When text is copied to the control, any tab character in the text causes space to be generated up to the next tab stop.

This message is processed only by multiline edit controls.

EM_SETTABSTOPS
wParam = (WPARAM) cTabs;               // number of tab stops
lParam = (LPARAM) (LPDWORD) lpdwTabs;  // tab stop array

Parameters

cTabs
Value of wParam. Specifies the number of tab stops contained in the lpdwTabs parameter. If this parameter is zero, the lpdwTabs parameter is ignored and default tab stops are set at every 32 dialog template units. If this parameter is 1, tab stops are set at every n dialog template units, where n is the distance pointed to by the ldpwTabs parameter. If the cTabs parameter is greater than 1, lpdwTabs points to an array of tab stops.
lpdwTabs
Value of lParam. Pointer to an array of unsigned integers specifying the tab stops, in dialog template units. If the cTabs parameter is 1, lpdwTabs points to an unsigned integer containing the distance between all tab stops, in dialog template units.

Return Values

If all the tabs are set, the return value is TRUE; otherwise, it is FALSE.

Remarks

The EM_SETTABSTOPS message does not automatically redraw the edit control window. If the application is changing the tab stops for text already in the edit control, it should call the InvalidateRect function to redraw the edit control window.

The values specified by the lpdwTabs parameter are in dialog template units, which 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.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, InvalidateRect, MapDialogRect


EM_SETWORDBREAKPROC

An application sends the EM_SETWORDBREAKPROC message to an edit control to replace the default word wrap function with an application-defined word wrap function.

EM_SETWORDBREAKPROC
wParam = 0;                                 // not used; must be zero
lParam = (LPARAM)(EDITWORDBREAKPROC)ewbprc; // function address

Parameters

ewbprc
Value of lParam. Specifies the address of the application-defined word wrap function. For more information about breaking lines, see the description of the EditWordBreakProc callback function.

Return Values

This message does not return a value.

Remarks

A word wrap function scans a text buffer that contains text to be sent to the screen, looking for the first word that does not fit on the current screen line. The word wrap function places this word at the beginning of the next line on the screen.

A word wrap function defines the point at which the system should break a line of text for multiline edit controls, usually at a space character that separates two words. Either a multiline or a single-line edit control might call this function when the user presses arrow keys in combination with the ctrl key to move the caret to the next word or previous word. The default word wrap function breaks a line of text at a space character. The application-defined function may define the word wrap to occur at a hyphen or a character other than the space character.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EditWordBreakProc, EM_FMTLINES, EM_GETWORDBREAKPROC


EM_UNDO

An application sends an EM_UNDO message to undo the last edit control operation.

EM_UNDO
wParam = 0; // not used; must be zero
lParam = 0; // not used; must be zero

Parameters

This message has no parameters.

Return Values

For a single-line edit control, the return value is always TRUE. For a multiline edit control, the return value is TRUE if the undo operation is successful, or FALSE if the undo operation fails.

Remarks

An undo operation can also be undone. For example, you can restore deleted text with the first EM_CANUNDO message, and remove the text again with a second EM_CANUNDO message as long as there is no intervening edit operation.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_CANUNDO


EN_CHANGE

The EN_CHANGE notification message is sent when the user has taken an action that may have altered text in an edit control. Unlike the EN_UPDATE notification message, this notification message is sent after the system updates the screen. The parent window of the edit control receives this notification message through the WM_COMMAND message.

EN_CHANGE
idEditCtrl = (int) LOWORD(wParam); // identifier of edit control
hwndEditCtrl = (HWND) lParam;      // handle of edit control

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EN_UPDATE, WM_COMMAND


EN_ERRSPACE

The EN_ERRSPACE notification message is sent when an edit control cannot allocate enough memory to meet a specific request. The parent window of the edit control receives this notification message through the WM_COMMAND message.

EN_ERRSPACE
idEditCtrl = (int) LOWORD(wParam); // identifier of edit control
hwndEditCtrl = (HWND) lParam;      // handle of edit control

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, WM_COMMAND


EN_HSCROLL

The EN_HSCROLL notification message is sent when the user clicks an edit control's horizontal scroll bar. The parent window of the edit control receives this notification message through the WM_COMMAND message. The parent window is notified before the screen is updated.

EN_HSCROLL
idEditCtrl = (int) LOWORD(wParam); // identifier of edit control
hwndEditCtrl = (HWND) lParam;      // handle of edit control

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EN_VSCROLL, WM_COMMAND


EN_KILLFOCUS

The EN_KILLFOCUS notification message is sent when an edit control loses the keyboard focus. The parent window of the edit control receives this notification message through the WM_COMMAND message.

EN_KILLFOCUS
idEditCtrl = (int) LOWORD(wParam); // identifier of edit control
wNotifyCode = HIWORD(wParam);      // notification code
hwndEditCtrl = (HWND) lParam;      // handle of edit control

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EN_SETFOCUS, WM_COMMAND


EN_MAXTEXT

The EN_MAXTEXT notification message is sent when the current text insertion has exceeded the specified number of characters for the edit control. The text insertion has been truncated.

This message is also sent when an edit control does not have the ES_AUTOHSCROLL style and the number of characters to be inserted would exceed the width of the edit control.

This message is also sent when an edit control does not have the ES_AUTOVSCROLL style and the total number of lines resulting from a text insertion would exceed the height of the edit control.

The parent window of the edit control receives this notification message through the WM_COMMAND message.

EN_MAXTEXT
idEditCtrl = (int) LOWORD(wParam); // identifier of edit control
hwndEditCtrl = (HWND) lParam;      // handle of edit control

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages


EN_SETFOCUS

The EN_SETFOCUS notification message is sent when an edit control receives the keyboard focus. The parent window of the edit control receives this notification message through the WM_COMMAND message.

EN_SETFOCUS
idEditCtrl = (int) LOWORD(wParam); // identifier of edit control
wNotifyCode = HIWORD(wParam);      // notification code
hwndEditCtrl = (HWND) lParam;      // handle of edit control

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EN_KILLFOCUS, WM_COMMAND


EN_UPDATE

The EN_UPDATE notification message is sent when an edit control is about to display altered text. This notification message is sent after the control has formatted the text, but before it displays the text. This makes it possible to resize the edit control window, if necessary. The parent window of the edit control receives this notification message through the WM_COMMAND message.

EN_UPDATE
idEditCtrl = (int) LOWORD(wParam); // identifier of edit control
hwndEditCtrl = (HWND) lParam;      // handle of edit control

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EN_CHANGE, WM_COMMAND


EN_VSCROLL

The EN_VSCROLL notification message is sent when the user clicks an edit control's vertical scroll bar. The parent window of the edit control receives this notification message through the WM_COMMAND message. The parent window is notified before the screen is updated.

EN_VSCROLL
idEditCtrl = (int) LOWORD(wParam); // identifier of edit control
hwndEditCtrl = (HWND) lParam;      // handle of edit control

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, EN_HSCROLL, WM_COMMAND


WM_COMMAND

The WM_COMMAND message is sent when the user selects a command item from a menu, when a control sends a notification message to its parent window, or when an accelerator keystroke is translated.

WM_COMMAND
wNotifyCode = HIWORD(wParam); // notification code
wID = LOWORD(wParam);         // item, control, or accelerator identifier
hwndCtl = (HWND) lParam;      // handle of control

Parameters

wNotifyCode
Value of the high-order word of wParam. Specifies the notification code if the message is from a control. If the message is from an accelerator, this parameter is 1. If the message is from a menu, this parameter is 0.
wID
Value of the low-order word of wParam. Specifies the identifier of the menu item, control, or accelerator.
hwndCtl
Value of lParam. Handle to the control sending the message if the message is from a control. Otherwise, this parameter is NULL.

Return Values

If an application processes this message, it should return zero.

Remarks

Accelerator keystrokes that select items from the window menu are translated into WM_SYSCOMMAND messages.

If an accelerator keystroke occurs that corresponds to a menu item when the window that owns the menu is minimized, no WM_COMMAND message is sent. However, if an accelerator keystroke occurs that does not match any of the items in the window's menu or in the window menu, a WM_COMMAND message is sent, even if the window is minimized.

If an application enables a menu separator, the system sends a WM_COMMAND message with the low-word of the wParam parameter set to zero when the user selects the separator.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, WM_SYSCOMMAND


WM_CTLCOLOREDIT

An edit control that is not read-only or disabled sends the WM_CTLCOLOREDIT 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 edit control.

WM_CTLCOLOREDIT
hdcEdit = (HDC) wParam;   // handle to display context
hwndEdit = (HWND) lParam; // handle to static control

Parameters

hdcEdit
Value of wParam. Handle to the device context for the edit control window.
hwndEdit
Value of lParam. Handle to the edit control.

Return Values

If an application processes this message, it must return the handle of a brush. The system uses the brush to paint the background of the edit control.

Default Action

The DefWindowProc function selects the default system colors for the edit control.

Remarks

Read-only or disabled edit controls do not send the WM_CTLCOLOREDIT message; instead, they send the WM_CTLCOLORSTATIC message. However, for compatibility purposes, the system sends the WM_CTLCOLOREDIT message for read-only and disabled edit controls if the application was designed for Windows 3.1 or earlier.

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_CTLCOLOREDIT message is never sent between threads, it is only sent 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.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, DefWindowProc, RealizePalette, SelectPalette, WM_CTLCOLORBTN, WM_CTLCOLORDLG, WM_CTLCOLORLISTBOX, WM_CTLCOLORMSGBOX, WM_CTLCOLORSCROLLBAR, WM_CTLCOLORSTATIC


WM_UNDO

An application sends a WM_UNDO message to an edit control to undo the last operation. When this message is sent to an edit control, the previously deleted text is restored or the previously added text is deleted.

WM_UNDO
wParam = 0; // not used; must be zero
lParam = 0; // not used; must be zero

Parameters

This message has no parameters.

Return Values

If the message succeeds, the return value is TRUE; otherwise, it is FALSE.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Edit Controls Overview, Edit Control Messages, WM_CLEAR, WM_COPY, WM_CUT, WM_PASTE


Edit Control Styles

To create an edit control using the CreateWindow or CreateWindowEx function, specify the EDIT class, appropriate window style constants, and a combination of the following edit control styles.

Style | Meaning
ES_AUTOHSCROLL | Automatically scrolls text to the right by 10 characters when the user types a character at the end of the line. When the user presses the enter key, the control scrolls all text back to position zero.
ES_AUTOVSCROLL | Automatically scrolls text up one page when the user presses the enter key on the last line.
ES_CENTER Windows NT 5.0 and later; Windows 98 and later: Centers text in a single-line or multiline edit control.

Earlier versions of Windows and Windows NT: Centers text in a multiline edit control.
ES_LEFT | Left-aligns text.
ES_LOWERCASE | Converts all characters to lowercase as they are typed into the edit control.
ES_MULTILINE | Designates a multiline edit control. The default is single-line edit control.
When the multiline edit control is in a dialog box, the default response to pressing the enter key is to activate the default button. To use the enter key as a carriage return, use the ES_WANTRETURN style.
When the multiline edit control is not in a dialog box and the ES_AUTOVSCROLL style is specified, the edit control shows as many lines as possible and scrolls vertically when the user presses the enter key. If you do not specify ES_AUTOVSCROLL, the edit control shows as many lines as possible and beeps if the user presses the enter key when no more lines can be displayed.
If you specify the ES_AUTOHSCROLL style, the multiline edit control automatically scrolls horizontally when the caret goes past the right edge of the control. To start a new line, the user must press the enter key. If you do not specify ES_AUTOHSCROLL, the control automatically wraps words to the beginning of the next line when necessary. A new line is also started if the user presses the enter key. The window size determines the position of the word wrap. If the window size changes, the word wrapping position changes and the text is redisplayed.
Multiline edit controls can have scroll bars. An edit control with scroll bars processes its own scroll bar messages. Note that edit controls without scroll bars scroll as described in the previous paragraphs and process any scroll messages sent by the parent window.
ES_NOHIDESEL | Negates the default behavior for an edit control. The default behavior hides the selection when the control loses the input focus and inverts the selection when the control receives the input focus. If you specify ES_NOHIDESEL, the selected text is inverted, even if the control does not have the focus.
ES_NUMBER | Allows only digits to be entered into the edit control.
ES_OEMCONVERT | Converts text entered in the edit control. The text is converted from the Windows character set to the OEM character set and then back to the Windows set. This ensures proper character conversion when the application calls the CharToOem function to convert a Windows string in the edit control to OEM characters. This style is most useful for edit controls that contain filenames.
ES_PASSWORD | Displays an asterisk (*) for each character typed into the edit control. You can use the EM_SETPASSWORDCHAR message to change the character that is displayed.
ES_READONLY | Prevents the user from typing or editing text in the edit control.
ES_RIGHT Windows NT 5.0 and later; Windows 98 and later: Right-aligns text in a single-line or multiline edit control.

Earlier versions of Windows and Windows NT: Right-aligns text in a multiline edit control.
ES_UPPERCASE | Converts all characters to uppercase as they are typed into the edit control.
ES_WANTRETURN | Specifies that a carriage return be inserted when the user presses the enter key while entering text into a multiline edit control in a dialog box. If you do not specify this style, pressing the enter key has the same effect as pressing the dialog box's default push button. This style has no effect on a single-line edit control.


List Boxes

The Microsoft® Win32® application programming interface (API) provides dialog boxes and controls to support communication between an application and the user. A list box is a control window that contains a list of items from which the user can choose.


About List Boxes

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 can provide a scroll bar. The user maneuvers through the list box items, scrolling the list when necessary, and selects or removes the selection from items. Selecting a list box item changes its visual appearance, usually by changing the text and background colors to the colors specified by the operating system metrics for selected items. When the user selects an item or removes the selection from 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. For more information about dialog boxes, see Dialog Boxes.

For general information about controls, see Controls.


List Box Types and Styles

The Win32 API provides 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 multiple-selection list box, the user can select more than one item at a time. To create a multiple-selection list box, specify the LBS_MULTIPLESEL or the LBS_EXTENDEDSEL style.

The Win32 API provides many other list box 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.

For a table of list box styles, see List Box Styles.


List Box Functions Overview

The Win32 API provides two functions specific to list boxes. The DlgDirList function fills a list box with the files and directories in a specified path. The DlgDirSelectEx function retrieves the current selection in a list box initialized by DlgDirList. These functions make it possible for the user to select a file from a list box without typing the location and name of the file.


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 low-order 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.


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.

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 0, the index of the second item is 1, 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 matches a given prefix.
LB_FINDSTRINGEXACT | Returns the index of the string that is equivalent to or prefixed by a given prefix.
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 32-bit value associated with the given item.
LB_GETITEMHEIGHT | Returns the height, in pixels, of an item in a list box.
LB_GETITEMRECT | Retrieves the client coordinates of the given list box item.
LB_GETLOCALE | Retrieves the locale of the list box. The high-order word contains the country code and the low-order 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 multiple-selection 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 given item and the length of the string.
LB_GETTEXTLEN | Returns the length, in characters, of the string associated with a given 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 given 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 given prefix.
LB_SELITEMRANGE | Selects a given range of items in a list box.
LB_SELITEMRANGEEX | Selects a given 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 given item.
LB_SETCARETINDEX | Sets the focus rectangle to a given 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 given list box item.
LB_SETHORIZONTALEXTENT | Sets the scrollable width, in pixels, of a list box.
LB_SETITEMDATA | Associates a 32-bit 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 given array.
LB_SETTOPINDEX | Scrolls the list box so the specified item is at the top of the visible range.


Default Window-Message Processing

The window procedure for the predefined list box window class carries out default processing for all messages that the list box does not process. When the list box procedure returns FALSE for a message, the predefined window procedure checks the message and performs default actions, as shown in the following table.

Message | Default action
WM_CHAR Moves the selection to the first item that begins with the character the user typed. If the list box has the LBS_OWNERDRAW style, no action occurs.

Multiple characters typed within a short interval are treated as a group, and the first item that begins with that series of characters is selected.
WM_CREATE | Creates an empty list box.
WM_DESTROY | Destroys the list box and frees any resources it uses.
WM_DROPFILES | Passes the message to the dialog box procedure or parent window process.
WM_ENABLE | If the control is visible, invalidates the rectangle so the strings can be painted gray.
WM_ERASEBKGND | Erases the background of a list box. If the list box has the LBS_OWNERDRAW style, the background is not erased.
WM_GETDLGCODE | Returns DLGC_WANTARROWS | DLGC_WANTCHARS, indicating the default list box procedure processes the arrow keys and WM_CHAR messages.
WM_GETFONT | Returns a handle to the current font for the list box.
WM_HSCROLL | Scrolls the list box horizontally.
WM_KEYDOWN | Processes virtual keys for scrolling. The virtual key is the index of the item to move the caret to. The selection is not changed.
WM_KILLFOCUS | Turns the caret off and destroys it. Sends an LBN_KILLFOCUS notification message to the owner of the list box.
WM_LBUTTONDBLCLK | Tracks the mouse in the list box client area. This enables the user to cancel a selection if the mouse button is released outside the list box client area.
WM_LBUTTONDOWN | Tracks the mouse in the list box client area. This enables the user to cancel a selection if the mouse button is released outside the list box client area.
WM_LBUTTONUP | Tracks the mouse in the list box client area. This enables the user to cancel a selection if the mouse button is released outside the list box client area.
WM_MOUSEMOVE | Tracks the mouse in the list box client area. This enables the user to cancel a selection if the mouse button is released outside the list box client area.
WM_PAINT | Performs a subclassed paint operation by using the list box handle to the device context (DC).
WM_SETFOCUS | Turns the caret on and sends an LBN_SETFOCUS notification message to the owner of the list box.
WM_SETFONT | Sets a new font for the list box.
WM_SETREDRAW | Sets or clears the redraw flag based on the value of wParam.
WM_SIZE | Resizes the list box to an integral number of items.
WM_VSCROLL | Scrolls the list box vertically.

The predefined list box procedure passes all other messages to DefWindowProc for default processing.


Owner-Drawn List Boxes

An application can create an owner-drawn list box to take responsibility for painting list items. The parent window or dialog box of an owner-drawn list box (its owner) receives WM_DRAWITEM messages when a portion of the list box needs to be painted. An owner-drawn list box can list information other than, or in addition to, text strings.

The owner of an owner-drawn list box must process the WM_DRAWITEM message. This message is sent whenever a portion of the list box must be redrawn. The owner may need to process other messages, depending on the styles specified for the list box.

An application can create an owner-drawn list box by specifying the LBS_OWNERDRAWFIXED or LBS_OWNERDRAWVARIABLE style. If all list items in the list box are the same height, such as strings or icons, an application can use the LBS_OWNERDRAWFIXED style. If list items are of varying height, bitmaps of different size, for example, an application can use the LBS_OWNERDRAWVARIABLE style.

The owner of an owner-drawn list box can process a WM_MEASUREITEM message to specify the dimensions of list items. If the application creates the list box by using the LBS_OWNERDRAWFIXED style, the system sends the WM_MEASUREITEM message only once. The dimensions specified by the owner are used for all list items. If the LBS_OWNERDRAWVARIABLE style is used, the system sends a WM_MEASUREITEM message for each list item added to the list box. The owner can determine or set the height of a list item at any time by using the LB_GETITEMHEIGHT and LB_SETITEMHEIGHT messages, respectively.

If the information displayed in an owner-drawn list box includes text, an application can keep track of the text for each list item by specifying the LBS_HASSTRINGS style. List boxes with the LBS_SORT style are sorted based on this text. If a list box is sorted, but is not of the LBS_HASSTRINGS style, the owner must process the WM_COMPAREITEM message.

In an owner-drawn list box, the owner must keep track of list items containing information other than or in addition to text. One convenient way to do this is to save the handle to the information as item data using the LB_SETITEMDATA message. To free data objects associated with items in a list box, the owner can process the WM_DELETEITEM message.

For an example of an owner-drawn list box, see Creating an Owner-Drawn List Box.


Using List Boxes

  • Creating a simple list box
  • Creating a directory listing in a single-selection list box
  • Creating a multiple-selection list box
  • Creating an owner-drawn list box


Creating a Simple List Box

The following example demonstrates how a dialog box procedure creates a simple list box and fills it with the names of people on a softball team. When a name in the list is selected, additional information about the player is displayed in the dialog box. The following illustration shows the dialog box.

The list box has the LBS_STANDARD style, a combination of LBS_SORT, LBS_NOTIFY, WS_VSCROLL, and WS_BORDER. The code initializes the dialog box while processing the WM_INITDIALOG message. For each name that appears in the list box, the code sends an LB_ADDSTRING message to the list box. By processing the LBN_SELCHANGE notification message, the code also keeps track of when the selection changes.

#define BUFFER MAX_PATH

#define NAMELENGTH 15
#define POSITIONLENGTH 20
#define TEAMSIZE 15

typedef struct
{
    TCHAR tchName[NAMELENGTH];
    TCHAR tchPosition[POSITIONLENGTH];
    int nGamesPlayed;
    int nInningsPlayed;
    double xBattingAverage;
    TCHAR tchFoodName[NAMELENGTH];
} Player;

Player Roster[] =
{
        {"Alan", "Center field", 17, 56, .375, "Cannelloni"},
        {"Colin", "Pitcher", 26, 96, .456, "Lefse"},
        {"Cindy", "Second base", 13, 58, .207, "Tequila"},
        {"Dave", "First base", 28, 138, .508, "Suds"},
        {"David", "Center field", 18, 101, .612, "Bok Choy"}
        {"Jack", "Pitcher", 27, 110, .542, "Animal Crackers"},
        {"Julie", "Right field", 22, 101, .509, "Mashed Potatoes"},
        {"Karen", "Second base", 26, 140, .238, "Pez"},
        {"Kathie", "Left field", 26, 127, .353, "Baba Ganouj"},
        {"Matt", "Shortstop", 24, 112, .579, "Oats"},
        {"Miriam", "Right field", 24, 112, .393, "Zotz"},
        {"Pete", "Shortstop", 26, 90, .608, "Beet"},
        {"Seth", "Center field", 20, 76, .407, "Otter Pop"},
        {"Suzanna", "Catcher", 16, 53, .286, "Toast"},
        {"Wendy", "Third base", 25, 154, .493, "Ham"},
    };

BOOL APIENTRY DlgTeamProc(
    HWND hDlg,            // window handle to dialog box
    UINT message,         // type of message
    UINT wParam,          // message-specific information
    LONG lParam)          // message-specific information
{
    TCHAR tchBuffer[BUFFER];
    int nItem;
    int i;
    HWND hwndList;

    switch (message)
    {
        case WM_INITDIALOG:
        {
            hwndList = GetDlgItem(hDlg, IDL_SOFTBALL);

            // Initialize the list box (fill it with player names).

            for (i = 0; i < TEAMSIZE; i++)
            {
                SendMessage(hwndList, LB_ADDSTRING, 0,
                    (LPARAM) Roster[i].tchName);
                SendMessage(hwndList, LB_SETITEMDATA, i, (LPARAM) i);
            }
            SetFocus(hwndList);
            return FALSE;
        }

        case WM_COMMAND:
            switch (LOWORD(wParam))
            {
                case IDL_SOFTBALL:
                    switch (HIWORD(wParam))
                    {
                        case LBN_SELCHANGE:

                           // Show the selected player's statistics.

                           hwndList = GetDlgItem(hDlg, IDL_SOFTBALL);
                           nItem = SendMessage(hwndList, LB_GETCURSEL,
                               0, 0);
                           i = SendMessage(hwndList, LB_GETITEMDATA,
                               nItem, 0);

                           SetDlgItemText(hDlg, IDS_POS,
                               Roster[i].tchPosition);
                           SetDlgItemText(hDlg, IDS_GAME,
                               _itoa(Roster[i].nGamesPlayed,
                               tchBuffer, 10));
                           SetDlgItemText(hDlg, IDS_INN,
                               _itoa(Roster[i].nInningsPlayed,
                               tchBuffer, 10));
                           SetDlgItemText(hDlg, IDS_BA,
                               _gcvt(Roster[i].xBattingAverage,
                               3, tchBuffer));
                           SetDlgItemText(hDlg, IDS_FOOD,
                               Roster[i].tchFoodName);

                           return TRUE;
                   }
                   break;

                case IDOK:
                case IDCANCEL:

                  // Destroy the dialog box.

                  EndDialog(hDlg, TRUE);
                  return TRUE;

                default:
                  return FALSE;
            }

        default:
            return FALSE;
    }
}


Creating a Directory Listing in a Single-Selection List Box

The following example demonstrates how to display the content of the current directory in a list box and enable the user to delete one file at a time.

In addition to the standard list box styles, this list box has the LBS_MULTICOLUMN and LBS_HSCROLL styles. The code initializes the list box by using the DlgDirList function to fill the list box with the names of all the files in the current directory. When the user chooses the Delete button, the DlgDirSelectEx function retrieves the name of the selected file. The code deletes the file by using the DeleteFile function and updates the directory list box by sending the LB_DELETESTRING message.

#define BUFFER MAX_PATH

BOOL APIENTRY DlgDelFileProc(
    HWND hDlg,            // window handle to dialog box
    UINT message,         // type of message
    UINT wParam,          // message-specific information
    LONG lParam)
{

    DWORD cchCurDir;
    LPTSTR lpszCurDir;
    LPTSTR lpszFileToDelete;
    int nItem;
    int nTotal;
    TCHAR tchBuffer[BUFFER];
    BOOL fResult;

    switch (message)
    {
        case WM_INITDIALOG:

           // Initialize the list box by filling it with files from
           // the current directory.

           lpszCurDir = tchBuffer;
           GetCurrentDirectory(cchCurDir, lpszCurDir);
           DlgDirList(hDlg, lpszCurDir, IDL_FILES, IDS_PATHTOFILL, 0);
           SetFocus(GetDlgItem(hDlg, IDL_FILES));
           return FALSE;

        case WM_COMMAND:

            switch (LOWORD(wParam))
            {
                case IDOK:

                    // When the user presses the DEL (IDOK) button,
                    // delete the selected file.

                    lpszFileToDelete = tchBuffer;

                    DlgDirSelectEx(hDlg, lpszFileToDelete, MAX_PATH,
                        IDL_FILES);
                    fResult = DeleteFile(lpszFileToDelete);
                    if (!fResult)
                    {
                        MessageBox(hDlg, "Could not delete file.",
                            NULL, MB_OK);
                    }
                    else
                    {
                        nItem = SendMessage(GetDlgItem(hDlg,
                                IDL_FILES), LB_GETCURSEL, 0, 0);

                        nTotal = SendMessage(GetDlgItem(hDlg,
                            IDL_FILES), LB_DELETESTRING, nItem, 0);

                        // Update the list box.

                        if (nTotal > nItem)
                        {
                            SendMessage(GetDlgItem(hDlg, IDL_FILES),
                                LB_SETCURSEL, nItem, 0);
                        }
                        else
                        {
                            SendMessage(GetDlgItem(hDlg, IDL_FILES),
                                LB_SETCURSEL, nTotal, 0);
                        }
                    }
                    return TRUE;

                case IDCANCEL:

                    // Destroy the dialog box.

                    EndDialog(hDlg, TRUE);
                    return TRUE;

                default:
                    return FALSE;
            }

        default:
            return FALSE;
    }
}


Creating a Multiple-Selection List Box

The following example displays and initializes the dialog box used in the preceding example. However, this code uses the LBS_MULTIPLESEL style to enable the user to select more than one file at a time. When the user chooses the Delete button, the example sends the LB_GETSELCOUNT message (to retrieve the number of files selected) and the LB_GETSELITEMS message (to retrieve an array of selected list box items). After deleting a file, the code removes the corresponding item from the list box by sending the LB_DELETESTRING message.

#define BUFFER MAX_PATH

#define BIGBUFF 8192

BOOL APIENTRY DlgDelFilesProc(
    HWND hDlg,            // window handle to dialog box
    UINT message,         // type of message
    UINT wParam,          // message-specific information
    LONG lParam)
{
    DWORD cchCurDir;
    LPTSTR lpszCurDir;
    LPTSTR lpszFileToDelete;
    int nSelItems;
    int nSelItemsInBuffer;
    TCHAR tchBuffer[BUFFER];
    TCHAR tchMsgBuff[BUFFER];
    int nBuffer[BIGBUFF];
    int i;
    BOOL fResult;
    HWND hListBox;

    switch (message) {

        case WM_INITDIALOG:

           // Initialize the list box by filling it with files from
           // the current directory.

           lpszCurDir = tchBuffer;
           GetCurrentDirectory(cchCurDir, lpszCurDir);
           DlgDirList(hDlg, lpszCurDir, IDL_FILES, IDS_PATHTOFILL, 0);

           SetFocus(GetDlgItem(hDlg, IDL_FILES));

           return FALSE;

        case WM_COMMAND:

            switch (LOWORD(wParam))
            {
                case IDOK:

                    // When the user presses the Delete (IDOK)
                    // button, delete all the selected files.

                    lpszFileToDelete = tchBuffer;

                    hListBox = GetDlgItem(hDlg, IDL_FILES);
                    nSelItems = SendMessage(hListBox,
                            LB_GETSELCOUNT, 0, 0);

                    nSelItemsInBuffer = SendMessage(hListBox,
                            LB_GETSELITEMS, 512, (LPARAM) nBuffer);

                    if (nSelItems > nSelItemsInBuffer)
                    {
                        MessageBox(hDlg, "Too many items selected.",
                                NULL, MB_OK);
                    }
                    else
                    {
                        // Go through the list backwards because after
                        // deleting an item the indices change for
                        // every subsequent item. By going backward,
                        // the indices are never invalidated.

                        for (i = nSelItemsInBuffer - 1; i >= 0; i--)
                        {
                            SendMessage(hListBox, LB_GETTEXT,
                                        nBuffer[i],
                                        (LPARAM) lpszFileToDelete);

                            fResult = DeleteFile(lpszFileToDelete);
                            if (!fResult)
                            {
                                sprintf(tchMsgBuff,
                                        "Could not delete file: %s "
                                        "GetLastError = %u",
                                        (LPARAM) lpszFileToDelete);

                                // Call app-defined error handler.

                                ErrorHandler(tchMsgBuff);
                            }
                            else
                            {
                                SendMessage(hListBox, LB_DELETESTRING,
                                        nBuffer[i], 0);
                            }
                        }
                        SendMessage(hListBox, LB_SETCARETINDEX, 0, 0);
                    }
                    return TRUE;

                case IDCANCEL:

                    // Destroy the dialog box.

                    EndDialog(hDlg, TRUE);
                    return TRUE;

                default:
                    return FALSE;
            }

        default:
                return FALSE;
    }
}


Creating an Owner-Drawn List Box

The following example shows how to draw a list box that contains five owner-drawn items: four drawing implements and a fork. Each list item appears as a bitmap followed by the name of the object. A button prompts the user to select one item that is not like the others. Choosing the button with the fork selected displays a "You're right!" message and closes the dialog box. Choosing the button with any other list item selected displays a "Try again!" message.

The list box has the LBS_OWNERDRAW and LBS_HASSTRINGS styles, in addition to the standard list box styles. The code initializes the list box by sending the LB_ADDSTRING message to set the text, and then sends the LB_SETITEMDATA message to associate a bitmap with each list box item. The code also sets the height of each list box item by processing the WM_MEASUREITEM message and draws the text and bitmap for each item by processing the WM_DRAWITEM message.

#define XBITMAP 80
#define YBITMAP 20

#define BUFFER MAX_PATH

HBITMAP hbmpPencil, hbmpCrayon, hbmpMarker, hbmpPen, hbmpFork;
HBITMAP hbmpPicture, hbmpOld;

void AddItem(HWND hwnd, LPSTR lpstr, HBITMAP hbmp)
{
    int nItem;

    nItem = SendMessage(hwndList, LB_ADDSTRING, 0, lpstr);
    SendMessage(hwndList, LB_SETITEMDATA, nItem, hbmp);
}

DWORD APIENTRY DlgDrawProc(
        HWND hDlg,            // window handle to dialog box
        UINT message,         // type of message
        UINT wParam,          // message-specific information
        LONG lParam)
{
    int nItem;
    TCHAR tchBuffer[BUFFER];
    HBITMAP hbmp;
    HWND hListBox;
    TEXTMETRIC tm;
    int y;
    HDC hdcMem;
    LPMEASUREITEMSTRUCT lpmis;
    LPDRAWITEMSTRUCT lpdis;
    RECT rcBitmap;

    switch (message)
    {

        case WM_INITDIALOG:

            // Load bitmaps.

            hbmpPencil = LoadBitmap(hinst, MAKEINTRESOURCE(700));
            hbmpCrayon = LoadBitmap(hinst, MAKEINTRESOURCE(701));
            hbmpMarker = LoadBitmap(hinst, MAKEINTRESOURCE(702));
            hbmpPen = LoadBitmap(hinst, MAKEINTRESOURCE(703));
            hbmpFork = LoadBitmap(hinst, MAKEINTRESOURCE(704));

            // Retrieve list box handle.

            hListBox = GetDlgItem(hDlg, IDL_STUFF);

            // Initialize the list box text and associate a bitmap
            // with each list box item.

            AddItem(hListBox, "pencil", hbmpPencil);
            AddItem(hListBox, "crayon", hbmpCrayon);
            AddItem(hListBox, "marker", hbmpMarker);
            AddItem(hListBox, "pen",    hbmpPen);
            AddItem(hListBox, "fork",   hbmpFork);

            SetFocus(hListBox);
            SendMessage(hListBox, LB_SETCURSEL, 0, 0);
            return TRUE;

        case WM_MEASUREITEM:

            lpmis = (LPMEASUREITEMSTRUCT) lParam;

            // Set the height of the list box items.

            lpmis->itemHeight = 20;
            return TRUE;

        case WM_DRAWITEM:

            lpdis = (LPDRAWITEMSTRUCT) lParam;

            // If there are no list box items, skip this message.

            if (lpdis->itemID == -1)
            {
                break;
            }

            // Draw the bitmap and text for the list box item. Draw a
            // rectangle around the bitmap if it is selected.

            switch (lpdis->itemAction)
            {
                case ODA_SELECT:
                case ODA_DRAWENTIRE:

                    // Display the bitmap associated with the item.

                    hbmpPicture =(HBITMAP)SendMessage(lpdis->hwndItem,
                        LB_GETITEMDATA, lpdis->itemID, (LPARAM) 0);

                    hdcMem = CreateCompatibleDC(lpdis->hDC);
                    hbmpOld = SelectObject(hdcMem, hbmpPicture);

                    BitBlt(lpdis->hDC,
                        lpdis->rcItem.left, lpdis->rcItem.top,
                        lpdis->rcItem.right - lpdis->rcItem.left,
                        lpdis->rcItem.bottom - lpdis->rcItem.top,
                        hdcMem, 0, 0, SRCCOPY);

                    // Display the text associated with the item.

                    SendMessage(lpdis->hwndItem, LB_GETTEXT,
                        lpdis->itemID, (LPARAM) tchBuffer);

                    GetTextMetrics(lpdis->hDC, &tm);

                    y = (lpdis->rcItem.bottom + lpdis->rcItem.top -
                        tm.tmHeight) / 2;

                    TextOut(lpdis->hDC,
                        XBITMAP + 6,
                        y,
                        tchBuffer,
                        strlen(tchBuffer));

                    SelectObject(hdcMem, hbmpOld);
                    DeleteDC(hdcMem);

                    // Is the item selected?

                    if (lpdis->itemState & ODS_SELECTED)
                    {
                        // Set RECT coordinates to surround only the
                        // bitmap.

                        rcBitmap.left = lpdis->rcItem.left;
                        rcBitmap.top = lpdis->rcItem.top;
                        rcBitmap.right = lpdis->rcItem.left + XBITMAP;
                        rcBitmap.bottom = lpdis->rcItem.top + YBITMAP;

                        // Draw a rectangle around bitmap to indicate
                        // the selection.

                        DrawFocusRect(lpdis->hDC, &rcBitmap);
                    }
                    break;

                case ODA_FOCUS:

                    // Do not process focus changes. The focus caret
                    // (outline rectangle) indicates the selection.
                    // The IDOK button indicates the final
                    // selection.

                    break;
            }
            return TRUE;

        case WM_COMMAND:

            switch (LOWORD(wParam))
            {
                case IDOK:
                    // Get the selected item's text.

                    nItem = SendMessage(GetDlgItem(hDlg, IDL_STUFF),
                       LB_GETCURSEL, 0, (LPARAM) 0);
                       hbmp = SendMessage(GetDlgItem(hDlg, IDL_STUFF),
                            LB_GETITEMDATA, nItem, 0);

                    // If the item is not the correct answer, tell the
                    // user to try again.
                    //
                    // If the item is the correct answer, congratulate
                    // the user and destroy the dialog box.

                    if (hbmp != hbmpFork)
                    {
                        MessageBox(hDlg, "Try again!", "Oops", MB_OK);
                        return FALSE;
                    }
                    else
                    {
                        MessageBox(hDlg, "You're right!",
                            "Congratulations.", MB_OK);

                      // Fall through.

                    }

                case IDCANCEL:

                    // Destroy the dialog box.

                    EndDialog(hDlg, TRUE);
                    return TRUE;

                default:

                    return FALSE;
            }

        case WM_DESTROY:

            // Free any resources used by the bitmaps.

            DeleteObject(hbmpPencil);
            DeleteObject(hbmpCrayon);
            DeleteObject(hbmpMarker);
            DeleteObject(hbmpPen);
            DeleteObject(hbmpFork);

            return TRUE;

        default:
            return FALSE;

    }
    return FALSE;
}


List Box Reference

The following elements are associated with list boxes.

  • List Box Functions
  • List Box Structures
  • List Box Messages


List Box Functions

The following functions are used with list boxes.

DlgDirList
DlgDirSelectEx


DlgDirList

The DlgDirList function fills the specified list box with the names of all files matching the specified path or filename.

int DlgDirList(
  HWND hDlg,          // handle to dialog box with list box
  LPTSTR lpPathSpec,  // pointer to path or filename string
  int nIDListBox,     // identifier of list box
  int nIDStaticPath,  // identifier of static control
  UINT uFileType      // file attributes to display
);

Parameters

hDlg
Handle to the dialog box that contains the list box.
lpPathSpec
Pointer to a null-terminated string that contains the path or filename. DlgDirList modifies this string, which should be long enough to contain the modifications. For more information about this parameter, see the Remarks section.
nIDListBox
Specifies the identifier of a list box. If this parameter is zero, DlgDirList assumes that no list box exists and does not attempt to fill one.
nIDStaticPath
Specifies the identifier of the static control used for displaying the current drive and directory. If this parameter is zero, DlgDirList assumes that no such control is present.
uFileType
Specifies attributes of the filenames to be displayed. This parameter must be one or more of the following values:
Value | Description
DDL_ARCHIVE | Includes archived files.
DDL_DIRECTORY | Includes subdirectories. Subdirectory names are enclosed in square brackets ([ ]).
DDL_DRIVES | Includes drives. Drives are listed in the form [-x-], where x is the drive letter.
DDL_EXCLUSIVE | Includes only files with the specified attributes. By default, read-write files are listed even if DDL_READWRITE is not specified.
DDL_HIDDEN | Includes hidden files.
DDL_READONLY | Includes read-only files.
DDL_READWRITE | Includes read-write files with no additional attributes.
DDL_SYSTEM | Includes system files.
DDL_POSTMSGS | Posts messages to the application's message queue. By default, DlgDirList sends messages directly to the dialog box procedure.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. For example, if the string specified by lpPathSpec is not a valid path, the function fails. To get extended error information, call GetLastError.

Remarks

If you specify a zero-length string for the lpPathSpec parameter or if you specify only a directory name with no filename, the string will be changed to *.*

The lpPathSpec parameter has the following form:

[drive:] [[\u]directory[\i directory]\u] [filename]

In this example, drive is a drive letter, directory is a valid directory name, and filename is a valid filename that must contain at least one wildcard (? or *).

If lpPathSpec includes a drive or directory name, or both, the current drive and directory are changed to the specified drive and directory before the list box is filled. The static control identified by the nIDStaticPath parameter is also updated with the new drive or directory name, or both.

After the list box is filled, DlgDirList updates lpPathSpec by removing the drive or directory portion, or both, of the path and filename.

DlgDirList sends the LB_RESETCONTENT and LB_DIR messages to the list box.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

List Boxes Overview, List Box Functions, DlgDirListComboBox, DlgDirSelectComboBoxEx, DlgDirSelectEx


List Box Structures

The following structure is used with list boxes.

DELETEITEMSTRUCT


DELETEITEMSTRUCT

The DELETEITEMSTRUCT structure describes a deleted list box or combo box item. The lParam parameter of a WM_DELETEITEM message contains a pointer to this structure. When an item is removed from a list box or combo box or when a list box or combo box is destroyed, the system sends the WM_DELETEITEM message to the owner for each deleted item.

Windows NT: The system sends a WM_DELETEITEM message only for items deleted from an owner-drawn list box (with the LBS_OWNERDRAWFIXED or LBS_OWNERDRAWVARIABLE style) or owner-drawn combo box (with the CBS_OWNERDRAWFIXED or CBS_OWNERDRAWVARIABLE style).

Windows 95 and Windows 98: The system sends the WM_DELETEITEM message for any deleted list box or combo box item with nonzero item data.

typedef struct tagDELETEITEMSTRUCT { // ditms
    UINT CtlType;
    UINT CtlID;
    UINT itemID;
    HWND hwndItem;
    UINT itemData;
} DELETEITEMSTRUCT;

Members

CtlType
Specifies one of the following values to indicate whether the item was deleted from a list box or a combo box:
Value | Meaning
ODT_LISTBOX | A list box.
ODT_COMBOBOX | A combo box.

CtlID
Specifies the identifier of the list box or combo box.
itemID
Specifies index of the item in the list box or combo box being removed.
hwndItem
Handle to the control.
itemData
Specifies application-defined data for the item. This value is passed to the control in the lParam parameter of the message that adds the item to the list box or combo box.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Structures, WM_DELETEITEM


List Box Messages

The following messages are used with list boxes.

LB_ADDFILE
LB_ADDSTRING
LB_DELETESTRING
LB_DIR
LB_FINDSTRING
LB_FINDSTRINGEXACT
LB_GETANCHORINDEX
LB_GETCARETINDEX
LB_GETCOUNT
LB_GETCURSEL
LB_GETHORIZONTALEXTENT
LB_GETITEMDATA
LB_GETITEMHEIGHT
LB_GETITEMRECT
LB_GETLOCALE
LB_GETSEL
LB_GETSELCOUNT
LB_GETSELITEMS
LB_GETTEXT
LB_GETTEXTLEN
LB_GETTOPINDEX
LB_INITSTORAGE
LB_INSERTSTRING
LB_ITEMFROMPOINT
LB_RESETCONTENT
LB_SELECTSTRING
LB_SELITEMRANGE
LB_SELITEMRANGEEX
LB_SETANCHORINDEX
LB_SETCARETINDEX
LB_SETCOLUMNWIDTH
LB_SETCOUNT
LB_SETCURSEL
LB_SETHORIZONTALEXTENT
LB_SETITEMDATA
LB_SETITEMHEIGHT
LB_SETLOCALE
LB_SETSEL
LB_SETTABSTOPS
LB_SETTOPINDEX
LBN_DBLCLK
LBN_ERRSPACE
LBN_KILLFOCUS
LBN_SELCANCEL
LBN_SELCHANGE
LBN_SETFOCUS
WM_CHARTOITEM
WM_CTLCOLORLISTBOX
WM_DELETEITEM
WM_VKEYTOITEM


LB_ADDFILE

An application sends an LB_ADDFILE message to add the specified filename to a list box that contains a directory listing.

LB_ADDFILE
wParam = 0;                               // not used; must be zero
lParam = (LPARAM) (LPCTSTR) lpszFilename; // name of file to add

Parameters

lpszFilename
Value of lParam. Pointer to the name of the file to add.

Return Values

The return value is the zero-based index of the file that was added, or LB_ERR if an error occurs.

Remarks

The list box to which lpszFilename is added must have been filled by the DlgDirList function.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, DlgDirList, LB_ADDSTRING


LB_ADDSTRING

An application sends an LB_ADDSTRING message to add a string to a list box. If the list box does not have the LBS_SORT style, the string is added to the end of the list. Otherwise, the string is inserted into the list and the list is sorted.

LB_ADDSTRING
wParam = 0;                         // not used; must be zero
lParam = (LPARAM) (LPCTSTR) lpsz;   // address of string to add

Parameters

lpsz
Value of lParam. Pointer to the null-terminated string that is to be added.

If you create the list box with an owner-drawn style but without the LBS_HASSTRINGS style, the value of the lpsz parameter is stored as item data instead of the string it would otherwise point to. You can send the LB_GETITEMDATA and LB_SETITEMDATA messages to retrieve or modify the item data.

Return Values

The return value is the zero-based index of the string in the list box. If an error occurs, the return value is LB_ERR. If there is insufficient space to store the new string, the return value is LB_ERRSPACE.

Remarks

If you create an owner-drawn list box with the LBS_SORT style but not the LBS_HASSTRINGS style, the system sends the WM_COMPAREITEM message one or more times to the owner of the list box to place the new item properly in the list box.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_DELETESTRING, LB_INSERTSTRING, LB_SELECTSTRING, WM_COMPAREITEM


LB_DELETESTRING

An application sends an LB_DELETESTRING message to delete a string in a list box.

LB_DELETESTRING
wParam = (WPARAM) index;    // index of string to delete
lParam = 0;                 // not used; must be zero

Parameters

index
Value of wParam. Specifies the zero-based index of the string to be deleted.

Windows 95 and Windows 98: The wParam parameter is limited to 16-bit values. This means list boxes cannot contain more than 32,767 items. Although the number of items is restricted, the total size in bytes of the items in a list box is limited only by available memory.

Return Values

The return value is a count of the strings remaining in the list. The return value is LB_ERR if the index parameter specifies an index greater than the number of items in the list.

Remarks

If an application creates the list box with an owner-drawn style but without the LBS_HASSTRINGS style, the system sends a WM_DELETEITEM message to the owner of the list box so the application can free any additional data associated with the item.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_ADDSTRING, LB_INSERTSTRING, WM_DELETEITEM


LB_DIR

An application sends an LB_DIR message to add a list of filenames to a list box.

LB_DIR
wParam = (WPARAM) (UINT) uAttrs;          // file attributes
lParam = (LPARAM) (LPCTSTR) lpszFileSpec; // filename address

Parameters

uAttrs
Value of wParam. Specifies the attributes of the files to be added to the list box. This parameter can be a combination of the following values:
Value | Description
DDL_ARCHIVE | Includes archived files.
DDL_DIRECTORY | Includes subdirectories. Subdirectory names are enclosed in square brackets ([ ]).
DDL_DRIVES | Includes drives. Drives are listed in the form [-x-], where x is the drive letter.
DDL_EXCLUSIVE | Includes only files with the specified attributes. By default, read-write files are listed even if DDL_READWRITE is not specified.
DDL_HIDDEN | Includes hidden files.
DDL_READONLY | Includes read-only files.
DDL_READWRITE | Includes read-write files with no additional attributes.
DDL_SYSTEM | Includes system files.

lpszFileSpec
Value of lParam. Pointer to the null-terminated string that specifies the filename to add to the list. If the filename contains wildcards (for example, *.*), all files that match the wildcards and have the attributes specified by the uAttrs parameter are added to the list.

Return Values

The return value is the zero-based index of the last filename added to the list. If an error occurs, the return value is LB_ERR. If there is insufficient space to store the new strings, the return value is LB_ERRSPACE.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, DlgDirList


LB_FINDSTRING

An application sends an LB_FINDSTRING message to find the first string in a list box that contains the specified prefix.

LB_FINDSTRING
wParam = (WPARAM) indexStart;           // item before start of search
lParam = (LPARAM) (LPCTSTR) lpszFind;   // search string address

Parameters

indexStart
Value of wParam. Specifies the zero-based index of the item before the first item to be searched. When the search reaches the bottom of the list box, it continues from the top of the list box back to the item specified by the indexStart parameter. If indexStart is –1, the entire list box is searched from the beginning.

Windows 95 and Windows 98: The wParam parameter is limited to 16-bit values. This means list boxes cannot contain more than 32,767 items. Although the number of items is restricted, the total size in bytes of the items in a list box is limited only by available memory.

lpszFind
Value of lParam. Pointer to the null-terminated string that contains the prefix to search for. The search is case independent, so this string can contain any combination of uppercase and lowercase letters.

Return Values

The return value is the index of the matching item, or LB_ERR if the search was unsuccessful.

Remarks

If you create the list box with an owner-drawn style but without the LBS_HASSTRINGS style, this message returns the index of the item with a long value (supplied as the lParam parameter of the LB_ADDSTRING or LB_INSERTSTRING message) that matches the value supplied as the lpszFind parameter.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_ADDSTRING, LB_INSERTSTRING, LB_SELECTSTRING


LB_FINDSTRINGEXACT

An application sends a LB_FINDSTRINGEXACT message to find the first list box string that matches the string specified in the lpszFind parameter.

LB_FINDSTRINGEXACT
wParam = (WPARAM) indexStart;      // item before start of search
lParam = (LPARAM)(LPCSTR)lpszFind; // address of search string

Parameters

indexStart
Value of wParam. Specifies the zero-based index of the item before the first item to be searched. When the search reaches the bottom of the list box, it continues from the top of the list box back to the item specified by the indexStart parameter. If indexStart is – 1, the entire list box is searched from the beginning.

Windows 95 and Windows 98: The wParam parameter is limited to 16-bit values. This means list boxes cannot contain more than 32,767 items. Although the number of items is restricted, the total size in bytes of the items in a list box is limited only by available memory.

lpszFind
Value of lParam. Pointer to the null-terminated string to search for. This string can contain a complete filename, including the extension. The search is not case sensitive, so this string can contain any combination of uppercase and lowercase letters.

Return Values

The return value is the zero-based index of the matching item, or LB_ERR if the search was unsuccessful.

Remarks

If an application creates the list box with an owner-drawn style but without the LBS_HASSTRINGS style, the action taken by LB_FINDSTRINGEXACT depends on whether the LBS_SORT style is used. If LBS_SORT is used, the system sends WM_COMPAREITEM messages to the list box owner to determine which item matches the specified string. Otherwise, LB_FINDSTRINGEXACT attempts to match the 32-bit value against the value of the lpszFind parameter.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_FINDSTRING, LB_SELECTSTRING, WM_COMPAREITEM


LB_GETANCHORINDEX

An application sends an LB_GETANCHORINDEX message to retrieve the index of the anchor item—that is, the item from which a multiple selection starts. A multiple selection spans all items from the anchor item to the caret item.

LB_GETANCHORINDEX
wParam = 0; // not used; must be zero
lParam = 0; // not used; must be zero

Parameters

This message has no parameters.

Return Values

The return value is the index of the anchor item.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_SETANCHORINDEX


LB_GETCARETINDEX

An application sends an LB_GETCARETINDEX message to determine the index of the item that has the focus rectangle in a multiple-selection list box. The item may or may not be selected.

LB_GETCARETINDEX
wParam = 0; // not used; must be zero
lParam = 0; // not used; must be zero

Parameters

This message has no parameters.

Return Values

The return value is the zero-based index of the list box item that has the focus rectangle. If the list box is a single-selection list box, the return value is the zero-based index of the item that is selected, if any.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_SETCARETINDEX


LB_GETCOUNT

An application sends an LB_GETCOUNT message to retrieve the number of items in a list box.

LB_GETCOUNT
wParam = 0; // not used; must be zero
lParam = 0; // not used; must be zero

Parameters

This message has no parameters.

Return Values

The return value is the number of items in the list box, or LB_ERR if an error occurs.

Remarks

The returned count is one greater than the index value of the last item (the index is zero-based).

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_SETCOUNT


LB_GETCURSEL

Send an LB_GETCURSEL message to retrieve the index of the currently selected item, if any, in a single-selection list box.

LB_GETCURSEL
wParam = 0;     // not used; must be zero
lParam = 0;     // not used; must be zero

Parameters

This message has no parameters.

Return Values

In a single-selection list box, the return value is the zero-based index of the currently selected item. If there is no selection, the return value is LB_ERR.

Remarks

Do not send this message to a multiple-selection list box.

To retrieve the indexes of the selected items in a multiple-selection list box, use the LB_GETSELITEMS message. To determine whether the item that has the focus rectangle in a multiple selection list box is selected, use the LB_GETSEL message.

If sent to a multiple-selection list box, LB_GETCURSEL returns the index of the item that has the focus rectangle. If no items are selected, it returns zero.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_GETCARETINDEX, LB_GETSEL, LB_GETSELITEMS, LB_SETCURSEL


LB_GETHORIZONTALEXTENT

An application sends an LB_GETHORIZONTALEXTENT message to retrieve from a list box the width, in pixels, by which the list box can be scrolled horizontally (the scrollable width) if the list box has a horizontal scroll bar.

LB_GETHORIZONTALEXTENT
wParam = 0; // not used; must be zero
lParam = 0; // not used; must be zero

Parameters

This message has no parameters.

Return Values

The return value is the scrollable width, in pixels, of the list box.

Remarks

To respond to the LB_GETHORIZONTALEXTENT message, the list box must have been defined with the WS_HSCROLL style.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_SETHORIZONTALEXTENT


LB_GETITEMDATA

An application sends an LB_GETITEMDATA message to retrieve the application-defined 32-bit value associated with the specified list box item.

LB_GETITEMDATA
wParam = (WPARAM) index;    // item index
lParam = 0;                 // not used; must be zero

Parameters

index
Value of wParam. Specifies the index of the item.

Windows 95 and Windows 98: The wParam parameter is limited to 16-bit values. This means list boxes cannot contain more than 32,767 items. Although the number of items is restricted, the total size in bytes of the items in a list box is limited only by available memory.

Return Values

The return value is the 32-bit value associated with the item, or LB_ERR if an error occurs. If the item is in an owner-drawn list box and was created without the LBS_HASSTRINGS style, this 32-bit value was in the lParam parameter of the LB_ADDSTRING or LB_INSERTSTRING message that added the item to the list box. Otherwise, it is the value in the lParam of an LB_SETITEMDATA message.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_ADDSTRING, LB_INSERTSTRING, LB_SETITEMDATA


LB_GETITEMHEIGHT

An application sends an LB_GETITEMHEIGHT message to retrieve the height of items in a list box.

LB_GETITEMHEIGHT
wParam = (WPARAM) index;    // item index
lParam = 0;                 // not used; must be zero

Parameters

index
Value of wParam. Specifies the zero-based index of the list box item. This index is used only if the list box has the LBS_OWNERDRAWVARIABLE style; otherwise, it must be zero.

Windows 95 and Windows 98: The wParam parameter is limited to 16-bit values. This means list boxes cannot contain more than 32,767 items. Although the number of items is restricted, the total size in bytes of the items in a list box is limited only by available memory.

Return Values

The return value is the height, in pixels, of each item in the list box. The return value is the height of the item specified by the index parameter if the list box has the LBS_OWNERDRAWVARIABLE style. The return value is LB_ERR if an error occurs.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_SETITEMHEIGHT


LB_GETITEMRECT

An application sends an LB_GETITEMRECT message to retrieve the dimensions of the rectangle that bounds a list box item as it is currently displayed in the list box.

LB_GETITEMRECT
wParam = (WPARAM) index;            // item index
lParam = (LPARAM) (RECT FAR*) lprc; // address of rectangle

Parameters

index
Value of wParam. Specifies the zero-based index of the item.

Windows 95 and Windows 98: The wParam parameter is limited to 16-bit values. This means list boxes cannot contain more than 32,767 items. Although the number of items is restricted, the total size in bytes of the items in a list box is limited only by available memory.

lprc
Value of lParam. Pointer to a RECT structure that will receive the client coordinates for the item in the list box.

Return Values

If an error occurs, the return value is LB_ERR.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, RECT


LB_GETLOCALE

An application sends an LB_GETLOCALE message to retrieve the current locale of the list box. You can use the locale to determine the correct sorting order of displayed text (for list boxes with the LBS_SORT style) and of text added by the LB_ADDSTRING message.

LB_GETLOCALE
wParam = 0; // not used; must be zero
lParam = 0; // not used; must be zero

Parameters

This message has no parameters.

Return Values

The return value is a 32-bit value that specifies the current locale of the list box. The high-order word contains the country code and the low-order word contains the language identifier.

Remarks

The language identifier consists of a sublanguage identifier and a primary language identifier. Use the PRIMARYLANGID macro to extract the primary language identifier from the low-order word of the return value, and the SUBLANGID macro to extract the sublanguage identifier.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_ADDSTRING, LB_SETLOCALE, PRIMARYLANGID, SUBLANGID


LB_GETSEL

An application sends an LB_GETSEL message to retrieve the selection state of an item.

LB_GETSEL
wParam = (WPARAM) index;    // item index
lParam = 0;                 // not used; must be zero

Parameters

index
Value of wParam. Specifies the zero-based index of the item.

Windows 95 and Windows 98: The wParam parameter is limited to 16-bit values. This means list boxes cannot contain more than 32,767 items. Although the number of items is restricted, the total size in bytes of the items in a list box is limited only by available memory.

Return Values

If an item is selected, the return value is greater than zero; otherwise, it is zero. If an error occurs, the return value is LB_ERR.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_SETSEL


LB_GETSELCOUNT

An application sends an LB_GETSELCOUNT message to retrieve the total number of selected items in a multiple-selection list box.

LB_GETSELCOUNT
wParam = 0; // not used; must be zero
lParam = 0; // not used; must be zero

Parameters

This message has no parameters.

Return Values

The return value is the count of selected items in the list box. If the list box is a single-selection list box, the return value is LB_ERR.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_SETSEL


LB_GETSELITEMS

An application sends an LB_GETSELITEMS message to fill a buffer with an array of integers that specify the item numbers of selected items in a multiple-selection list box.

LB_GETSELITEMS
wParam = (WPARAM) cItems;           // maximum number of items
lParam = (LPARAM) (LPINT) lpnItems; // address of buffer

Parameters

cItems
Value of wParam. Specifies the maximum number of selected items whose item numbers are to be placed in the buffer.

Windows 95 and Windows 98: The wParam parameter is limited to 16-bit values. This means list boxes cannot contain more than 32,767 items. Although the number of items is restricted, the total size in bytes of the items in a list box is limited only by available memory.

lpnItems
Value of lParam. Pointer to a buffer large enough for the number of integers specified by the cItems parameter.

Return Values

The return value is the number of items placed in the buffer. If the list box is a single-selection list box, the return value is LB_ERR.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_GETSELCOUNT


LB_GETTEXT

An application sends an LB_GETTEXT message to retrieve a string from a list box.

LB_GETTEXT
wParam = (WPARAM) index;                // item index
lParam = (LPARAM) (LPCTSTR) lpszBuffer; // address of buffer

Parameters

index
Value of wParam. Specifies the zero-based index of the string to retrieve.

Windows 95 and Windows 98: The wParam parameter is limited to 16-bit values. This means list boxes cannot contain more than 32,767 items. Although the number of items is restricted, the total size in bytes of the items in a list box is limited only by available memory.

lpszBuffer
Value of lParam. Pointer to the buffer that will receive the string. The buffer must have sufficient space for the string and a terminating null character. An LB_GETTEXTLEN message can be sent before the LB_GETTEXT message to retrieve the length, in characters, of the string.

Return Values

The return value is the length of the string, in characters, excluding the terminating null character. If index does not specify a valid index, the return value is LB_ERR.

Remarks

If you create the list box with an owner-drawn style but without the LBS_HASSTRINGS style, the buffer pointed to by the lpszBuffer parameter will receive the 32-bit value associated with the item (the item data).

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_GETTEXTLEN


LB_GETTEXTLEN

An application sends an LB_GETTEXTLEN message to retrieve the length of a string in a list box.

LB_GETTEXTLEN
wParam = (WPARAM) index;    // item index
lParam = 0;                 // not used; must be zero

Parameters

index
Value of wParam. Specifies the zero-based index of the string.

Windows 95 and Windows 98: The wParam parameter is limited to 16-bit values. This means list boxes cannot contain more than 32,767 items. Although the number of items is restricted, the total size in bytes of the items in a list box is limited only by available memory.

Return Values

The return value is the length of the string, in characters, excluding the terminating null character. Under certain conditions, this value may actually be greater than the length of the text. For more information, see the following Remarks section.

If the index parameter does not specify a valid index, the return value is LB_ERR.

Remarks

Under certain conditions, the return value is larger than the actual length of the text. This occurs with certain mixtures of ANSI and Unicode, and is due to the operating system allowing for the possible existence of double-byte character set (DBCS) characters within the text. The return value, however, will always be at least as large as the actual length of the text; you can thus always use it to guide buffer allocation. This behavior can occur when an application uses both ANSI functions and common dialogs, which use Unicode.

To obtain the exact length of the text, use the WM_GETTEXT, LB_GETTEXT, or CB_GETLBTEXT messages, or the GetWindowText function.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, CB_GETLBTEXT, GetWindowText, LB_GETTEXT, WM_GETTEXT


LB_GETTOPINDEX

An application sends an LB_GETTOPINDEX message to retrieve the index of the first visible item in a list box. Initially the item with index 0 is at the top of the list box, but if the list box contents have been scrolled another item may be at the top.

LB_GETTOPINDEX
wParam = 0; // not used; must be zero
lParam = 0; // not used; must be zero

Parameters

This message has no parameters.

Return Values

The return value is the index of the first visible item in the list box.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_SETTOPINDEX


LB_INITSTORAGE

An application sends the LB_INITSTORAGE message before adding a large number of items to a list box. This message allocates memory for storing list box items.

LB_INITSTORAGE
wParam = (WPARAM) (int) cItems;  // number of items to add
lParam = (LPARAM) (DWORD) cb;   // amount of memory to allocate, in bytes

Parameters

cItems
Specifies the number of items to add.

Windows 95 and Windows 98: The wParam parameter is limited to 16-bit values. This means list boxes cannot contain more than 32,767 items. Although the number of items is restricted, the total size in bytes of the items in a list box is limited only by available memory.

cb
Specifies the amount of memory, in bytes, to allocate for item strings.

Return Values

If the message is successful, the return value is the total number of items for which memory has been pre-allocated, that is, the total number of items added by all successful LB_INITSTORAGE messages.

If the message fails, the return value is LB_ERRSPACE.

Windows NT: For Windows NT version 4.0, this message does not allocate the specified amount of memory; however, it always returns the value specified in the cItems parameter. For Windows NT version 5.0, the message allocates memory and returns the success and error values described above.

Remarks

The LB_INITSTORAGE message helps speed up the initialization of list boxes that have a large number of items (more than 100). It reserves the specified amount of memory so that subsequent LB_ADDSTRING, LB_INSERTSTRING, LB_DIR, and LB_ADDFILE messages take the shortest possible time. You can use estimates for the cItems and cb parameters. If you overestimate, the extra memory is allocated; if you underestimate, the normal allocation is used for items that exceed the requested amount.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_ADDFILE, LB_ADDSTRING, LB_DIR, LB_INSERTSTRING


LB_INSERTSTRING

An application sends an LB_INSERTSTRING message to insert a string into a list box. Unlike the LB_ADDSTRING message, the LB_INSERTSTRING message does not cause a list with the LBS_SORT style to be sorted.

LB_INSERTSTRING
wParam = (WPARAM) index;          // item index
lParam = (LPARAM) (LPCTSTR) lpsz; // address of string to insert

Parameters

index
Value of wParam. Specifies the zero-based index of the position at which to insert the string. If this parameter is –1, the string is added to the end of the list.

Windows 95 and Windows 98: The wParam parameter is limited to 16-bit values. This means list boxes cannot contain more than 32,767 items. Although the number of items is restricted, the total size in bytes of the items in a list box is limited only by available memory.

lpsz
Value of lParam. Pointer to the null-terminated string to be inserted.

If you create the list box with an owner-drawn style but without the LBS_HASSTRINGS style, the value of the lpsz parameter is stored as item data instead of the string it would otherwise point to. You can send the LB_GETITEMDATA and LB_SETITEMDATA messages to retrieve or modify the item data.

Return Values

The return value is the index of the position at which the string was inserted. If an error occurs, the return value is LB_ERR. If there is insufficient space to store the new string, the return value is LB_ERRSPACE.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_ADDSTRING, LB_SELECTSTRING


LB_ITEMFROMPOINT

An application sends this message to retrieve the zero-based index of the item nearest the specified point in a list box.

LB_ITEMFROMPOINT
wParam = 0;                                // not used, must be zero
lParam = (LPARAM) MAKELPARAM(xPos, yPos);  // coordinates of point

Parameters

xPos
Value of the low-order word of lParam. Specifies the x-coordinate of a point, relative to the upper-left corner of the client area of the list box.
yPos
Value of the high-order word of lParam. Specifies the y-coordinate of a point, relative to the upper-left corner of the client area of the list box.

Return Values

The return value contains the index of the nearest item in the low-order word. The high-order word is zero if the specified point is in the client area of the list box, or one if it is outside the client area.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages


LB_RESETCONTENT

An application sends an LB_RESETCONTENT to remove all items from a list box.

LB_RESETCONTENT
wParam = 0; // not used; must be zero
lParam = 0; // not used; must be zero

Parameters

This message has no parameters.

Return Values

This message does not return a value.

Remarks

If you create the list box with an owner-drawn style but without the LBS_HASSTRINGS style, the owner of the list box receives a WM_DELETEITEM message for each item in the list box.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, WM_DELETEITEM


LB_SELECTSTRING

An application sends an LB_SELECTSTRING message to search a list box for an item that begins with the characters in a specified string. If a matching item is found, the item is selected.

LB_SELECTSTRING
wParam = (WPARAM) indexStart;        // item before start of search
lParam = (LPARAM)(LPCTSTR)lpszFind;  // address of search string

Parameters

indexStart
Value of wParam. Specifies the zero-based index of the item before the first item to be searched. When the search reaches the bottom of the list box, it continues from the top of the list box back to the item specified by the indexStart parameter. If indexStart is –1, the entire list box is searched from the beginning.

Windows 95 and Windows 98: The wParam parameter is limited to 16-bit values. This means list boxes cannot contain more than 32,767 items. Although the number of items is restricted, the total size in bytes of the items in a list box is limited only by available memory.

lpszFind
Value of lParam. Pointer to the null-terminated string that contains the prefix to search for. The search is case independent, so this string can contain any combination of uppercase and lowercase letters.

Return Values

If the search is successful, the return value is the index of the selected item. If the search is unsuccessful, the return value is LB_ERR and the current selection is not changed.

Remarks

The list box is scrolled, if necessary, to bring the selected item into view.

Do not use this message with a list box that has the LBS_MULTIPLESEL style.

An item is selected only if its initial characters from the starting point match the characters in the string specified by the lpszFind parameter.

If you create the list box with an owner-drawn style but without the LBS_HASSTRINGS style, this message returns the index of the item whose long value (supplied as the lParam parameter of the LB_ADDSTRING or LB_INSERTSTRING message) matches the value supplied as the lParam parameter of LB_SELECTSTRING.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_ADDSTRING, LB_FINDSTRING, LB_INSERTSTRING


LB_SELITEMRANGE

An application sends an LB_SELITEMRANGE message to select one or more consecutive items in a multiple-selection list box.

LB_SELITEMRANGE
wParam = (WPARAM) (BOOL) fSelect;   // selection flag
lParam = MAKELPARAM(wFirst, wLast); // first and last items

Parameters

fSelect
Value of wParam. Specifies how to set the selection. If the fSelect parameter is TRUE, the string is selected and highlighted; if fSelect is zero, the highlight is removed and the string is no longer selected.
wFirst
Value of the low-order word of lParam. Specifies the zero-based index of the first item to select.
wLast
Value of the high-order word of lParam. Specifies the zero-based index of the last item to select.

Return Values

If an error occurs, the return value is LB_ERR.

Remarks

Use this message only with multiple-selection list boxes.

This message can select a range only within the first 65,536 items.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_SELITEMRANGEEX, LB_SETSEL


LB_SELITEMRANGEEX

An application sends an LB_SELITEMRANGEEX message to select one or more consecutive items in a multiple-selection list box.

LB_SELITEMRANGEEX
wParam = (WPARAM) wFirst; // first item
lParam = (LPARAM) wLast); // last item

Parameters

wFirst
Value of wParam. Specifies the zero-based index of the first item to select.

Windows 95 and Windows 98: The wParam parameter is limited to 16-bit values. This means list boxes cannot contain more than 32,767 items. Although the number of items is restricted, the total size in bytes of the items in a list box is limited only by available memory.

wLast
Value of lParam. Specifies the zero-based index of the last item to select.

Return Values

If an error occurs, the return value is LB_ERR.

Remarks

If the wFirst parameter is less than the wLast parameter, the specified range of items is selected. If wFirst is greater than wLast, the selection is removed from the specified range of items.

Use this message only with multiple-selection list boxes.

This message can select a range only within the first 65,536 items.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_SELITEMRANGE, LB_SETSEL


LB_SETANCHORINDEX

An application sends an LB_SETANCHORINDEX message to set the anchor item—that is, the item from which a multiple selection starts. A multiple selection spans all items from the anchor item to the caret item.

LB_SETANCHORINDEX
wParam = (WPARAM) index; // index to set as anchor
lParam = 0;              // not used; must be zero

Parameters

index
Value of wParam. Specifies the index of the new anchor item.

Windows 95 and Windows 98: The wParam parameter is limited to 16-bit values. This means list boxes cannot contain more than 32,767 items. Although the number of items is restricted, the total size in bytes of the items in a list box is limited only by available memory.

Return Values

If the message succeeds, the return value is zero.

If the message fails, the return value is LB_ERR.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_GETANCHORINDEX


LB_SETCARETINDEX

An application sends an LB_SETCARETINDEX message to set the focus rectangle to the item at the specified index in a multiple-selection list box. If the item is not visible, it is scrolled into view.

LB_SETCARETINDEX
wParam = (WPARAM) index;            // item index
lParam = MAKELPARAM(fScroll, 0);    // flag for scrolling item

Parameters

index
Value of wParam. Specifies the zero-based index of the list box item that is to receive the focus rectangle.

Windows 95 and Windows 98: The wParam parameter is limited to 16-bit values. This means list boxes cannot contain more than 32,767 items. Although the number of items is restricted, the total size in bytes of the items in a list box is limited only by available memory.

fScroll
Value of lParam. If this value is FALSE, the item is scrolled until it is fully visible; if it is TRUE, the item is scrolled until it is at least partially visible.

Return Values

If an error occurs, the return value is LB_ERR.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_GETCARETINDEX


LB_SETCOLUMNWIDTH

An application sends an LB_SETCOLUMNWIDTH message to a multiple-column list box (created with the LBS_MULTICOLUMN style) to set the width, in pixels, of all columns in the list box.

LB_SETCOLUMNWIDTH
wParam = (WPARAM) cxColumn; // column width in pixels
lParam = 0;                 // not used; must be zero

Parameters

cxColumn
Value of wParam. Specifies the width, in pixels, of all columns.

Return Values

This message does not return a value.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_SETTABSTOPS


LB_SETCOUNT

An application sends an LB_SETCOUNT message to set the count of items in a list box created with the LBS_NODATA style and not created with the LBS_HASSTRINGS style.

LB_SETCOUNT
wParam = (WPARAM) (int) cItems; // count of list box items
lParam = 0;                     // not used; must be zero

Parameters

cItems
Value of wParam. Specifies the new count of items in the list box.

Windows 95 and Windows 98: The wParam parameter is limited to 16-bit values. This means list boxes cannot contain more than 32,767 items. Although the number of items is restricted, the total size in bytes of the items in a list box is limited only by available memory.

Return Values

If an error occurs, the return value is LB_ERR. If there is insufficient memory to store the items, the return value is LB_ERRSPACE.

Remarks

The LB_SETCOUNT message is supported only by list boxes created with the LBS_NODATA style and not created with the LBS_HASSTRINGS style. All other list boxes return LB_ERR.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_GETCOUNT


LB_SETCURSEL

An application sends an LB_SETCURSEL message to select a string and scroll it into view, if necessary. When the new string is selected, the list box removes the highlight from the previously selected string.

LB_SETCURSEL
wParam = (WPARAM) index;    // item index
lParam = 0;                 // not used; must be zero

Parameters

index
Value of wParam. Specifies the zero-based index of the string that is selected. If the index parameter is -1, the list box is set to have no selection.

Windows 95 and Windows 98: The wParam parameter is limited to 16-bit values. This means list boxes cannot contain more than 32,767 items. Although the number of items is restricted, the total size in bytes of the items in a list box is limited only by available memory.

Return Values

If an error occurs, the return value is LB_ERR. If the index parameter is –1, the return value is LB_ERR even though no error occurred.

Remarks

Use this message only with single-selection list boxes. You cannot use it to set or remove a selection in a multiple-selection list box.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_GETCURSEL


LB_SETHORIZONTALEXTENT

An application sends an LB_SETHORIZONTALEXTENT message to set the width, in pixels, by which a list box can be scrolled horizontally (the scrollable width). If the width of the list box is smaller than this value, the horizontal scroll bar horizontally scrolls items in the list box. If the width of the list box is equal to or greater than this value, the horizontal scroll bar is hidden.

LB_SETHORIZONTALEXTENT
wParam = (WPARAM) cxExtent; // horizontal scroll width
lParam = 0;                 // not used; must be zero

Parameters

cxExtent
Value of wParam. Specifies the number of pixels by which the list box can be scrolled.

Windows 95 and Windows 98: The wParam parameter is limited to 16-bit values.

Return Values

This message does not return a value.

Remarks

To respond to the LB_SETHORIZONTALEXTENT message, the list box must have been defined with the WS_HSCROLL style.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_GETHORIZONTALEXTENT


LB_SETITEMDATA

An application sends an LB_SETITEMDATA message to set a 32-bit value associated with the specified item in a list box.

LB_SETITEMDATA
wParam = (WPARAM) index;    // item index
lParam = (LPARAM) dwData;   // value to associate with item

Parameters

index
Value of wParam. Specifies the zero-based index of the item.

Windows 95 and Windows 98: The wParam parameter is limited to 16-bit values. This means list boxes cannot contain more than 32,767 items. Although the number of items is restricted, the total size in bytes of the items in a list box is limited only by available memory.

dwData
Value of lParam. Specifies the 32-bit value to be associated with the item.

Return Values

If an error occurs, the return value is LB_ERR.

Remarks

If the item is in an owner-drawn list box created without the LBS_HASSTRINGS style, this message replaces the 32-bit value contained in the lParam parameter of the LB_ADDSTRING or LB_INSERTSTRING message that added the item to the list box.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_ADDSTRING, LB_GETITEMDATA, LB_INSERTSTRING


LB_SETITEMHEIGHT

An application sends an LB_SETITEMHEIGHT message to set the height, in pixels, of items in a list box. If the list box has the LBS_OWNERDRAWVARIABLE style, this message sets the height of the item specified by the index parameter. Otherwise, this message sets the height of all items in the list box.

LB_SETITEMHEIGHT
wParam = (WPARAM) index;        // item index
lParam = MAKELPARAM(cyItem, 0); // item height

Parameters

index
Value of wParam. Specifies the zero-based index of the item in the list box. Use this parameter only if the list box has the LBS_OWNERDRAWVARIABLE style; otherwise, set it to zero.

Windows 95 and Windows 98: The wParam parameter is limited to 16-bit values. This means list boxes cannot contain more than 32,767 items. Although the number of items is restricted, the total size in bytes of the items in a list box is limited only by available memory.

cyItem
Value of lParam. Specifies the height, in pixels, of the item.

Return Values

If the index or height is invalid, the return value is LB_ERR.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_GETITEMHEIGHT


LB_SETLOCALE

An application sends an LB_SETLOCALE message to set the current locale of the list box. You can use the locale to determine the correct sorting order of displayed text (for list boxes with the LBS_SORT style) and of text added by the LB_ADDSTRING message.

LB_SETLOCALE
wParam = (WPARAM) wLocaleID;    // locale identifier
lParam = 0;                     // not used; must be zero

Parameters

wLocaleID
Value of wParam. Specifies the locale identifier that the list box will use for sorting when adding text.

Return Values

The return value is the previous locale identifier. If the wLocaleID parameter specifies a locale that is not installed on the system, the return value is LB_ERR and the current list box locale is not changed.

Remarks

Use the MAKELCID macro to construct a locale identifier.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_ADDSTRING, LB_GETLOCALE, MAKELCID


LB_SETSEL

An application sends an LB_SETSEL message to select a string in a multiple-selection list box.

LB_SETSEL
wParam = (WPARAM) (BOOL) fSelect;   // selection flag
lParam = (LPARAM) (UINT) index;     // item index

Parameters

fSelect
Value of wParam. Specifies how to set the selection. If the fSelect parameter is TRUE, the string is selected and highlighted; if fSelect is FALSE, the highlight is removed and the string is no longer selected.
index
Value of lParam. Specifies the zero-based index of the string to set. If index is –1, the selection is added to or removed from all strings, depending on the value of fSelect.

Return Values

If an error occurs, the return value is LB_ERR.

Remarks

Use this message only with multiple-selection list boxes.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_GETSEL, LB_SELITEMRANGE


LB_SETTABSTOPS

An application sends an LB_SETTABSTOPS message to set the tab-stop positions in a list box.

LB_SETTABSTOPS
wParam = (WPARAM) cTabs;            // number of tab stops
lParam = (LPARAM) (LPINT) lpnTabs;  // address of tab-stop array

Parameters

cTabs
Value of wParam. Specifies the number of tab stops in the list box.
lpnTabs
Value of lParam. Pointer to the first member of an array of integers containing the tab stops, in dialog template units. The tab stops must be sorted in ascending order; backward tabs are not allowed.

Return Values

If all the specified tabs are set, the return value is TRUE; otherwise, it is FALSE.

Remarks

To respond to the LB_SETTABSTOPS message, the list box must have been created with the LBS_USETABSTOPS style.

If cTabs parameter is 0 and lpnTabs is NULL, the default tab stop is two dialog template units. If cTabs is 1, the list box will have tab stops separated by the distance specified by lpnTabs.

If lpnTabs points to more than a single value, a tab stop will be set for each value in lpnTabs, up to the number specified by cTabs.

The values specified by the lpnTabs parameter are in dialog template units, which 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.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, MapDialogRect


LB_SETTOPINDEX

An application sends an LB_SETTOPINDEX message to ensure that a particular item in a list box is visible.

LB_SETTOPINDEX
wParam = (WPARAM) index;    // item index
lParam = 0;                 // not used; must be zero

Parameters

index
Value of wParam. Specifies the zero-based index of the item in the list box.

Windows 95 and Windows 98: The wParam parameter is limited to 16-bit values. This means list boxes cannot contain more than 32,767 items. Although the number of items is restricted, the total size in bytes of the items in a list box is limited only by available memory.

Return Values

If an error occurs, the return value is LB_ERR.

Remarks

The system scrolls the list box contents so that either the specified item appears at the top of the list box or the maximum scroll range has been reached.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_GETTOPINDEX


LBN_DBLCLK

An application sends the LBN_DBLCLK notification message when the user double-clicks a string in a list box. The parent window of the list box receives this notification message through the WM_COMMAND message.

LBN_DBLCLK
idListBox = (int) LOWORD(wParam);  // identifier of list box
hwndListBox = (HWND) lParam;       // handle to list box

Remarks

Only a list box that has the LBS_NOTIFY style will send this notification message.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LBN_SELCHANGE, WM_COMMAND


LBN_ERRSPACE

An application sends the LBN_ERRSPACE notification message when a list box cannot allocate enough memory to meet a specific request. The parent window of the list box receives this notification message through the WM_COMMAND message.

LBN_ERRSPACE
idListBox = (int) LOWORD(wParam);  // identifier of list box
hwndListBox = (HWND) lParam;       // handle to list box

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, WM_COMMAND


LBN_KILLFOCUS

An application sends the LBN_KILLFOCUS notification message when a list box loses the keyboard focus. The parent window of the list box receives this notification message through the WM_COMMAND message.

LBN_KILLFOCUS
idListBox = (int) LOWORD(wParam);  // identifier of list box
hwndListBox = (HWND) lParam;       // handle to list box

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LBN_SETFOCUS, WM_COMMAND


LBN_SELCANCEL

An application sends the LBN_SELCANCEL notification message when the user cancels the selection in a list box. The parent window of the list box receives this notification message through the WM_COMMAND message.

LBN_SELCANCEL
idListBox = (int) LOWORD(wParam);  // identifier of list box
hwndListBox = (HWND) lParam;       // handle to list box

Remarks

This notification message applies only to list boxes of the LBS_NOTIFY style.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_SETCURSEL, LBN_DBLCLK, LBN_SELCHANGE, WM_COMMAND


LBN_SELCHANGE

An application sends the LBN_SELCHANGE notification message when the selection in a list box is about to change. The parent window of the list box receives this notification message through the WM_COMMAND message.

LBN_SELCHANGE
idListBox = (int) LOWORD(wParam);  // identifier of list box
hwndListBox = (HWND) lParam;       // handle to list box

Remarks

This notification message is not sent if the LB_SETCURSEL message changes the selection.

This notification message applies only to a list box that has the LBS_NOTIFY style.

For a multiple-selection list box, the LBN_SELCHANGE notification is sent whenever the user presses an arrow key, even if the selection does not change.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LB_SETCURSEL, LBN_DBLCLK, LBN_SELCANCEL, WM_COMMAND


LBN_SETFOCUS

An application sends the LBN_SETFOCUS notification message when a list box receives the keyboard focus. The parent window of the list box receives this notification message through the WM_COMMAND message.

LBN_SETFOCUS
idListBox = (int) LOWORD(wParam);  // identifier of list box
hwndListBox = (HWND) lParam;       // handle to list box

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, LBN_KILLFOCUS, WM_COMMAND


WM_CHARTOITEM

The WM_CHARTOITEM message is sent by a list box with the LBS_WANTKEYBOARDINPUT style to its owner in response to a WM_CHAR message.

WM_CHARTOITEM
nKey = LOWORD(wParam);          // key value
nCaretPos = HIWORD(wParam);     // caret position
hwndListBox = (HWND) lParam;    // handle to list box

Parameters

nKey
Value of the low-order word of wParam. Specifies the value of the key the user pressed.
nCaretPos
Value of the high-order word of wParam. Specifies the current position of the caret.
hwndListBox
Value of lParam. Handle to the list box.

Return Values

The return value specifies the action that the application performed in response to the message. A return value of –1 or –2 indicates that the application handled all aspects of selecting the item and requires no further action by the list box. A return value of 0 or greater specifies the zero-based index of an item in the list box and indicates that the list box should perform the default action for the keystroke on the given item.

Default Action

The DefWindowProc function returns –1.

Remarks

Only owner-drawn list boxes that do not have the LBS_HASSTRINGS style can receive this message.

If a dialog box procedure handles this message, it should cast the desired return value to a BOOL and return the value directly. The DWL_MSGRESULT value set by the SetWindowLong function is ignored.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, DefWindowProc, WM_CHAR, WM_VKEYTOITEM


WM_CTLCOLORLISTBOX

The WM_CTLCOLORLISTBOX message is sent to the parent window of a list box before the system draws the list box. By responding to this message, the parent window can set the text and background colors of the list box by using the given display device context handle.

WM_CTLCOLORLISTBOX
hdcLB = (HDC) wParam;   // handle to list box display context
hwndLB = (HWND) lParam; // handle to list box

Parameters

hdcLB
Value of wParam. Handle to the device context for the list box.
hwndLB
Value of lParam. Handle to the list box.

Return Values

If an application processes this message, it must return a handle to a brush. The system uses the brush to paint the background of the list box.

Default Action

The DefWindowProc function selects the default system colors for the list box.

Remarks

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_CTLCOLORLISTBOX message is never sent between threads. It is sent only within one 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.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, DefWindowProc, RealizePalette, SelectPalette, WM_CTLCOLORBTN, WM_CTLCOLORDLG, WM_CTLCOLOREDIT, WM_CTLCOLORMSGBOX, WM_CTLCOLORSCROLLBAR, WM_CTLCOLORSTATIC


WM_DELETEITEM

The WM_DELETEITEM message is sent to the owner of a list box or combo box when the list box or combo box is destroyed or when items are removed by the LB_DELETESTRING, LB_RESETCONTENT, CB_DELETESTRING, or CB_RESETCONTENT message. The system sends a WM_DELETEITEM message for each deleted item. The system sends the WM_DELETEITEM message for any deleted list box or combo box item with nonzero item data.

WM_DELETEITEM
idCtl = wParam;                      // control identifier
lpdis = (LPDELETEITEMSTRUCT) lParam; // structure with item information

Parameters

idCtl
Value of wParam. Specifies the identifier of the control that sent the WM_DELETEITEM message.
lpdis
Value of lParam. Pointer to a DELETEITEMSTRUCT structure that contains information about the item deleted from a list box.

Return Values

An application should return TRUE if it processes this message.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, CB_DELETESTRING, CB_RESETCONTENT, DELETEITEMSTRUCT, LB_DELETESTRING, LB_RESETCONTENT


WM_VKEYTOITEM

The WM_VKEYTOITEM message is sent by a list box with the LBS_WANTKEYBOARDINPUT style to its owner in response to a WM_KEYDOWN message.

WM_VKEYTOITEM
vkey = LOWORD(wParam);      // virtual-key code
nCaretPos = HIWORD(wParam); // caret position
hwndLB = lParam;            // handle to list box

Parameters

vkey
Value of the low-order word of wParam. Specifies the virtual-key code of the key the user pressed.
nCaretPos
Value of the high-order word of wParam. Specifies the current position of the caret.
hwndLB
Value of lParam. Handle to the list box.

Return Values

The return value specifies the action that the application performed in response to the message. A return value of –2 indicates that the application handled all aspects of selecting the item and requires no further action by the list box. A return value of –1 indicates that the list box should perform the default action in response to the keystroke. A return value of 0 or greater specifies the index of an item in the list box and indicates that the list box should perform the default action for the keystroke on the given item.

Default Action

The DefWindowProc function returns –1.

Remarks

If a dialog box procedure handles this message, it should cast the desired return value to a BOOL and return the value directly. The DWL_MSGRESULT value set by the SetWindowLong function is ignored.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

List Boxes Overview, List Box Messages, DefWindowProc, WM_CHARTOITEM, WM_KEYDOWN


List Box Styles

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.

List box style | Description
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 | Allows multiple items to be selected by using the shift key and the mouse or special key combinations.
LBS_HASSTRINGS | 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 | Specifies a multicolumn 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 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 given item data; requests to find a string within the list box 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 | 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 | Specifies that the list box's appearance is not updated when changes are made. You can change this style by sending a WM_SETREDRAW message at any time.
LBS_NOSEL | Specifies that the list box contains items that can be viewed but not selected.
LBS_NOTIFY | Notifies the parent window with an input message whenever the user clicks or double-clicks a string in the list box.
LBS_OWNERDRAWFIXED | 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.
LBS_WANTKEYBOARDINPUT | 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.


Rich Edit Controls

A rich edit control is a window in which the user can enter, edit, format, print, and save text. The text can be assigned character and paragraph formatting, and can include embedded COM objects. Rich edit controls provide a programming interface for formatting text. However, an application must implement any user interface components necessary to make formatting operations available to the user.

Rich edit controls support almost all of the messages and notification messages used with multiline edit controls. Thus, applications that already use edit controls can be easily changed to use rich edit controls. Additional messages and notifications enable applications to access the functionality unique to rich edit controls. For information about edit controls, see Edit Controls.


About Rich Edit Controls

The original specification for rich edit controls is rich edit version 1.0. The current specification is rich edit version 2.0. Before creating a rich edit control, you should call the LoadLibrary function to verify which version of rich edit is installed. The following table shows which DLL corresponds with which version of rich edit.

Rich Edit Version | DLL
1.0 | RICHED32.DLL
2.0 | RICHED20.DLL

Windows NT: Windows NT version 4.0 and later ship both rich edit libraries.

Windows 95: Windows 95 ships only RICHED32.DLL. However, RICHED20.DLL is compatible with Windows 95 and may be present if an application that uses rich edit 2.0 has been installed on the system.


Rich Edit Version 2.0

[This is preliminary documentation and subject to change.]

Rich edit version 2.0 includes several new features, such as support for Unicode and Far Eastern languages, multilevel Undo, and numerous user interface enhancements.

With a few exceptions, rich edit 2.0 uses the same Win32 functions, structures, and messages as rich edit 1.0. The differences are listed following.

  • The name of the rich edit 1.0 window class is "RichEdit". Rich edit 2.0 has both ANSI and Unicode window classes, "RichEdit20A" and "RichEdit20W", respectively To specify the appropriate rich edit window class, use the RICHEDIT_CLASS constant, which the RICHEDIT.H file defines depending on the definition of the UNICODE compile flag.
  • In rich edit version 2.0, if you create a Unicode rich edit control, specify only Unicode data in any window messages sent to the control. Similarly, if you create an ANSI rich edit control, send only ANSI or DBCS data. You can use the IsWindowUnicode function to determine whether a rich edit control is Unicode.
  • Rich edit 1.0 used CRLF (carriage return, line-feed) character combinations for paragraph markers. RichEdit 2.0 uses only a carriage return character ('\r').
  • Rich edit 2.0 introduces the following new messages:
Message | Description
EM_AUTOURLDETECT | Enable or disable automatic URL detection.
EM_CANREDO | Determine whether there are any actions in the redo queue.
EM_GETIMECOMPMODE | Retrieve the current input method editor (IME) mode.
EM_GETLANGOPTIONS | Retrieve options for IME and Far East language support.
EM_GETREDONAME | Retrieve the type name of the next action in the redo queue.
EM_GETTEXTMODE | Retrieve the text mode or undo level.
EM_GETUNDONAME | Retrieve the type name of the next action in the undo queue.
EM_REDO | Redo the next action in the redo queue.
EM_SETLANGOPTIONS | Set options for IME and Far East language support.
EM_SETTEXTMODE | Set the text mode or undo level.
EM_SETUNDOLIMIT | Set the maximum number of actions in the undo queue.
EM_STOPGROUPTYPING | Stop grouping consecutive typing actions into the current undo action.

  • Rich edit 2.0 introduces the following new structures:
Message | Description
CHARFORMAT2 | Contains information about character formatting.
PARAFORMAT2 | Contains information about paragraph formatting.

  • Rich edit 2.0 does not support the following messages that were supported in Asian-language versions of rich edit 1.0:
EM_CONVPOSITION
EM_GETIMECOLOR
EM_GETIMEOPTIONS
EM_GETPUNCTUATION
EM_GETWORDWRAPMODE
EM_SETIMECOLOR
EM_SETIMEOPTIONS
EM_SETPUNCTUATION
EM_SETWORDWRAPMODE


Creating a Rich Edit Control

To create a rich edit control, call the CreateWindowEx function, specifying the rich edit window class. If you are using rich edit 1.0 (RICHED32.DLL), specify "RichEdit" for the window class parameter. If you are using rich edit version 2.0 (RICHED20.DLL), specify RICHEDIT_CLASS for the window class parameter.

Rich edit controls support most of the window styles used with edit controls as well as additional styles. You should specify the ES_MULTILINE window style if you want to allow more than one line of text in the control.


Text Formatting

An application can send messages to a rich edit control to format characters and paragraphs and to retrieve formatting information. Paragraph formatting attributes include alignment, tabs, indents, and numbering. For characters, you can specify typeface, size, color, and effects such as bold, italic, and protected.

You can apply paragraph formatting by using the EM_SETPARAFORMAT message. To determine the current paragraph formatting for the selected text, use the EM_GETPARAFORMAT message. The PARAFORMAT structure is used with both messages to specify paragraph formatting attributes.

You can apply character formatting by using the EM_SETCHARFORMAT message. To determine the current character formatting for the selected text, you can use the EM_GETCHARFORMAT message. The CHARFORMAT structure is used with both messages to specify character attributes.

You can also use EM_SETCHARFORMAT and EM_GETCHARFORMAT messages to set and retrieve the default character formatting, which is the formatting applied to any subsequently inserted characters. For example, if an application sets the default character formatting to bold and the user then types a character, that character is bold.

The default character formatting is applied to newly inserted text only if the current selection is empty. Otherwise, the new text assumes the character formatting of the text it replaces. If the selection changes, the default character formatting changes to match the first character in the new selection.

The protected character effect is unique in that it does not change the appearance of text. If the user attempts to modify protected text, a rich edit control sends its parent window an EN_PROTECTED notification message, allowing the parent window to allow or prevent the change. To receive this notification message, you must enable it by using the EM_SETEVENTMASK message.

Foreground color is a character attribute, but background color is a property of the rich edit control. To set the background color, use the EM_SETBKGNDCOLOR message.


Current Selection in a Rich Edit Control

The user can select text in a rich edit control by using the mouse or the keyboard. The current selection is the range of selected characters, or the position of the insertion point if no characters are selected. An application can get information about the current selection, set the current selection, determine when the current selection changes, and show or hide the selection highlight.

To determine the current selection in a rich edit control, use the EM_EXGETSEL message. To set the current selection, use the EM_EXSETSEL message. The CHARRANGE structure is used with both messages and specifies a range of characters. To retrieve information about the contents of the current selection, you can use the EM_SELECTIONTYPE message.

An application can detect when the current selection changes by processing the EN_SELCHANGE notification message. The notification message specifies a SELCHANGE structure containing information about the new selection. A rich edit control sends this notification message only if you enable it by using the EM_SETEVENTMASK message.

By default, a rich edit control shows and hides the selection highlight when it gains and loses the focus. You can show or hide the selection highlight at any time by using the EM_HIDESELECTION message. For example, an application might provide a Search dialog box to find text in a rich edit control. The application might select matching text without closing the dialog box, in which case it must use the EM_HIDESELECTION message to highlight the selection.

As with edit controls, you can specify the ES_NOHIDESEL window style to prevent a rich edit control from hiding the selection highlight when it loses the focus. You can also use the EM_HIDESELECTION message to change the ES_NOHIDESEL window style after a rich edit control is created.

Instead of using the EM_EXGETSEL and EM_EXSETSEL messages, you retrieve and set the current selection by using the EM_GETSEL and EM_SETSEL edit control messages. The EM_GETSEL message packs two 16-bit character indexes into its 32-bit return value and, therefore, works only for selections that fall entirely within the first 64K. However, a rich edit control will never contain more than 32K of text, unless you extend this limit by using the EM_EXLIMITTEXT message. For selections that extend beyond the first 64K of text, the EM_GETSEL message returns – 1.


Rich Edit Text Operations

An application can send messages to retrieve or find text in a rich edit control. You can retrieve either the selected text or a specified range of text.

To get the selected text in a rich edit control, use the EM_GETSELTEXT message. The text is copied to the specified character array. You must ensure that the array is large enough to hold the selected text plus a terminating null character.

To retrieve a specified range of text, use the EM_GETTEXTRANGE message. The TEXTRANGE structure used with this message specifies the text range to retrieve and points to a character array that receives the text. Here again, the application must ensure that the array is large enough for the specified text plus a terminating null character.

You can search for a string in a rich edit control by using the EM_FINDTEXT message. The FINDTEXT structure used with this message specifies the text range to search and the string to search for. You can also specify such options as whether the search is case-sensitive.


Word and Line Breaks

A rich edit control calls a function called a word break procedure to find breaks between words and to determine where it can break lines. The control uses this information when performing word wrap operations and when processing the ctrl+left and ctrl+right key combinations. An application can send messages to a rich edit control to replace the default word break procedure, to retrieve word break information, and to determine what line a given character falls on.

Word break procedures for rich edit controls are similar to those for edit controls, but they have additional capabilities. Word break procedures for both kinds of controls can determine whether a character is a delimiter and can find the nearest word break before or after the specified position. A delimiter is a character that marks the end of a word, such as a space. In an edit control, word breaks occur only after delimiters.

Word break procedures for rich edit controls also group characters into character classes, each identified by a value in the range 0x00 through 0x0F. Word breaks occur either after delimiters or between characters of different classes. Thus, a word break procedure with different classes for alphanumeric and punctuation characters would find two word breaks in the string "WIN.COM".

A character's class can be combined with zero or more word break flags to form an eight-bit value. When performing word wrap operations, a rich edit control uses word break flags to determine where it can break lines. There are the following word break flags.

WBF_BREAKAFTER | Lines may be broken after the character.
WBF_BREAKLINE | The character is a delimiter. Delimiters mark the ends of words. Lines may be broken after delimiters.
WBF_ISWHITE | The character is a white space character. Trailing white space characters are not included in the length of a line when wrapping.

The WBF_BREAKAFTER value is used to allow wrapping after a character that does not mark the end of a word, such as a hyphen.

You can replace a rich edit control's default word break procedure with your own by using the EM_SETWORDBREAKPROC message. For more information about word break procedures, see the description of the EditWordBreakProc function.

Alternately, you can use the EM_SETWORDBREAKPROCEX message to replace the default extended word break procedure with an EditWordBreakProcEx function. This function provides additional information about the text, such as the character set. You can use the EM_GETWORDBREAKPROCEX message to retrieve the address of the current extended word break procedure.

You can use the EM_FINDWORDBREAK message to find word breaks or to determine a character's class and word break flags. In turn, the control calls its word break procedure to get the requested information.

To determine which line a given character falls on, you can use the EM_EXLINEFROMCHAR message.


Rich Edit Clipboard Operations

An application can paste the contents of the clipboard into a rich edit control using either the best available clipboard format or a specific clipboard format. You can also determine whether a rich edit control is capable of pasting a clipboard format.

As with an edit control, you can copy or cut the contents of the current selection by using the WM_COPY or WM_CUT message. Similarly, you can paste the contents of the clipboard into a rich edit control by using the WM_PASTE message. The control pastes the first available format that it recognizes, which presumably is the most descriptive format.

To paste a specific clipboard format, you can use the EM_PASTESPECIAL message. This message is useful for applications with a Paste Special command that enables the user to select the clipboard format. You can use the EM_CANPASTE message to determine whether a given format is recognized by the control.

You can also use the EM_CANPASTE message to determine whether any available clipboard format is recognized by a rich edit control. This message is useful when processing the WM_INITMENUPOPUP message. An application might enable or gray its Paste command depending on whether the control can paste any available format.

Rich edit controls register two clipboard formats: Rich Text Format (RTF) and a format called RichEdit Text and Objects. An application can register these formats by using the RegisterClipboardFormat function, specifying the CF_RTF and CF_RETEXTOBJ values.


Streams

You can use streams to transfer data into or out of a rich edit control. A stream is defined by an EDITSTREAM structure, which specifies a buffer and an application-defined callback function.

To read data into a rich edit control (that is, stream the data in), use the EM_STREAMIN message. The control repeatedly calls the application's callback function, which transfers a portion of the data into the buffer each time.

To save the contents of a rich edit control (that is, stream the data out), you can use the EM_STREAMOUT message. The control repeatedly writes to the buffer and then calls the application's callback function. For each call, the callback function saves the contents of the buffer.


Printing

You can send messages to a rich edit control to render its output for a specified device, such as a printer. You can also specify the output device for which a rich edit control formats its text.

To format part of a rich edit control's contents for a specific device, you can use the EM_FORMATRANGE message. The FORMATRANGE structure used with this message specifies the range of text to format as well as the device context for the target device.

After formatting text for an output device, you can send the output to the device by using the EM_DISPLAYBAND message. By repeatedly using the EM_FORMATRANGE and EM_DISPLAYBAND messages, an application that prints the contents of a rich edit control can implement banding. (Banding is division of output into smaller parts for printing purposes).

You can use the EM_SETTARGETDEVICE message to specify the target device for which a rich edit control formats its text. This message is useful for WYSIWYG (what you see is what you get) formatting, in which an application positions text using the default printer's font metrics instead of the screen's.


Bottomless Rich Edit Controls

An application can resize a rich edit control as needed so that it is always the same size as its contents. A rich edit control supports this so-called "bottomless" functionality by sending its parent window an EN_REQUESTRESIZE notification message whenever the size of its contents changes.

When processing the EN_REQUESTRESIZE notification message, an application should resize the control to the dimensions in the specified REQRESIZE structure. An application might also move any information near the control to accommodate the control's change in height. To resize the control, you can use the SetWindowPos function.

You can force a bottomless rich edit control to send an EN_REQUESTRESIZE notification message by using the EM_REQUESTRESIZE message. This message can be useful when processing the WM_SIZE message.

To receive EN_REQUESTRESIZE notification messages, you must enable the notification by using the EM_SETEVENTMASK message.


Miscellaneous Notification Messages

A rich edit control's parent window can process notification messages to monitor events affecting the control. Rich edit controls support all of the notification messages used with edit controls as well as several additional ones. You can determine which notification messages a rich edit control sends its parent window by setting its event mask.

To set the event mask for a rich edit control, use the EM_SETEVENTMASK message. You can retrieve the current event mask for a rich edit control by using the EM_GETEVENTMASK message.

A rich edit control's parent window can filter all keyboard and mouse input to the control by processing the EN_MSGFILTER notification message. The parent window can prevent the keyboard or mouse message from being processed or can change the message by modifying the specified MSGFILTER structure.

An application can process the EN_PROTECTED notification message to detect when the users attempts to modify protected text. To mark a range of text as protected, you can set the protected character effect. For more information, see Text Formatting.

You can enable the user to drop files in a rich edit control by processing the EN_DROPFILES notification message. The specified ENDROPFILES structure contains information about the files being dropped.


Unsupported Edit Control Functionality

Rich edit controls support most but not all of the functionality of multiline edit controls. This section lists the edit control messages and window styles that are not supported by rich edit controls.

The following messages are processed by edit controls but not by rich edit controls.

Unsupported message | Comments
EM_FMTLINES | Not supported.
EM_GETHANDLE | Rich edit controls do not store text as a simple array of characters.
EM_GETMARGINS | Not supported.
EM_GETPASSWORDCHAR | The ES_PASSWORD style is not supported.
EM_SETHANDLE | Rich edit controls do not store text as a simple array of characters.
EM_SETMARGINS | Not supported.
EM_SETPASSWORDCHAR | The ES_PASSWORD style is not supported.
EM_SETRECTNP | Not supported.
EM_SETTABSTOPS | The EM_SETPARAFORMAT message is used instead.
WM_CTLCOLOR | The EM_SETBKGNDCOLOR message is used instead.
WM_GETFONT | The EM_GETCHARFORMAT message is used instead.

The following window styles are used with multiline edit controls but not with rich edit controls:

ES_LOWERCASE | ES_PASSWORD
ES_OEMCONVERT | ES_UPPERCASE


Rich Edit Control Reference

The messages, notification messages, and structures associated with rich edit controls are grouped as follows. Some of these application programming interface (API) elements are also used with edit controls.

Formatting

CHARFORMAT
CHARFORMAT2
EM_GETCHARFORMAT
EM_GETPARAFORMAT
EM_GETRECT
EM_SETBKGNDCOLOR
EM_SETCHARFORMAT
EM_SETEVENTMASK
EM_SETPARAFORMAT
EM_SETRECT
PARAFORMAT2

Selection and Hit Testing

CHARRANGE
EM_CHARFROMPOS
EM_EXGETSEL
EM_EXSETSEL
EM_GETFIRSTVISIBLELINE
EM_GETSEL
EM_HIDESELECTION
EM_POSFROMCHAR
EM_SELECTIONTYPE
EM_SETSEL
EN_SELCHANGE
SELCHANGE

Text Operations

EM_EXLIMITTEXT
EM_FINDTEXT
EM_GETLIMITTEXT
EM_GETSELTEXT
EM_GETTEXTRANGE
EM_REPLACESEL
EM_SETLIMITTEXT
FINDTEXT
TEXTRANGE

Word and Line Breaks

EM_EXLINEFROMCHAR
EM_FINDWORDBREAK
EM_GETWORDBREAKPROC
EM_SETWORDBREAKPROC
EM_GETWORDBREAKPROCEX
EM_SETWORDBREAKPROCEX
EditWordBreakProcEx

Lines and Scrolling

EM_GETLINE
EM_GETLINECOUNT
EM_GETTHUMB
EM_LINEFROMCHAR
EM_LINEINDEX
EM_LINELENGTH
EM_LINESCROLL
EM_SCROLL
EM_SCROLLCARET

Editing Operations

EM_CANPASTE
EM_CANUNDO
EM_EMPTYUNDOBUFFER
EM_PASTESPECIAL
EM_UNDO

Streams

EDITSTREAM
EM_STREAMIN
EM_STREAMOUT

Printing

EM_DISPLAYBAND
EM_FORMATRANGE
EM_SETTARGETDEVICE
FORMATRANGE

Bottomless Rich Edit Controls

EM_REQUESTRESIZE
EN_REQUESTRESIZE
REQRESIZE

OLE Interfaces

IRichEditOle
IRichEditOleCallback

Miscellaneous

EM_GETEVENTMASK
EM_GETIMECOLOR
EM_GETIMEOPTIONS
EM_GETMODIFY
EM_GETOPTIONS
EM_GETPUNCTUATION
EM_GETWORDWRAPMODE
EM_SETEVENTMASK
EM_SETIMECOLOR
EM_SETIMEOPTIONS
EM_SETEVENTMASK
EM_SETMODIFY
EM_SETREADONLY
EM_SETOPTIONS
EM_SETPUNCTUATION
EM_SETWORDWRAPMODE
EN_CHANGE
EN_CORRECTTEXT
EN_DROPFILES
EN_ERRSPACE
EN_HSCROLL
EN_IMECHANGE
EN_KILLFOCUS
EN_MAXTEXT
EN_MSGFILTER
EN_OLEOPFAILED
EN_PROTECTED
EN_SAVECLIPBOARD
EN_SETFOCUS
EN_STOPNOUNDO
EN_UPDATE
EN_VSCROLL
WM_CONTEXTMENU
WM_CTLCOLOREDIT
COMPCOLOR
ENCORRECTTEXT
ENDROPFILES
ENOLEOPFAILED
ENPROTECTED
ENSAVECLIPBOARD
PUNCTUATION
MSGFILTER


Rich Edit Callback Functions

The following callback function is unique to rich edit controls:

EditStreamCallback
EditWordBreakProcEx


EditStreamCallback

The EditStreamCallback function is an application-defined callback function used with the EM_STREAMIN and EM_STREAMOUT messages. It is used to transfer a stream of data into or out of a rich edit control. The EDITSTREAMCALLBACK type defines a pointer to this callback function. EditStreamCallback is a placeholder for the application-defined function name.

DWORD CALLBACK EditStreamCallback(
  DWORD dwCookie, // application-defined value
  LPBYTE pbBuff,  // pointer to a buffer
  LONG cb,        // number of bytes to read or write
  LONG *pcb       // pointer to number of bytes transferred
);

Parameters

dwCookie
Specifies the value of the dwCookie member of the EDITSTREAM structure. The application specifies this value when it sends the EM_STREAMIN or EM_STREAMOUT message.
pbBuff
Pointer to a buffer to read from or write to. For a stream-in (read) operation, the callback function fills this buffer with data to transfer into the rich edit control. For a stream-out (write) operation, the buffer contains data from the control that the callback function writes to some storage.
cb
Specifies the number of bytes to read or write.
pcb
Pointer to a variable that the callback function sets to the number of bytes actually read or written.

Return Values

The callback function returns zero to indicate success.

The callback function returns a nonzero value to indicate an error. If an error occurs, the read or write operation ends and the rich edit control discards any data in the pbBuff buffer. If the callback function returns a nonzero value, the rich edit control uses the dwError member of the EDITSTREAM structure to pass the value back to the application.

Remarks

When you send the EM_STREAMIN or EM_STREAMOUT message to a rich edit control, the pfnCallback member of the EDITSTREAM structure specifies a pointer to an EditStreamCallback function. The rich edit control repeatedly calls the function to transfer a stream of data into or out of the control.

When you send the EM_STREAMIN or EM_STREAMOUT message, you specify a value for the dwCookie member of the EDITSTREAM structure. The rich edit control uses the dwCookie parameter to pass this value to your EditStreamCallback function. For example, you might use dwCookie to pass a handle to an open file. The callback function can then use the dwCookie handle to read from or write to the file.

The control calls the callback function repeatedly, transferring a portion of the data with each call. The control continues to call the callback function until one of the following conditions occurs:

  • The callback function returns a nonzero value.
  • The callback function returns zero in the *pcb parameter.
  • The value returned in the *pcb parameter is less than the number of bytes requested in the cb parameter.
  • An error occurs that prevents the rich edit control from transferring data into or out of itself. Examples are out-of-memory situations, failure of a system function, or the read buffer contains an invalid character.
  • For a stream-in operation, the RTF code contains data specifying the end of an RTF block.
  • For a stream-in operation on a single-line edit control, the callback reads in a CRLF.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.
Import Library: User-defined.

See Also

Rich Edit Controls Overview, Rich Edit Callback Functions, EDITSTREAM, EM_STREAMIN, EM_STREAMOUT


EditWordBreakProcEx

The EditWordBreakProcEx function is an application-defined callback function used with the EM_SETWORDBREAKPROCEX message. It determines the character index of the word break, or the character class and word break flags of the characters in the specified text. The EDITWORDBREAKPROCEX type defines a pointer to this callback function. EditWordBreakProcEx is a placeholder for the application-defined function name.

LONG EditWordBreakProcEx(
  char *pchText,
  LONG cchText,
  BYTE bCharSet,
  INT code
);

Parameters

pchText
Pointer to the text at the current position. If code specifies movement to the left, the text is in the elements pchText[-1] through pchText[-cchText] and pchText[0] is undefined. For all other actions, the text is in the elements pchText[0] through pchText[cchText - 1].
cchText
Number of characters in the buffer in the direction specified by code.
bCharSet
Character set of the text.
code
Wordbreak action to take. Can be one of the values described for the code parameter in the EM_FINDWORDBREAK message.

Return Values

Returns the character index of the word break, unless the code parameter is the WB_CLASSIFY or WB_ISDELIMITER value.

Remarks

An application must install the callback function by specifying the address of the callback function in an EM_SETWORDBREAKPROCEX message.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.
Import Library: User-defined.

See Also

Rich Edit Controls Overview, Rich Edit Callback Functions, EM_FINDWORDBREAK, EM_SETWORDBREAKPROCEX


Rich Edit Structures

The following structures are used with rich edit controls.

CHARFORMAT
CHARFORMAT2
CHARRANGE
COMPCOLOR
EDITSTREAM
ENCORRECTTEXT
ENDROPFILES
ENLINK
ENOLEOPFAILED
ENPROTECTED
ENSAVECLIPBOARD
FINDTEXT
FINDTEXTEX
FORMATRANGE
MSGFILTER
PARAFORMAT
PARAFORMAT2
PUNCTUATION
REOBJECT
REPASTESPECIAL
REQRESIZE
SELCHANGE
TEXTRANGE


CHARFORMAT

The CHARFORMAT structure contains information about character formatting in a rich edit control.

Rich Edit 2.0: The CHARFORMAT2 structure is a rich edit 2.0 extension of the CHARFORMAT structure. Rich edit 2.0 allows you to use either structure with the EM_GETCHARFORMAT and EM_SETCHARFORMAT messages.

typedef struct _charformat {
    UINT     cbSize;
    _WPAD    _wPad1;
    DWORD    dwMask;
    DWORD    dwEffects;
    LONG     yHeight;
    LONG     yOffset;
    COLORREF crTextColor;
    BYTE     bCharSet;
    BYTE     bPitchAndFamily;
    TCHAR    szFaceName[LF_FACESIZE];
    _WPAD    _wPad2;
} CHARFORMAT;

Members

cbSize
Size in bytes of this structure. Must be set before passing the structure to the rich edit control.
dwMask
Members containing valid information or attributes to set. This member can be zero or more of the following values:
Value | Meaning
CFM_BOLD | The CFE_BOLD value of the dwEffects member is valid.
CFM_CHARSET | The bCharSet member is valid.
CFM_COLOR | The crTextColor member and the CFE_AUTOCOLOR value of the dwEffects member are valid.
CFM_FACE | The szFaceName member is valid.
CFM_ITALIC | The CFE_ITALIC value of the dwEffects member is valid.
CFM_OFFSET | The yOffset member is valid.
CFM_PROTECTED | The CFE_PROTECTED value of the dwEffects member is valid.
CFM_SIZE | The yHeight member is valid.
CFM_STRIKEOUT | The CFE_STRIKEOUT value of the dwEffects member is valid.
CFM_UNDERLINE. | The CFE_UNDERLINE value of the dwEffects member is valid.

dwEffects
Character effects. This member can be a combination of the following values:
Value | Meaning
CFE_AUTOCOLOR | The text color is the return value of GetSysColor (COLOR_WINDOWTEXT).
CFE_BOLD | Characters are bold.
CFE_ITALIC | Characters are italic.
CFE_STRIKEOUT | Characters are struck out.
CFE_UNDERLINE | Characters are underlined.
CFE_PROTECTED | Characters are protected; an attempt to modify them will cause an EN_PROTECTED notification message.

yHeight
Character height, in twips. A twip is 1/1440 of an inch, or 1/20 of a printer's point.
yOffset
Character offset, in twips, from the baseline. If this member is positive, the character is a superscript; if it is negative, the character is a subscript.
crTextColor
Text color. This member is ignored if the CFE_AUTOCOLOR character effect is specified.
bCharSet
Character set value. Can be one of the values specified for the lfCharSet member of the LOGFONT structure.
bPitchAndFamily
Font family and pitch. This member is the same as the lfPitchAndFamily member of the LOGFONT structure.
szFaceName
Null-terminated character array specifying the font face name.

Remarks

This structure is used with the EM_GETCHARFORMAT and EM_SETCHARFORMAT messages.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.
Unicode: Defined as Unicode and ANSI structures.

See Also

Rich Edit Controls Overview, Rich Edit Structures, CHARFORMAT2, EM_GETCHARFORMAT, EM_SETCHARFORMAT, EN_PROTECTED, GetSysColor, LOGFONT


CHARFORMAT2

[This is preliminary documentation and subject to change.]

The CHARFORMAT2 structure contains information about character formatting in a rich edit control. CHARFORMAT2 is a rich edit 2.0 extension of the CHARFORMAT structure. Rich edit 2.0 allows you to use either structure with the EM_GETCHARFORMAT and EM_SETCHARFORMAT messages.

typedef struct _charformat2 {
    UINT        cbSize;
    _WPAD       _wPad1;
    DWORD       dwMask;
    DWORD       dwEffects;
    LONG        yHeight;
    LONG        yOffset;
    COLORREF    crTextColor;
    BYTE        bCharSet;
    BYTE        bPitchAndFamily;
    WCHAR       szFaceName[LF_FACESIZE];
    _WPAD       _wPad2;
    WORD        wWeight;
    SHORT       sSpacing;
    COLORREF    crBackColor;
    LCID        lcid;
    DWORD       dwReserved;
    SHORT       sStyle;
    WORD        wKerning;
    BYTE        bUnderlineType;
    BYTE        bAnimation;
    BYTE        bRevAuthor;
    BYTE        bReserved1;
} CHARFORMAT2;

Members

cbSize
Specifies the size, in bytes, of this structure. Before passing this structure to a rich edit control, set cbSize to the size of the CHARFORMAT or CHARFORMAT2 structure. If cbSize equals the size of a CHARFORMAT structure, the control uses only the CHARFORMAT members.
dwMask
Specifies the parts of the CHARFORMAT2 structure that contain valid information. The dwMask member can be a combination of the values from two sets of bit flags. One set indicates the structure members that are valid. Another set indicates the valid attributes in the dwEffects member.

Set the following values to indicate the valid structure members.
Value | Meaning
CFM_ANIMATION | The bAnimation member is valid.
CFM_BACKCOLOR | The crBackColor member is valid.
CFM_CHARSET | The bCharSet member is valid.
CFM_COLOR | The crTextColor member is valid unless the CFE_AUTOCOLOR flag is set in the dwEffects member.
CFM_FACE | The szFaceName member is valid.
CFM_KERNING | The wKerning member is valid.
CFM_LCID | The lcid member is valid.
CFM_OFFSET | The yOffset member is valid.
CFM_REVAUTHOR | The bRevAuthor member is valid.
CFM_SIZE | The yHeight member is valid.
CFM_SPACING | The sSpacing member is valid.
CFM_STYLE | The sStyle member is valid.
CFM_UNDERLINETYPE | The bUnderlineType member is valid.
CFM_WEIGHT | The wWeight member is valid.

Set the following values to indicate the valid attributes of the dwEffects member:
Value | Meaning
CFM_ALLCAPS | The CFE_ALLCAPS value is valid.
CFM_BOLD | The CFE_BOLD value is valid.
CFM_COLOR | The CFE_AUTOCOLOR value is valid, or the crTextColor member is valid.
CFM_DISABLED | The CFE_DISABLED value is valid.
CFM_EMBOSS | The CFE_EMBOSS value is valid.
CFM_HIDDEN | The CFE_HIDDEN value is valid.
CFM_IMPRINT | The CFE_IMPRINT value is valid.
CFM_ITALIC | The CFE_ITALIC value is valid.
CFM_LINK | The CFE_LINK value is valid.
CFM_OUTLINE | The CFE_OUTLINE value is valid.
CFM_PROTECTED | The CFE_PROTECTED value is valid.
CFM_REVISED | The CFE_REVISION value is valid.
CFM_SHADOW | The CFE_SHADOW value is valid.
CFM_SMALLCAPS | The CFE_SMALLCAPS value is valid.
CFM_STRIKEOUT | The CFE_STRIKEOUT value is valid.
CFM_SUBSCRIPT | The CFE_SUBSCRIPT and CFE_SUPERSCRIPT values are valid.
CFM_SUPERSCRIPT | Same as CFM_SUBSCRIPT.
CFM_UNDERLINE. | The CFE_UNDERLINE value is valid.

dwEffects
A set of bit flags that specify character effects. Some of the flags are included only for compatibility with Microsoft Text Object Model (TOM) interfaces; the rich edit control stores the value but does not use it to display text.

This member can be a combination of the following values.
Value | Meaning
CFE_ALLCAPS | Characters are all capital letters. Does not affect the way the control displays the text.
CFE_AUTOCOLOR | The text color is the return value of GetSysColor (COLOR_WINDOWTEXT). If this flag is set, the crTextColor member is ignored.
CFE_BOLD | Characters are bold.
CFE_DELETED | Marks the characters as deleted.
CFE_EMBOSS | Characters are embossed. Does not affect how the control displays the text.
CFE_HIDDEN | Characters are not displayed. Does not affect how the control displays the text.
CFE_IMPRINT | Characters are displayed as imprinted characters. Does not affect how the control displays the text.
CFE_ITALIC | Characters are italic.
CFE_LINK | A rich edit control can send EN_LINK notification messages when it receives mouse messages while the mouse pointer is over text with the CFE_LINK effect.
CFE_OUTLINE | Characters are displayed as outlined characters. Does not affect how the control displays the text.
CFE_PROTECTED | Characters are protected; an attempt to modify them will cause an EN_PROTECTED notification message.
CFE_REVISION | Marks the characters as revised.
CFE_SHADOW | Characters are displayed as shadowed characters. Does not affect how the control displays the text.
CFE_SMALLCAPS | Characters are in small capital letters. Does not affect how the control displays the text.
CFE_STRIKEOUT | Characters are struck out.
CFE_SUBSCRIPT | Characters are subscript. The CFE_SUPERSCRIPT and CFE_SUBSCRIPT values are mutually exclusive. For both values, the control automatically calculates an offset and a smaller font size. Alternatively, you can use the yHeight and yOffset members to explicitly specify font size and offset for subscript and superscript characters.
CFE_SUPERSCRIPT | Characters are superscript.
CFE_UNDERLINE | Characters are underlined.

yHeight
Specifies the character height, in twips. A twip is 1/1440 of an inch, or 1/20 of a printer's point. To use this member, set the CFM_SIZE flag in the dwMask member.
yOffset
Specifies the character offset, in twips, from the baseline. If this member is positive, the character is a superscript; if it is negative, the character is a subscript. To use this member, set the CFM_OFFSET flag in the dwMask member.
crTextColor
Specifies the text color. To use this member, set the CFM_COLOR flag in the dwMask member. This member is ignored if the CFE_AUTOCOLOR character effect is specified.
bCharSet
Specifies the character set value, which can be one of the values specified for the lfCharSet member of the LOGFONT structure. To use this member, set the CFM_CHARSET flag in the dwMask member.
bPitchAndFamily
Specifies the font family and pitch. This member is the same as the lfPitchAndFamily member of the LOGFONT structure.
szFaceName
A null-terminated character array specifying the font face name. To use this member, set the CFM_FACE flag in the dwMask member.
wWeight
Specifies the font weight. This member is the same as the lfWeight member of the LOGFONT structure. To use this member, set the CFM_WEIGHT flag in the dwMask member.
sSpacing
Specifies the horizontal space, in twips, between letters. This value has no effect on the text displayed by a rich edit control; it is included for compatibility with Microsoft Text Object Model (TOM) interfaces. To use this member, set the CFM_SPACING flag in the dwMask member.
crBackColor
Specifies the background color. To use this member, set the CFM_BACKCOLOR flag in the dwMask member.
lcid
Specifies a 32-bit locale identifier that contains a language identifier in the lower word, and a sorting identifier and reserved value in the upper word. This member has no effect on the text displayed by a rich edit control, but spelling and grammar checkers can use it to deal with language-dependent problems. You can use the MAKELCID macro to create an LCID value. To use this member, set the CFM_LCID flag in the dwMask member.
dwReserved
Reserved; must be zero.
sStyle
Specifies a style handle. This value has no effect on the text displayed by a rich edit control; it is included for compatibility with Microsoft Text Object Model (TOM) interfaces. To use this member, set the CFM_STYLE flag in the dwMask member.
wKerning
Specifies the twip size above which to kern the character. This value has no effect on the text displayed by a rich edit control; it is included for compatibility with TOM interfaces. To use this member, set the CFM_KERNING flag in the dwMask member.
bUnderlineType
Specifies the underline type. To use this member, set the CFM_UNDERLINETYPE flag in the dwMask member. This member can be one of the following values.
Value | Meaning
CFU_CF1UNDERLINE | Map CHARFORMAT's bit underline to CHARFORMAT2.
CFU_INVERT | For IME composition fake a selection.
CFU_UNDERLINE | Solid underline.
CFU_UNDERLINEDOTTED | Dotted underlined text. The rich edit control displays the text with a solid underline.
CFU_UNDERLINEDOUBLE | Double-underlined text. The rich edit control displays the text with a solid underline.
CFU_UNDERLINENONE | No underline. This is the default.
CFU_UNDERLINEWORD | Underline words only. The rich edit control displays the text with a solid underline.

bAnimation
Specifies the text animation. This value has no effect on the text displayed by a rich edit control; it is included for compatibility with TOM interfaces. To use this member, set the CFM_ANIMATION flag in the dwMask member.
bRevAuthor
Specifies an index that identifies the author making a revision. The rich edit control uses different text colors for each different author index. To use this member, set the CFM_REVAUTHOR flag in the dwMask member.
bReserved1
Reserved; must be zero.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.
Unicode: Defined as Unicode and ANSI structures.

See Also

Rich Edit Controls Overview, Rich Edit Structures, CHARFORMAT, EM_GETCHARFORMAT, EM_SETCHARFORMAT, EN_PROTECTED, GetSysColor, LOGFONT, MAKELCID


CHARRANGE

The CHARRANGE structure specifies a range of characters in a rich edit control. This structure is used with the EM_EXGETSEL and EM_EXSETSEL messages.

If the cpMin and cpMax members are equal, the range is empty. The range includes everything if cpMin is 0 and cpMax is – 1.

typedef struct _charrange {
    LONG cpMin;
    LONG cpMax;
} CHARRANGE;

Members

cpMin
Index of first intercharacter position.
cpMax
Index of last intercharacter position.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EM_EXGETSEL, EM_EXSETSEL


COMPCOLOR

The COMPCOLOR structure contains color settings for a composition string.

typedef struct {
    COLORREF crText;
    COLORREF crBackground;
    DWORD dwEffects;
} COMPCOLOR;

Members

crText
Color of text.
crBackground
Color of background.
dwEffects
Character effect values as described for the dwEffects member in the CHARFORMAT structure.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, CHARFORMAT


EDITSTREAM

The EDITSTREAM structure contains information that an application passes to a rich edit control in a EM_STREAMIN or EM_STREAMOUT message. The rich edit control uses the information to transfer a stream of data into or out of the control.

typedef struct _editstream {
    DWORD dwCookie;
    DWORD dwError;
    EDITSTREAMCALLBACK pfnCallback;
} EDITSTREAM;

Members

dwCookie
Specifies an application-defined value that the rich edit control passes to the EditStreamCallback callback function specified by the pfnCallback member.
dwError
Indicates the results of the stream-in (read) or stream-out (write) operation. A value of zero indicates no error. A nonzero value can be the return value of the EditStreamCallback function or a code indicating that the control encountered an error.
pfnCallback
Pointer to an EditStreamCallback function, which is an application-defined function that the control calls to transfer data. The control calls the callback function repeatedly, transferring a portion of the data with each call.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EditStreamCallback, EM_STREAMIN, EM_STREAMOUT


ENCORRECTTEXT

Contains information about the selected text to be corrected.

typedef struct _encorrecttext {
    NMHDR nmhdr;     // notification header
    CHARRANGE chrg;  // current selection
    WORD seltyp;     // selection type
} ENCORRECTTEXT;

Members

seltyp
Value specifying the contents of the new selection. This member is SEL_EMPTY if the selection is empty or one or more of the following values:
Value | Meaning
SEL_TEXT | Text
SEL_OBJECT | At least one OLE object
SEL_MULTICHAR | More than one character of text
SEL_MULTIOBJECT | More than one OLE object

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures


ENDROPFILES

The ENDDROPFILES structure contains information associated with an EN_DROPFILES notification message. A rich edit control sends this notification message when it receives a WM_DROPFILES message.

typedef struct _endropfiles {
    NMHDR nmhdr;
    HANDLE hDrop;
    LONG cp;
    BOOL fProtected;
} ENDROPFILES;

Members

nmhdr
Notification header.
hDrop
Handle to the dropped files list (same as with WM_DROPFILES). This handle is used with the DragFinish, DragQueryFile, and DragQueryPoint functions.
cp
Character position at which the dropped files would be inserted.
fProtected
Boolean value specifying whether the specified character position is protected (TRUE) or not protected (FALSE).

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, DragFinish, DragQueryFile, DragQueryPoint, EN_DROPFILES, WM_DROPFILES


ENLINK

[This is preliminary documentation and subject to change.]

The ENLINK structure contains information about an EN_LINK notification message from a rich edit control.

typedef struct _enlink {
    NMHDR nmhdr;
    UINT msg;
    _WPAD   _wPad1;
    WPARAM wParam;
    _WPAD   _wPad2;
    LPARAM lParam;
    CHARRANGE chrg;
} ENLINK;

Members

nmhdr
A NMHDR structure. The code member of this structure identifies the notification message being sent.
msg
Identifier of the message that caused the rich edit control to send the EN_LINK notification message.
wParam
The wParam parameter of the message received by the rich edit control.
lParam
The lParam parameter of the message received by the rich edit control.
chrg
A CHARRANGE structure that specifies the range of consecutive characters in the rich edit control that have the CFE_LINK effect.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, CHARRANGE, EN_LINK, NMHDR


ENOLEOPFAILED

Contains information about a failed OLE operation.

typedef struct {
    NMHDR nmhdr;
    LONG iob;
    LONG lOper;
    HRESULT hr;
} ENOLEOPFAILED;

Members

nmhdr
Notification header.
iob
Object index.
lOper
OLE operation that failed. This can be OLEOP_DOVERB to indicate that IOleObject::DoVerb failed.
hr
Error code returned by the object on the operation.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EN_OLEOPFAILED, IOleObject::DoVerb


ENPROTECTED

The ENPROTECTED structure contains information associated with an EN_PROTECTED notification message. A rich edit control sends this notification when the user attempts to edit protected text.

typedef struct _enprotected {
    NMHDR nmhdr;
    _WPAD _wPad1;
    UINT msg;
    _WPAD _wPad2;
    WPARAM wParam;
    LPARAM lParam;
    CHARRANGE chrg;
} ENPROTECTED;

Members

nmhdr
Notification header.
msg
Message that triggered the notification.
wParam
wParam parameter of the message.
lParam
lParam parameter of the message.
chrg
Current selection.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EN_PROTECTED


ENSAVECLIPBOARD

Contains information about objects and text on the clipboard.

typedef struct {
    NMHDR nmhdr;
    LONG cObjectCount;
    LONG cch;
} ENSAVECLIPBOARD;

Members

nmhdr
Notification header.
cObjectCount
Number of objects on the clipboard.
cch
Number of characters on the clipboard.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures


FINDTEXT

The FINDTEXT structure contains information about text to search for in a rich edit control. This structure is used with the EM_FINDTEXT message.

typedef struct _findtext {
    CHARRANGE chrg;
    LPSTR lpstrText;
} FINDTEXT;

Members

chrg
Range to search.
lpstrText
Null-terminated string to find.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.
Import Library: Use comdlg32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EM_FINDTEXT


FINDTEXTEX

Contains information about text to search for in a rich edit control. This structure is used with the EM_FINDTEXTEX message.

typedef struct _findtextex {
    CHARRANGE chrg;      // range to search
    LPSTR lpstrText;     // null-terminated string to find
    CHARRANGE chrgText;  // range in which text is found
} FINDTEXTEX;

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.
Unicode: Defined as Unicode and ANSI structures.

See Also

Rich Edit Controls Overview, Rich Edit Structures


FORMATRANGE

The FORMATRANGE structure contains information that a rich edit control uses to format its output for a particular device. This structure is used with the EM_FORMATRANGE message.

typedef struct _formatrange {
    HDC hdc;
    HDC hdcTarget;
    RECT rc;
    RECT rcPage;
    CHARRANGE chrg;
} FORMATRANGE;

Members

hdc
Device to render to.
hdcTarget
Target device to format for.
rc
Area to render to. Units are in TWIPS
rcPage
Entire area of rendering device. Units are in TWIPS
chrg
Range of text to format.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EM_FORMATRANGE


MSGFILTER

The MSGFILTER structure contains information about a keyboard or mouse event. A rich edit control sends this structure to its parent window as part of an EN_MSGFILTER notification message, enabling the parent to change the message or prevent it from being processed.

typedef struct _msgfilter {
    NMHDR nmhdr;
    UINT msg;
    _WPAD _wPad1;
    WPARAM wParam;
    _WPAD _wPad2;
    LPARAM lParam;
} MSGFILTER;

Members

nmhdr
Specifies a NMHDR structure. The code member of the NMHDR structure is the EN_MSGFILTER notification code that identifies the message being sent.
msg
Specifies the keyboard or mouse message identifier.
wParam
Specifies the wParam parameter of the message.
lParam
Specifies the lParam parameter of the message.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EN_MSGFILTER


PARAFORMAT

The PARAFORMAT structure contains information about paragraph formatting attributes in a rich edit control. This structure is used with the EM_GETPARAFORMAT and EM_SETPARAFORMAT messages.

Rich Edit 2.0: The PARAFORMAT2 structure is a rich edit 2.0 extension of the PARAFORMAT structure. Rich edit 2.0 allows you to use either structure with EM_GETPARAFORMAT and EM_SETPARAFORMAT.

typedef struct _paraformat {
    UINT cbSize;
    _WPAD _wPad1;
    DWORD dwMask;
    WORD  wNumbering;
    WORD  wReserved;
    LONG  dxStartIndent;
    LONG  dxRightIndent;
    LONG  dxOffset;
    WORD  wAlignment;
    SHORT cTabCount;
    LONG  rgxTabs[MAX_TAB_STOPS];
} PARAFORMAT;

Members

cbSize
Size in bytes of this structure. Must be filled before passing to the rich edit control.
dwMask
Members containing valid information or attributes to set. This parameter can be zero or more of these values:
Value | Meaning
PFM_ALIGNMENT | The wAlignment member is valid.
PFM_NUMBERING | The wNumbering member is valid.
PFM_OFFSET | The dxOffset member is valid.
PFM_OFFSETINDENT | The dxStartIndent member is valid and specifies a relative value.
PFM_RIGHTINDENT | The dxRightIndent member is valid.
PFM_STARTINDENT | The dxStartIndent member is valid.
PFM_TABSTOPS | The cTabStobs and rgxTabStops members are valid.

If both PFM_STARTINDENT and PFM_OFFSETINDENT are specified, PFM_STARTINDENT takes precedence.

wNumbering
Value specifying numbering options. This member can be zero or PFN_BULLET.
dxStartIndent
Indentation, in twips, of the first line in the paragraph. If the paragraph formatting is being set and PFM_OFFSETINDENT is specified, this member is treated as a relative value that is added to the starting indentation of each affected paragraph.
dxRightIndent
Size, in twips, of the right indentation, relative to the right margin.
dxOffset
Indentation, in twips, of the second line and subsequent lines, relative to the starting indentation. The first line is indented if this member is negative, or outdented is this member is positive.
wAlignment
Value specifying the paragraph alignment. This member can be one of the following values:
Value | Meaning
PFA_LEFT | Paragraphs are aligned with the left margin.
PFA_RIGHT | Paragraphs are aligned with the right margin.
PFA_CENTER | Paragraphs are centered.

cTabCount
Number of tab stops.
rgxTabs
Array of absolute tab stop positions.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EM_GETPARAFORMAT, EM_SETPARAFORMAT, PARAFORMAT2


PARAFORMAT2

[This is preliminary documentation and subject to change.]

The PARAFORMAT2 structure contains information about paragraph formatting attributes in a rich edit control. PARAFORMAT2 is a rich edit 2.0 extension of the PARAFORMAT structure. Rich edit 2.0 allows you to use either structure with the EM_GETPARAFORMAT and EM_SETPARAFORMAT messages.

typedef struct _paraformat {
    UINT cbSize;
    _WPAD _wPad1;
    DWORD dwMask;
    WORD  wNumbering;
    WORD  wReserved; // redefined as wEffects in PARAFORMAT2
    LONG  dxStartIndent;
    LONG  dxRightIndent;
    LONG  dxOffset;
    WORD  wAlignment;
    SHORT cTabCount;
    LONG  rgxTabs[MAX_TAB_STOPS];
    LONG  dySpaceBefore;     // vertical spacing before para
    LONG  dySpaceAfter;      // vertical spacing after para
    LONG  dyLineSpacing;     // line spacing depending on Rule
    SHORT sStyle;            // style handle
    BYTE  bLineSpacingRule;  // rule for line spacing (see tom.doc)
    BYTE  bCRC;              // reserved for CRC for rapid searching
    WORD  wShadingWeight;    // shading in hundredths of a per cent
    WORD  wShadingStyle;     // nibble 0: style, 1: cfpat, 2: cbpat
    WORD  wNumberingStart;   // starting value for numbering
    WORD  wNumberingStyle;   // alignment, roman/arabic, (), ), ., etc.
    WORD  wNumberingTab;     // space bet 1st indent and 1st-line text
    WORD  wBorderSpace;      // space between border and text (twips)
    WORD  wBorderWidth;      // border pen width (twips)
    WORD  wBorders;          // byte 0: bits specify which borders
                             // nibble 2: border style, 3: color index
} PARAFORMAT2;
#define  wEffects  wReserved

Members

cbSize
Specifies the size, in bytes, of this structure. Before passing this structure to a rich edit control, set cbSize to the size of the PARAFORMAT or PARAFORMAT2 structure. If cbSize equals the size of a PARAFORMAT structure, the control uses only the PARAFORMAT members.
dwMask
Specifies the parts of the PARAFORMAT2 structure that contain valid information. The dwMask member can be a combination of the values from two sets of bit flags. One set indicates the structure members that are valid. Another set indicates the valid attributes in the wEffects member.

Set the following values to indicate the valid structure members.
Value | Meaning
PFM_ALIGNMENT | The wAlignment member is valid.
PFM_BORDER | The wBorderSpace, wBorderWidth, and wBorders members are valid.
PFM_LINESPACING | The dyLineSpacing and bLineSpacingRule members are valid.
PFM_NUMBERING | The wNumbering member is valid.
PFM_NUMBERINGSTART | The wNumberingStart member is valid.
PFM_NUMBERINGSTYLE | The wNumberingStyle member is valid.
PFM_NUMBERINGTAB | The wNumberingTab member is valid.
PFM_OFFSET | The dxOffset member is valid.
PFM_OFFSETINDENT | The dxStartIndent member is valid. If you are setting the indentation, dxStartIndent specifies the amount to indent relative to the current indentation.
PFM_RIGHTINDENT | The dxRightIndent member is valid.
PFM_SHADING | The wShadingWeight and wShadingStyle members are valid.
PFM_SPACEAFTER | The dySpaceAfter member is valid.
PFM_SPACEBEFORE | The dySpaceBefore member is valid.
PFM_STARTINDENT | The dxStartIndent member is valid and specifies the indentation from the left margin. If both PFM_STARTINDENT and PFM_OFFSETINDENT are specified, PFM_STARTINDENT takes precedence.
PFM_STYLE | The sStyle member is valid.
PFM_TABSTOPS | The cTabCount and rgxTabs members are valid.

Set the following values to indicate the valid attributes of the wEffects member.
Value | Meaning
PFM_DONOTHYPHEN | The PFE_DONOTHYPHEN value is valid.
PFM_KEEP | The PFE_KEEP value is valid.
PFM_KEEPNEXT | The PFE_KEEPNEXT value is valid.
PFM_NOLINENUMBER | The PFE_NOLINENUMBER value is valid.
PFM_NOWIDOWCONTROL | The PFE_NOWIDOWCONTROL value is valid.
PFM_PAGEBREAKBEFORE | The PFE_PAGEBREAKBEFORE value is valid.
PFM_RTLPARA | The PFE_RTLPARA value is valid.
PFM_SIDEBYSIDE | The PFE_SIDEBYSIDE value is valid.
PFM_TABLE | The PFE_TABLEROW, PFE_TABLECELLEND, and PFE_TABLECELL values are valid.

wNumbering
Specifies the options for bulleted or numbered paragraphs. To use this member, set the PFM_NUMBERING flag in the dwMask member. This member can be one of the following values.
Value | Meaning
zero | No paragraph numbering or bullets.
PFN_BULLET | Insert a bullet at the beginning of each selected paragraph.

Rich edit controls do not display paragraph numbers. However, for compatibility with Microsoft Text Object Model (TOM) interfaces, wNumbering can specify one of the following values; the rich edit control stores the value but does not use it to display the text.
Value | Meaning
2 | Use Arabic numbers (1, 2, 3, ...).
3 | Use lowercase letters (a, b, c, ...).
4 | Use uppercase letters (A, B, C, ...).
5 | Use lowercase Roman numerals (i, ii, iii, ...).
6 | Use uppercase Roman numerals (I, II, III, ...).
7 | Use a sequence of characters beginning with the Unicode character specified by the wNumberingStart member.

wReserved or wEffects
Rich Edit 2.0: A set of bit flags that specify paragraph effects. These flags are included only for compatibility with TOM interfaces; the rich edit control stores the value but does not use it to display the text.

This member can be a combination of the following values.
Value | Meaning
PFE_DONOTHYPHEN | Disable automatic hyphenation.
PFE_KEEP | No page break within the paragraph.
PFE_KEEPNEXT | No page break between this paragraph and the next.
PFE_NOLINENUMBER | Disable line numbering.
PFE_NOWIDOWCONTROL | Disable widow/orphan control for this paragraph.
PFE_PAGEBREAKBEFORE | Insert a page break before this paragraph.
PFE_RTLPARA | Display text using right-to-left reading order.
PFE_SIDEBYSIDE | Display paragraphs side-by-side.
PFE_TABLECELL | The paragraph is in a table cell, but is not the last paragraph in the cell.
PFE_TABLECELLEND | The paragraph is last in a table cell.
PFE_TABLEROW | The paragraph describes a row in a table.

Rich Edit 1.0: Reserved; must be zero.

dxStartIndent
Specifies the indentation, in twips, of the paragraph's first line. The indentation of subsequent lines depends on the dxOffset member. To use the dxStartIndent member, set the PFM_STARTINDENT or PFM_OFFSETINDENT flag in the dwMask member.

If you are setting the indentation, use the PFM_STARTINDENT flag to specify an absolute indentation from the left margin; or use the PFM_OFFSETINDENT flag to specify an indentation relative to the paragraph's current indentation. Use either flag to retrieve the current indentation.

dxRightIndent
Specifies the indentation, in twips, of the right side of the paragraph, relative to the right margin. To use this member, set the PFM_RIGHTINDENT flag in the dwMask member.
dxOffset
Specifies the indentation, in twips, of the second and subsequent lines, relative to the indentation of the first line. The first line is indented if this member is negative, or outdented is this member is positive. To use this member, set the PFM_OFFSET flag in the dwMask member.
wAlignment
Specifies the paragraph alignment. To use this member, set the PFM_ALIGNMENT flag in the dwMask member. This member can be one of the following values.
Value | Meaning
PFA_LEFT | Paragraphs are aligned with the left margin.
PFA_RIGHT | Paragraphs are aligned with the right margin.
PFA_CENTER | Paragraphs are centered.
PFA_JUSTIFY | Rich Edit 2.0: Paragraphs are justified. This value is included for compatibility with TOM interfaces; rich edit controls display the text aligned with the left margin.

cTabCount
Specifies the number of tab stops defined in the rgxTabs array.
rgxTabs
An array of absolute tab stop positions. Each element in the array specifies information about a tab stop. The 24 low-order bits specify the absolute offset in twips. To use this member, set the PFM_TABSTOPS flag in the dwMask member.

Rich Edit 2.0: For compatibility with TOM interfaces, you can use the 8 high-order bits to store additional information about each tab stop. These bits do not affect the rich edit control display.

Bits 24-27 can specify one of the following values to indicate the tab alignment.
Value | Meaning
0 | Ordinary tab
1 | Center tab
2 | Right-aligned tab
3 | Decimal tab
4 | Word bar tab (vertical bar)

Bits 28-31 can specify one of the following values to indicate the type of tab leader.
Value | Meaning
0 | No leader
1 | Dotted leader
2 | Dashed leader
3 | Underlined leader
4 | Thick line leader
5 | Double line leader

dySpaceBefore
Specifies the size, in twips, of the spacing above the paragraph. To use this member, set the PFM_SPACEBEFORE flag in the dwMask member.
dySpaceAfter
Specifies the size, in twips, of the spacing below the paragraph. To use this member, set the PFM_SPACEAFTER flag in the dwMask member.
dyLineSpacing
Specifies the spacing between lines. For a description of how this value is interpreted, see the bLineSpacingRule member. To use this member, set the PFM_LINESPACING flag in the dwMask member.
sStyle
Specifies the text style. To use this member, set the PFM_STYLE flag in the dwMask member. This member is included only for compatibility with TOM interfaces and Microsoft Word; the rich edit control stores the value but does not use it to display the text.
bLineSpacingRule
Specifies the type of line spacing. To use this member, set the PFM_SPACEAFTER flag in the dwMask member. This member can be one of the following values.
Value | Meaning
0 | Single spacing. The dyLineSpacing member is ignored.
1 | One and a half spacing. The dyLineSpacing member is ignored.
2 | Double spacing. The dyLineSpacing member is ignored.
3 | The dyLineSpacing member specifies the spacing, in twips, from one line to the next. However, if dyLineSpacing specifies a value that is less than single spacing, the control displays single-spaced text.
4 | The dyLineSpacing member specifies the spacing, in twips, from one line to the next. The control uses the exact spacing specified, even if dyLineSpacing specifies a value that is less than single spacing.
5 | The value of dyLineSpacing / 20 is the spacing, in lines, from one line to the next. Thus, setting dyLineSpacing to 20 produces single-spaced text, 40 is double-spaced, 60 is triple-spaced, and so on.

bCRC
Reserved.
wShadingWeight
Specifies a value between zero and 100 to indicate the percent of foreground color to use in shading. The wShadingStyle member specifies the foreground and background shading colors. A value of 5 indicates a shading color consisting of 5 percent foreground color and 95 percent background color. To use these members, set the PFM_SHADING flag in the dwMask member. This member is included only for compatibility with Microsoft Word; the rich edit control stores the value but does not use it to display the text.
wShadingStyle
Specifies the style and colors used for background shading. Bits 0 to 3 contain the shading style, bits 4 to 7 contain the foreground color index, and bits 8 to 11 contain the background color index. To use this member, set the PFM_SHADING flag in the dwMask member. This member is included only for compatibility with Microsoft Word; the rich edit control stores the value but does not use it to display the text.

The shading style can be one of the following values.
Value | Meaning | Value | Meaning
0 | None
1 | Dark horizontal | 7 | Light horizontal
2 | Dark vertical | 8 | Light vertical
3 | Dark down diagonal | 9 | Light down diagonal
4 | Dark up diagonal | 10 | Light up diagonal
5 | Dark grid | 11 | Light grid
6 | Dark trellis | 12 | Light trellis

The foreground and background color indexes can be one of the following values.
Value | Color | Value | Color
0 | Black | 8 | Dark blue
1 | Blue | 9 | Dark cyan
2 | Cyan | 10 | Dark green
3 | Green | 11 | Dark magenta
4 | Magenta | 12 | Dark red
5 | Red | 13 | Dark yellow
6 | Yellow | 14 | Dark gray
7 | White | 15 | Light gray

wNumberingStart
Specifies the starting number or Unicode value to use for numbered paragraphs. Use this member in conjunction with the wNumbering member. This member is included only for compatibility with TOM interfaces; the rich edit control stores the value but does not use it to display the text or bullets. To use this member, set the PFM_NUMBERINGSTART flag in the dwMask member.
wNumberingStyle
Specifies the numbering style to use with numbered paragraphs. Use this member in conjunction with the wNumbering member. This member is included only for compatibility with TOM interfaces; the rich edit control stores the value but does not use it to display the text or bullets. To use this member, set the PFM_NUMBERINGSTYLE flag in the dwMask member. This member can be one of the following values.
Value | Meaning
0 | Follow number with a right parenthesis.
1 | Follow number with period.
2 | Enclose number in parentheses.
0x8000 | Force Roman numerals.

wNumberingTab
Specifies the minimum space, in twips, between a paragraph number and the paragraph text. Use this member in conjunction with the wNumbering member. This member is included only for compatibility with TOM interfaces; the rich edit control stores the value but does not use it to display text. To use this member, set the PFM_NUMBERINGTAB flag in the dwMask member.
wBorderSpace
Specifies the space, in twips, between the border and the paragraph text. The wBorderSpace, wBorderWidth, and wBorders members are included for compatibility with Microsoft Word; the rich edit control stores the values but does not use them to display text. To use this member, set the PFM_BORDER flag in the dwMask member.
wBorderWidth
Specifies the width, in twips, of the border. To use this member, set the PFM_BORDER flag in the dwMask member.
wBorders
Specifies the location, style, and color of the border. Bits 0 to 7 specify the border locations, bits 8 to 11 specify the border style, and bits 12 to 15 specify the border color index. To use this member, set the PFM_BORDER flag in the dwMask member.

Specify the border locations using a combination of the following values.
Value | Meaning
1 | Left border
2 | Right border
4 | Top border
8 | Bottom border
16 | Inside borders
32 | Outside borders
64 | Autocolor. If this bit is set, the color index in bits 12 to 15 is not used.

Specify the border style using one of the following values.
Value | Style | Value | Style
0 | None | 6 | 6 point
1 | ¾ point | 7 | ¾ point double
2 | 1½ point | 8 | 1½ point double
3 | 2¼ point | 9 | 2¼ point double
4 | 3 point | 10 | ¾ point gray
5 | 4½ point | 11 | ¾ point gray dashed

Specify the border color using one of the following values. This value is ignored if the autocolor bit (bit 6) is set.
Value | Color | Value | Color
0 | Black | 8 | Dark blue
1 | Blue | 9 | Dark cyan
2 | Cyan | 10 | Dark green
3 | Green | 11 | Dark magenta
4 | Magenta | 12 | Dark red
5 | Red | 13 | Dark yellow
6 | Yellow | 14 | Dark gray
7 | White | 15 | Light gray

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EM_GETPARAFORMAT, EM_SETPARAFORMAT, PARAFORMAT


PUNCTUATION

The PUNCTUATION structure contains information about the punctuation used in a rich edit control.

typedef struct _punctuation {
    UINT   iSize;          // size of table; see below
    LPSTR  szPunctuation;  // punctuation; see below
} PUNCTUATION;

Members

iSize
Size in bytes of buffer pointed to by the szPunctuation member.
szPunctuation
Address of the buffer containing the punctuation characters.

Remarks

This structure is used only in Asian-language versions of the operating system.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures


REOBJECT

The REOBJECT structure contains information about an object.

typedef struct _reobject {
    DWORD  cbStruct;           // size of structure in bytes
    LONG   cp;                 // character position of object
    CLSID  clsid;              // class identifier of object
    LPOLEOBJECT      poleobj;  // OLE object interface
    LPSTORAGE        pstg;     // associated storage interface
    LPOLECLIENTSITE  polesite; // associated client site interface
    SIZEL  sizel;              // size of object (may be 0,0)
    DWORD  dvaspect;           // display aspect to use
    DWORD  dwFlags;            // object status flags
    DWORD  dwUser;             // user-defined value
} REOBJECT;

Members

cbStruct
Size, in bytes, of this structure.
cp
Character position of the object.
clsid
Class identifier of the object.
poleobj
Points to an instance of the IOleObject interface for the object.
pstg
Points to an instance of the IStorage interface. This is the storage object associated with the object.
polesite
Points to an instance of the IOleClientSite interface. This is the object's client site in the rich edit control. This address must have been obtained from the IRichEditOle::GetClientSite method.
sizel
SIZEL structure specifying the size of the object. A 0,0 on insert indicates that an object is free to determine its size until the modify flag is turned off.
dvAspect
Display aspect to use.
dwFlags
Object status flags. Can be a combination of the following values:
Value | Meaning
REO_BELOWBASELINE | Object sits below the baseline of the surrounding text; the default is to sit on the baseline.
REO_BLANK | Object is brand new. This gives the object an opportunity to save nothing and be deleted from the control automatically.
REO_DONTUSEPALETTE | Prevents creation and realization of a half-tone palette before rendering the object. Applies to 32-bit platforms only.
REO_DYNAMICSIZE | Object always determines its extents and may change despite the modify flag being turned off.
REO_GETMETAFILE | The rich edit control retrieved the metafile from the object to correctly determine the object's extents. This flag can be read but not set.
REO_HILITED | Object is currently highlighted to indicate selection. Occurs when focus is in the control and REO_SELECTED is set. This flag can be read but not set.
REO_INPLACEACTIVE | Object is currently in place active. This flag can be read but not set.
REO_INVERTEDSELECT | Object is to be drawn entirely inverted when selected; the default is to be drawn with a border.
REO_LINK | Object is a link. This flag can be read but not set.
REO_LINKAVAILABLE | Object is a link and is believed to be available. This flag can be read but not set.
REO_OPEN | Object is currently open in its server. This flag can be read but not set.
REO_RESIZABLE | Object may be resized.
REO_SELECTED | Object is currently selected in the rich edit control. This flag can be read but not set.
REO_STATIC | Object is a static object. This flag can be read but not set.

dwUser
Reserved for user-defined values.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, IOleClientSite, IOleObject, IRichEditOle::GetClientSite, IStorage


REPASTESPECIAL

Contains information identifying whether the display aspect of a pasted object should be based on the content of the object or the icon that represent the object.

typedef struct _repastespecial {
    DWORD  dwAspect;  // display aspect for object
    DWORD  dwParam;   // aspect data
} REPASTESPECIAL;

Members

dwAspect
Display aspect. Can be DVASPECT_CONTENT if the aspect of the pasted object is based on the content of the object, or DVASPECT_ICON if the aspect is based on the icon view of the object.
dwParam
Aspect data. If dwAspect is DVASPECT_ICON, this member contains the handle to the metafile with the icon view of the object.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures


REQRESIZE

The REQRESIZE structure contains the requested size of a rich edit control. A rich edit control sends this structure to its parent window as part of an EN_REQUESTRESIZE notification message.

typedef struct _reqresize {
    NMHDR nmhdr;
    RECT rc;
} REQRESIZE;

Members

nmhdr
Notification header.
rc
Requested new size.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EN_REQUESTRESIZE


SELCHANGE

The SELCHANGE stucture contains information associated with an EN_SELCHANGE notification message. A rich edit control sends this notification to its parent window when the current selection changes.

typedef struct _selchange {
    NMHDR nmhdr;
    CHARRANGE chrg;
    WORD seltyp;
} SELCHANGE;

Members

nmhdr
Notification header.
chrg
New selection range.
seltyp
Value specifying the contents of the new selection. This member is SEL_EMPTY if the selection is empty or one or more of the following values:
Value | Contents of the selection
SEL_TEXT | Text
SEL_OBJECT | At least one OLE object
SEL_MULTICHAR | More than one character of text
SEL_MULTIOBJECT | More than one OLE object

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EN_SELCHANGE


TEXTRANGE

The TEXTRANGE structure receives a range of text from a rich edit control. This structure is filled in by the EM_GETTEXTRANGE message. The buffer pointed to by the lpstrText member must be large enough to receive all characters and the teminating null character.

pedef struct _textrange {
    CHARRANGE chrg;
    LPSTR lpstrText;
} TEXTRANGE;

Members

chrg
Range of characters to get.
lpstrText
Pointer to buffer to receive the text.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.
Unicode: Defined as Unicode and ANSI structures.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EM_GETTEXTRANGE


Rich Edit Messages

The following messages are unique to rich edit controls.

EM_AUTOURLDETECT
EM_CANPASTE
EM_CANREDO
EM_DISPLAYBAND
EM_EXGETSEL
EM_EXLIMITTEXT
EM_EXLINEFROMCHAR
EM_EXSETSEL
EM_FINDTEXT
EM_FINDTEXTEX
EM_FINDWORDBREAK
EM_FORMATRANGE
EM_GETCHARFORMAT
EM_GETEVENTMASK
EM_GETIMECOLOR
EM_GETIMECOMPMODE
EM_GETIMEOPTIONS
EM_GETLANGOPTIONS
EM_GETOLEINTERFACE
EM_GETOPTIONS
EM_GETPARAFORMAT
EM_GETPUNCTUATION
EM_GETREDONAME
EM_GETSELTEXT
EM_GETTEXTMODE
EM_GETTEXTRANGE
EM_GETUNDONAME
EM_GETWORDBREAKPROCEX
EM_GETWORDWRAPMODE
EM_HIDESELECTION
EM_PASTESPECIAL
EM_REDO
EM_REQUESTRESIZE
EM_SELECTIONTYPE
EM_SETBKGNDCOLOR
EM_SETCHARFORMAT
EM_SETEVENTMASK
EM_SETIMECOLOR
EM_SETIMEOPTIONS
EM_SETLANGOPTIONS
EM_SETOLECALLBACK
EM_SETOPTIONS
EM_SETPARAFORMAT
EM_SETPUNCTUATION
EM_SETTARGETDEVICE
EM_SETTEXTMODE
EM_SETUNDOLIMIT
EM_SETWORDBREAKPROCEX
EM_SETWORDWRAPMODE
EM_STOPGROUPTYPING
EM_STREAMIN
EM_STREAMOUT
WM_CONTEXTMENU


EM_AUTOURLDETECT

[This is preliminary documentation and subject to change.]

Rich Edit 2.0 and later: Send an EM_AUTOURLDETECT message to enable or disable automatic detection of URLs by a rich edit control.

Rich Edit 1.0: This message is not supported.

EM_AUTOURLDETECT
wParam = (WPARAM) bEnable;  // TRUE to enable, FALSE to disable
lParam = 0 ;                // not used;  must be zero

Parameters

bEnable
Value of wParam. Specify TRUE to enable automatic URL detection, or FALSE to disable it.

Return Values

If the message succeeds, the return value is zero.

If the message fails, the return value is a nonzero value. For example, the message may fail due to insufficient memory.

Remarks

If automatic URL detection is enabled, the rich edit control scans any modified text to determine whether the text matches the format of a URL. The control detects several URL formats, including the following formats:

http:<text with no whitespace>
file:<text with no whitespace>
mailto:<text with no whitespace>
ftp:<text with no whitespace>
https:<text with no whitespace>
gopher:<text with no whitespace>
nntp:<text with no whitespace>
prospero:<text with no whitespace>
telnet:<text with no whitespace>
news:<text with no whitespace>
wais:<text with no whitespace>

When it detects a URL, the control sets the CFE_LINK effect bit for all characters in the URL string. The control highlights the URL string by underlining it and setting the text color.

Note that when automatic URL detection is enabled, the rich edit control removes the CFE_LINK effect from modified text that does not have a URL format recognized by the control. If your application uses the CFE_LINK effect to mark other types of text, do not enable automatic URL detection.

A rich edit control sends the EN_LINK notification when it receives various messages while the mouse pointer is over text that has the CFE_LINK effect.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, CHARFORMAT2, EN_LINK


EM_CANPASTE

The EM_CANPASTE message determines whether a rich edit control can paste a specified clipboard format.

EM_CANPASTE
wParam = (WPARAM) (UINT) uFormat;
lParam = 0;

Parameters

uFormat
Value identifying the clipboard format to try, or zero to try any format currently on the clipboard.

Return Values

Returns a nonzero value if the clipboard format can be pasted or zero otherwise.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages


EM_CANREDO

[This is preliminary documentation and subject to change.]

Rich Edit 2.0 and later: Send an EM_CANREDO message to a rich edit control to determine whether there are any actions in the control's redo queue.

Rich Edit 1.0: This message is not supported.

EM_CANREDO
wParam = 0;    // not used; must be zero
lParam = 0 ;   // not used; must be zero

Parameters

The parameters are not used; they must be zero.

Return Values

If there are actions in the control's redo queue, the return value is nonzero.

If the redo queue is empty, the return value is zero.

Remarks

To redo the most recent undo operation, send the EM_REDO message.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_GETREDONAME, EM_GETUNDONAME, EM_REDO, EM_UNDO


EM_DISPLAYBAND

The EM_DISPLAYBAND message displays a portion of a rich edit control's contents, as previously formatted for a device using the EM_FORMATRANGE message.

EM_DISPLAYBAND
wParam = 0;
lParam = (LPARAM) (LPRECT) lprc;

Parameters

lprc
Pointer to a RECT structure specifying the area of the device to display to.

Return Values

If the operation succeeds, the return value is TRUE.

If the operation fails, the return value is FALSE.

Remarks

Text and OLE objects are clipped by the rectangle. The application does not need to set the clipping region.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_FORMATRANGE, RECT


EM_EXGETSEL

The EM_EXGETSEL message retrieves the starting and ending character positions of the selection in a rich edit control.

EM_EXGETSEL
wParam = 0;
lParam = (LPARAM) (CHARRANGE FAR *) lpchr;

Parameters

lpchr
Pointer to a CHARRANGE structure that receives the selection range.

Return Values

No return value.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, CHARRANGE


EM_EXLIMITTEXT

The EM_EXLIMITTEXT message sets an upper limit to the amount of text the user can type or paste into a rich edit control.

EM_EXLIMITTEXT
wParam = 0;
lParam = (LPARAM) (DWORD) cchTextMax;

Parameters

cchTextMax
Maximum amount of text or zero for the default maximum. An OLE object counts as a single character. The default maximum is 32K.

Return Values

No return value.

Remarks

The text limit set by the EM_EXLIMITTEXT message does not limit the amount of text that you can stream into a rich edit control using the EM_STREAMIN message.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_STREAMIN


EM_EXLINEFROMCHAR

The EM_EXLINEFROMCHAR message determines which line contains the specified character in a rich edit control.

EM_EXLINEFROMCHAR
wParam = 0;
lParam = (LPARAM) (DWORD) ichCharPos;

Parameters

ichCharPos
Zero-based index of the character.

Return Values

Returns the zero-based index of the line.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages


EM_EXSETSEL

The EM_EXSETSEL message selects a range of characters and/or OLE objects in a rich edit control.

EM_EXSETSEL
wParam = 0;
lParam = (LPARAM) (CHARRANGE FAR *) ichCharRange;

Parameters

ichCharRange
Zero-based index of the character.

Return Values

Returns the zero-based index of the line.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages


EM_FINDTEXT

The EM_FINDTEXT message finds text within a rich edit control.

EM_FINDTEXT
wParam = (WPARAM) (UINT) fuFlags;
lParam = (LPARAM) (FINDTEXT FAR *) lpFindText;

Parameters

fuFlags
Zero or more of the FR_MATCHCASE and FR_WHOLEWORD values.
lpFindText
Pointer to a FINDTEXT structure containing information about the find operation.

Return Values

Returns the zero-based character position of the next match, or – 1 if there are no more matches.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.
Unicode: Defined as Unicode and ANSI messages.

See Also

Rich Edit Controls Overview, Rich Edit Messages, FINDTEXT


EM_FINDTEXTEX

Finds text within a rich edit control.

EM_FINDTEXTEX
wParam = (WPARAM) (UINT) fuFlags;
lParam = (LPARAM) (FINDTEXTEX FAR *) lpFindText;

Parameters

fuFlags
Zero or more of the FR_MATCHCASE and FR_WHOLEWORD values.
lpFindText
Address of a FINDTEXTEX structure containing information about the find operation.

Return Values

Returns the zero-based character position of the next match or – 1 if there are no more matches.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.
Unicode: Defined as Unicode and ANSI messages.

See Also

Rich Edit Controls Overview, Rich Edit Messages, FINDTEXTEX


EM_FINDWORDBREAK

The EM_FINDWORDBREAK message finds the next word break before or after the specified character position, or retrieves information about the character at that position.

EM_FINDWORDBREAK
wParam = (WPARAM) (UINT) code;
lParam = (LPARAM) (DWORD) ichStart;

Parameters

code
Action to take. This parameter can be one of these values:
Value | Meaning
WB_CLASSIFY | Returns the character class and word break flags of the character at the specified position.
WB_ISDELIMITER | Returns TRUE if the character at the specified position is a delimiter, or FALSE otherwise.
WB_LEFT | Finds the nearest character before the specified position that begins a word.
WB_LEFTBREAK | Finds the next word end before the specified position. Same as WB_PREVBREAK.
WB_MOVEWORDLEFT | Finds the next character that begins a word before the specified position. This value is used during ctrl+left key processing. Same as WB_MOVEWORDPREV.
WB_MOVEWORDRIGHT | Finds the next character that begins a word after the specified position. This value is used during ctrl+right key processing. Same as WB_MOVEWORDNEXT.
WB_RIGHT | Finds the next character that begins a word after the specified position.
WB_RIGHTBREAK | Finds the next end-of-word delimiter after the specified position. Same as WB_NEXTBREAK.

ichStart
Zero-based character position to start from.

Return Values

Returns the character index of the word break, unless the code parameter is the WB_CLASSIFY or WB_ISDELIMITER value. For more information, see the description of the code parameter.

Remarks

If code is WB_LEFT and WB_RIGHT, the word break procedure finds word breaks only after delimiters. This matches the functionality of an edit control. If code is WB_MOVEWORDLEFT or WB_MOVEWORDRIGHT, the word break procedure also compares character classes and word break flags.

For information about character classes and word break flags, see Word and Line Breaks.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages


EM_FORMATRANGE

The EM_FORMATRANGE message formats a range of text in a rich edit control for a specific device.

EM_FORMATRANGE
wParam = (WPARAM) (BOOL) fRender;
lParam = (LPARAM) (FORMATRANGE FAR *) lpFmt;

Parameters

fRender
Value specifying whether to render the text. If this parameter is nonzero, the text is rendered. Otherwise, the text is just measured.
lpFmt
Pointer to a FORMATRANGE structure containing information about the output device, or NULL to free information cached by the control.

This message is typically used with the EM_DISPLAYBAND message to format a rich edit control's contents for an output device such as a printer.

It is very important to free cached information after the last time you use this message by specifying NULL in lpFmt. In addition, after using this message for one device, you must free cached information before using it again for a different device.

Return Values

Returns the index of the last character that fits in the region plus one.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_DISPLAYBAND, FORMATRANGE


EM_GETCHARFORMAT

The EM_GETCHARFORMAT message determines the current character formatting in a rich edit control.

EM_GETCHARFORMAT
wParam = (WPARAM) (BOOL) fSelection;
lParam = (LPARAM) (CHARFORMAT FAR *) lpFmt;

Parameters

fSelection
Value specifying whether to get the default character formatting or the current selection's character formatting. If this parameter is zero, the default formatting is returned. Otherwise, the current selection's formatting is returned.
lpFmt
Pointer to a CHARFORMAT structure to fill in. If the selection formatting is being retrieved, the structure receives the attributes of the first character, and the dwMask member specifies which attributes are consistent throughout the entire selection.

Rich Edit 2.0 and later: This parameter can be a pointer to a CHARFORMAT2 structure, which is an extension of the CHARFORMAT structure. Before sending the EM_GETCHARFORMAT message, set the structure's cbSize member to indicate the version of the structure.

Return Values

Returns the value of the dwMask member of the CHARFORMAT structure.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, CHARFORMAT, CHARFORMAT2


EM_GETEVENTMASK

The EM_GETEVENTMASK message retrieves the event mask for a rich edit control. The event mask specifies which notification messages the control sends to its parent window.

EM_GETEVENTMASK
wParam = 0;  // not used; must be zero
lParam = 0;  // not used; must be zero

Return Values

Returns the event mask for the rich edit control.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages


EM_GETIMECOLOR

Retrieves the IME composition color. This message is available only in Asian-language versions of the operating system.

EM_GETIMECOLOR
wParam = (WPARAM) 0;
lParam = (LPARAM) (COMPCOLOR *) aCompColor;

Parameters

aCompColor
Address of a 4-element array of COMPCOLOR structures that receives the composition color.

Return Values

Returns nonzero if successful, zero otherwise.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, COMPCOLOR


EM_GETIMECOMPMODE

[This is preliminary documentation and subject to change.]

Rich Edit 2.0 and later: Send an EM_GETIMECOMPMODE message to get the current IME mode for a rich edit control.

Rich Edit 1.0: This message is not supported.

EM_GETIMECOMPMODE
wParam = 0 ;       // not used;  must be zero
lParam = 0 ;       // not used;  must be zero

Parameters

The parameters are not used; they must be zero.

Return Values

The return value is one of the following bit values.

Enumerator Value | Meaning
ICM_NOTOPEN |
ICM_LEVEL3 |
ICM_LEVEL2 |
ICM_LEVEL2_5 |
ICM_LEVEL2_SUI |

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages


EM_GETIMEOPTIONS

Retrieves the current IME options. This message is available only in Asian-language versions of the operating system.

EM_GETIMEOPTIONS
wParam = (WPARAM) 0;
lParam = (LPARAM) 0;

Return Values

Returns a combination of the IME option values described for the EM_SETIMEOPTIONS message.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_SETIMEOPTIONS


EM_GETLANGOPTIONS

[This is preliminary documentation and subject to change.]

Rich Edit 2.0 and later: Send an EM_GETLANGOPTIONS message to get a rich edit control's option settings for input method editors (IME) and Far East language support.

Rich Edit 1.0: This message is not supported.

EM_GETLANGOPTIONS
wParam = 0 ;       // not used;  must be zero
lParam = 0 ;       // not used;  must be zero

Parameters

The parameters are not used; they must be zero.

Return Values

The return value is a combination of the following bit flags, which indicate the current language option settings.

Enumerator Value | Meaning
IMF_AUTOKEYBOARD | If this flag is set, the control automatically changes the keyboard layout when the user explictly changes to a different font, or when the user explictly changes the insertion point to a new location in the text.
IMF_AUTOFONT | If this flag is set, the control automatically changes fonts when the user explicitly changes to a different keyboard layout.
IMF_IMECANCELCOMPLETE | This flag determines how the control uses the composition string of an IME if the user cancels it. If this flag is set, the control discards the composition string. If this flag is not set, the control uses the composition string as the result string.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_SETLANGOPTIONS


EM_GETOLEINTERFACE

The EM_GETOLEINTERFACE message retrieves an IRichEditOle object that a client can use to access a rich edit control's OLE functionality.

EM_GETOLEINTERFACE
wParam = 0;
lParam = (LPARAM) (LPVOID FAR *) ppObject;

Parameters

ppObject
Address at which the control stores a pointer to the IRichEditOle object. The control calls the AddRef function for the object before returning, so the calling application must call the Release function when it is done with the object.

Return Values

Returns a nonzero value if successful, or zero otherwise.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, IRichEditOle


EM_GETOPTIONS

Retrieves the rich edit control options.

EM_GETOPTIONS
wParam = (WPARAM) 0;
lParam = (LPARAM) 0;

Return Values

Returns the current option values. Can be a combination of values described for the EM_SETOPTIONS message.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_SETOPTIONS


EM_GETPARAFORMAT

The EM_GETPARAFORMAT message retrieves the paragraph formatting of the current selection in a rich edit control.

EM_GETPARAFORMAT
wParam = 0;
lParam = (LPARAM) (PARAFORMAT FAR *) lpFmt;

Parameters

lpFmt
Pointer to a PARAFORMAT structure that receives the paragraph formatting attributes of the current selection.

If more than one paragraph is selected, the structure receives the attributes of the first paragraph, and the dwMask member specifies which attributes are consistent throughout the entire selection.

Rich Edit 2.0 and later: This parameter can be a pointer to a PARAFORMAT2 structure, which is an extension of the PARAFORMAT structure. Before sending the EM_GETPARAFORMAT message, set the structure's cbSize member to indicate the version of the structure.

Return Values

Returns the value of the dwMask member of the PARAFORMAT structure.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, PARAFORMAT, PARAFORMAT2


EM_GETPUNCTUATION

Gets the current punctuation characters for the rich edit control. This message is available only in Asian-language versions of the operating system.

EM_GETPUNCTUATION
wParam = (WPARAM) (UINT) fType;
lParam = (LPARAM) (PUNCTUATION FAR *) punctTable;

Parameters

fType
Punctuation type flag. Can be one of the following values:
Value | Meaning
PC_LEADING | Leading punctuation characters
PC_FOLLOWING | Following punctuation characters
PC_DELIMITER | Delimiter

The PC_OVERFLOW value is not supported.

punctTable
Address of a PUNCTUATION structure that receives the punctuation characters.

Return Values

Returns nonzero if successful; zero otherwise.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, PUNCTUATION


EM_GETREDONAME

[This is preliminary documentation and subject to change.]

Rich Edit 2.0 and later: Send an EM_GETREDONAME message to a rich edit control to retrieve the type of the next action, if any, in the control's redo queue.

Rich Edit 1.0: This message is not supported.

EM_GETREDONAME
wParam = 0;    // not used; must be zero
lParam = 0 ;   // not used; must be zero

Parameters

The parameters are not used; they must be zero.

Return Values

If the control's redo queue is not empty, the value returned is an UNDONAMEID enumeration value that indicates the type of the next action in the control's redo queue.

If there are no redoable actions or the type of the next redoable action is unknown, the return value is zero.

Remarks

The types of actions that can be undone or redone include typing, delete, drag-drop, cut, and paste operations. This information can be useful for applications that provide an extended user interface for undo and redo operations, such as a drop-down list box of redoable actions.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_GETUNDONAME, EM_REDO, EM_UNDO, UNDONAMEID


EM_GETSELTEXT

The EM_GETSELTEXT message retrieves the currently selected text in a rich edit control.

EM_GETSELTEXT
wParam = 0;
lParam = (LPARAM) (LPSTR) lpBuf;

Parameters

lpBuf
Pointer to a buffer that receives the selected text. The calling application must ensure that the buffer is large enough to hold the selected text.

Return Values

Returns the number of characters copied, not including the terminating null character.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages


EM_GETTEXTMODE

[This is preliminary documentation and subject to change.]

Rich Edit 2.0 and later: Send an EM_GETTEXTMODE message to get the current text mode and undo level of a rich edit control.

Rich Edit 1.0: This message is not supported.

EM_GETTEXTMODE
wParam = 0 ;               // not used;  must be zero
lParam = 0 ;               // not used;  must be zero

Parameters

The parameters are not used; they must be zero.

Return Values

The return value is a set of bit flags from the TEXTMODE enumeration type. The flags indicate the current text mode and undo level of the control.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_SETTEXTMODE, TEXTMODE


EM_GETTEXTRANGE

The EM_GETTEXTRANGE message retrieves a specified range of characters from a rich edit control.

EM_GETTEXTRANGE
wParam = 0;
lParam = (LPARAM) (TEXTRANGE FAR *) lpRange;

Parameters

lpRange
Pointer to a TEXTRANGE structure that specifies the range of characters to retrieve and a buffer to copy the characters to.

Return Values

Returns the number of characters copied, not including the terminating null character.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, TEXTRANGE


EM_GETUNDONAME

[This is preliminary documentation and subject to change.]

Rich Edit 2.0 and later: Send an EM_GETUNDONAME message to a rich edit control to retrieve the type of the next undo action, if any.

Rich Edit 1.0: This message is not supported.

EM_GETUNDONAME
wParam = 0;    // not used; must be zero
lParam = 0 ;   // not used; must be zero

Parameters

The parameters are not used; they must be zero.

Return Values

If there is an undo action, the value returned is an UNDONAMEID enumeration value that indicates the type of the next action in the control's undo queue.

If there are no actions that can be undone or the type of the next undo action is unknown, the return value is zero.

Remarks

The types of actions that can be undone or redone include typing, delete, drag-drop, cut, and paste operations. This information can be useful for applications that provide an extended user interface for undo and redo operations, such as a drop-down list box of actions that can be undone.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_GETREDONAME, EM_REDO, EM_UNDO, UNDONAMEID


EM_GETWORDBREAKPROCEX

Retrieves the address of the currently registered extended word break procedure.

EM_GETWORDBREAKPROCEX
wParam = (WPARAM) 0;
lParam = (LPARAM) 0;

Return Values

Returns the address of the current procedure.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages


EM_GETWORDWRAPMODE

Gets the current word wrapping and word breaking options for the rich edit control. This message is available only in Asian-language versions of the operating system.

EM_GETWORDWRAPMODE
wParam = (WPARAM) 0;
lParam = (LPARAM) 0:

Return Values

Returns the current word wrapping and word breaking options.

Remarks

This message must not be sent by the application-defined word breaking procedure.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages


EM_HIDESELECTION

The EM_HIDESELECTION message hides or shows the selection in a rich edit control.

EM_HIDESELECTION
wParam = (WPARAM) (BOOL) fHide;
lParam = (LPARAM) (BOOL) fChangeStyle;

Parameters

fHide
Value specifying whether to hide or show the selection. If this parameter is zero, the selection is shown. Otherwise, the selection is hidden.
fChangeStyle
Value specifying whether to change the control's ES_NOHIDESEL window style. If this parameter is zero, the selection is temporarily shown or hidden. Otherwise, the style is changed.

If this parameter is nonzero and the control has the focus, the selection is hidden or shown as appropriate.

Return Values

No return value.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages


EM_PASTESPECIAL

The EM_PASTESPECIAL message pastes a specific clipboard format in a rich edit control.

EM_PASTESPECIAL
wParam = (WPARAM) (UINT) uFormat;
lParam = (REPASTESPECIAL FAR *) lpRePasteSpecial;

Parameters

uFormat
Clipboard format to paste. For a list of clipboard formats, see SetClipboardData.
lpRePasteSpecial
The address of a REPASTESPECIAL structure or NULL. If an object is being pasted in, the repastespecial structure is filled in with the desired display aspect. If lParam is NULL or REPASTESPECIAL.dwAspect is zero, the display aspect used will be the contents of the object descriptor.

Return Values

No return value.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, REPASTESPECIAL, SetClipboardData


EM_REDO

[This is preliminary documentation and subject to change.]

Rich Edit 2.0 and later: Send an EM_REDO message to a rich edit control to redo the next action in the control's redo queue.

Rich Edit 1.0: This message is not supported.

EM_REDO
wParam = 0;    // not used; must be zero
lParam = 0 ;   // not used; must be zero

Parameters

The parameters are not used; they must be zero.

Return Values

If the redo operation succeeds, the return value is nonzero.

If the redo operation fails, the return value is zero.

Remarks

To determine whether there are any actions in the control's redo queue, send the EM_CANREDO message.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_CANREDO, EM_GETREDONAME, EM_GETUNDONAME, EM_UNDO


EM_REQUESTRESIZE

The EM_REQUESTRESIZE message forces a rich edit control to send an EN_REQUESTRESIZE notification message to its parent window.

EM_REQUESTRESIZE
wParam = 0;
lParam = 0;

Return Values

No return value.

Remarks

This message is useful during WM_SIZE processing for the parent of a bottomless rich edit control.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EN_REQUESTRESIZE, WM_SIZE


EM_SELECTIONTYPE

The EM_SELECTIONTYPE message determines the selection type for a rich edit control.

EM_SELECTIONTYPE
wParam = 0;
lParam = 0;

Return Values

Returns SEL_EMPTY if the selection is empty, or one or more of the following values:

Value | Contents of the selection
SEL_TEXT | Text
SEL_OBJECT | At least one OLE object
SEL_MULTICHAR | More than one character of text
SEL_MULTIOBJECT | More than one OLE object

Remarks

This message is useful during WM_SIZE processing for the parent of a bottomless rich edit control.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, WM_SIZE


EM_SETBKGNDCOLOR

The EM_SETBKGNDCOLOR message sets the background color for a rich edit control.

EM_SETBKGNDCOLOR
wParam = (WPARAM) (BOOL) fUseSysColor;
lParam = (LPARAM) (COLORREF) clr;

Parameters

fUseSysColor
Value specifying whether to use the system color. If this parameter is nonzero, the background is set to the window background system color. Otherwise, the background is set to the specified color.
clr
COLORREF structure specifying the color if fUseSysColor is zero.

Return Values

Returns the old background color.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, COLORREF


EM_SETCHARFORMAT

The EM_SETCHARFORMAT message sets character formatting in a rich edit control.

EM_SETCHARFORMAT
wParam = (WPARAM) (UINT) uFlags;
lParam = (LPARAM) (CHARFORMAT FAR *) lpFmt;

Parameters

uFlags
Character formatting that applies to the control. If this parameter is zero, the default character format is set. Otherwise, it can be one of the following values:
Value | Meaning
SCF_ALL | Applies the formatting to all text in the control.
SCF_SELECTION | Applies the formatting to the current selection. If the selection is empty, the character formatting is applied to the insertion point, and the new character format is in effect only until the insertion point changes.
SCF_WORD | SCF_SELECTION | Applies the formatting to the selected word or words. If the selection is empty but the insertion point is inside a word, the formatting is applied to the word. The SCF_WORD value must be used in conjunction with the SCF_SELECTION value.

lpFmt
Pointer to a CHARFORMAT structure specifying the character formatting to use. Only the formatting attributes specified by the dwMask member are changed.

Rich Edit 2.0 and later: This parameter can be a pointer to a CHARFORMAT2 structure, which is an extension of the CHARFORMAT structure. Before sending the EM_SETCHARFORMAT message, set the structure's cbSize member to indicate the version of the structure.

Return Values

Returns a nonzero value if successful or zero otherwise.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, CHARFORMAT, CHARFORMAT2


EM_SETEVENTMASK

The EM_SETEVENTMASK message sets the event mask for a rich edit control. The event mask specifies which notification messages the control sends to its parent window.

EM_SETEVENTMASK
wParam = 0;
lParam = (LPARAM) (DWORD) dwMask;

Parameters

dwMask
New event mask for the rich edit control.

Return Values

Returns the previous event mask.

Remarks

The default event mask (before any is set) is ENM_NONE.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages


EM_SETIMECOLOR

Sets the IME composition color. This message is available only in Asian-language versions of the operating system.

EM_SETIMECOLOR
wParam = (WPARAM) 0;
lParam = (LPARAM) (COMPCOLOR *) aCompColor;

Parameters

aCompColor
Address of a four-element array of COMPCOLOR structures that contains the composition color to be set.

Return Values

Returns nonzero if successful, zero otherwise.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_GETIMECOLOR, COMPCOLOR


EM_SETIMEOPTIONS

Sets the IME options. This message is available only in Asian-language versions of the operating system.

EM_SETIMEOPTIONS
wParam = (WPARAM) (UINT) fOperation;
lParam = (LPARAM) (int) fOptions;

Parameters

fOperation
Operation flag. Can be one of the following values:
ECOOP_SET | Set the options to those specified by fOptions.
ECOOP_OR | Combine the specified options with the current options.
ECOOP_AND | Retain only those current options that are also specified by fOptions.
ECOOP_XOR | Logically Exclusive OR the current options with those specified by fOptions.

fOptions
IME option flag. Can be a combination of the following values:
IMF_CLOSESTATUSWINDOW | Closes the IME status window when the control receives the input focus.
IMF_FORCEACTIVE | Activates the IME when the control receives the input focus.
IMF_FORCEDISABLE | Disables the IME when the control receives the input focus.
IMF_FORCEENABLE | Enables the IME when the control receives the input focus.
IMF_FORCEINACTIVE | Inactivates the IME when the control receives the input focus.
IMF_FORCENONE | Disables IME handling.
IMF_FORCEREMEMBER | Restores the previous IME status when the control receives the input focus.
IMF_MULTIPLEEDIT | Specifies that the composition string will not be canceled or determined by focus changes. This allows an application to have separate comosition strings on each rich edit control.

Return Values

Returns nonzero if successful, zero otherwise.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_GETIMEOPTIONS


EM_SETLANGOPTIONS

[This is preliminary documentation and subject to change.]

Rich Edit 2.0 and later: Send an EM_SETLANGOPTIONS message to set options for input method editors (IME) and Far East language support in a rich edit control.

Rich Edit 1.0: This message is not supported.

EM_SETLANGOPTIONS
wParam = 0 ;                 // not used;  must be zero
lParam = (LPARAM) fOptions   // language options

Parameters

fOptions
Value of lParam. A set of bit flags that specify the language options. This parameter can be a combination of the following values.
Value | Meaning
IMF_AUTOKEYBOARD | If this flag is set, the control automatically changes the keyboard layout when the user explictly changes to a different font, or when the user explictly changes the insertion point to a new location in the text.
IMF_AUTOFONT | If this flag is set, the control automatically changes fonts when the user explicitly changes to a different keyboard layout.
IMF_IMECANCELCOMPLETE | This flag determines how the control uses the composition string of an IME if the user cancels it. If this flag is set, the control discards the composition string. If this flag is not set, the control uses the composition string as the result string.

Return Values

This message does not return a value.

Remarks

The IMF_AUTOFONT flag is set by default. The IMF_AUTOKEYBOARD and IMF_IMECANCELCOMPLETE flags are clear by default.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_GETLANGOPTIONS


EM_SETOLECALLBACK

The EM_SETOLECALLBACK message gives a rich edit control an IRichEditOleCallback object that the control uses to get OLE-related resources and information from the client.

EM_SETOLECALLBACK
wParam = 0;
lParam = (LPARAM) (IRichEditOleCallback FAR *) lpObj;

Parameters

lpObj
Pointer to an IRichEditOleCallback object. The control calls the AddRef function for the object before returning.

Return Values

Returns a nonzero value if successful or zero otherwise.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages


EM_SETOPTIONS

Sets the options for a rich edit control.

EM_SETOPTIONS
wParam = (WPARAM) (UINT) fOperation;
lParam = (LPARAM) (UINT) fOptions;

Parameters

fOperation
Operation flag. Can be one of these values:
ECOOP_SET | Set the options to those specified by fOptions.
ECOOP_OR | Combine the specified options with the current options.
ECOOP_AND | Retain only those current options that are also specified by fOptions.
ECOOP_XOR | Logically Exclusive OR the current options with those specified by fOptions.

fOptions
Rich edit control options. Can be a combination of these values:
Value | Meaning
ECO_AUTOWORDSELECTION | Automatic selection of word on doubleclick.
ECO_AUTOVSCROLL | Same as ES_AUTOVSCROLL style.
ECO_AUTOHSCROLL | Same as ES_AUTOHSCROLL style.
ECO_NOHIDESEL | Same as ES_NOHIDESEL style.
ECO_READONLY | Same as ES_READONLY style.
ECO_WANTRETURN | Same as ES_WANTRETURN style.
ECO_SAVESEL | Same as ES_SAVESEL style.
ECO_SELECTIONBAR | Same as ES_SELECTIONBAR style.
ECO_VERTICAL | Same as ES_VERTICAL style. Available in Asian-language versions only.

Return Values

Returns current option of edit control.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages


EM_SETPARAFORMAT

The EM_SETPARAFORMAT message sets the paragraph formatting for the current selection in a rich edit control.

EM_SETPARAFORMAT
wParam = 0;  // not used; must be zero
lParam = (LPARAM) (PARAFORMAT FAR *) lpFmt;

Parameters

lpFmt
Pointer to a PARAFORMAT structure specifying the new paragraph formatting attributes. Only the attributes specified by the dwMask member are changed.

Rich Edit 2.0 and later: This parameter can be a pointer to a PARAFORMAT2 structure, which is an extension of the PARAFORMAT structure. Before sending the EM_SETPARAFORMAT message, set the structure's cbSize member to indicate the version of the structure.

Return Values

Returns a nonzero value if successful, or zero otherwise.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, PARAFORMAT, PARAFORMAT2


EM_SETPUNCTUATION

Sets the punctuation characters for a rich edit control. This message is available only in Asian-language versions of the operating system.

EM_SETPUNCTUATION
wParam = (WPARAM) (UINT) fType;
lParam = (LPARAM) (PUNCTUATION FAR *) punctTable;

Parameters

fType
Punctuation type flag. Can be one of the following values:
Value | Meaning
PC_LEADING | Leading punctuation characters.
PC_FOLLOWING | Following punctuation characters.
PC_DELIMITER | Delimiter.

The PC_OVERFLOW value is not supported.

punctTable
Address of a PUNCTUATION structure that contains the punctuation characters.

Return Values

Returns nonzero if successful; zero otherwise.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, PUNCTUATION


EM_SETTARGETDEVICE

The EM_SETTARGETDEVICE message sets the target device and line width used for WYSIWYG (what you see is what you get) formatting in a rich edit control.

EM_SETTARGETDEVICE
wParam = (WPARAM) (HDC) hdcTarget;
lParam = (LPARAM) (int) cxLineWidth;

Parameters

hdcTarget
Handle to a device context for the target device.
cxLineWidth
Line width to use for formatting.

Return Values

Returns a nonzero value if successful or zero otherwise.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages


EM_SETTEXTMODE

[This is preliminary documentation and subject to change.]

Rich Edit 2.0 and later: Send an EM_SETTEXTMODE message to set the text mode or undo level of a rich edit control. The message fails if the control contains any text.

Rich Edit 1.0: This message is not supported.

EM_GETUNDONAME
wParam = (WPARAM) mode;    // specifies the new text mode
lParam = 0 ;               // not used;  must be zero

Parameters

mode
Value of wParam. Specifies a combination of values from the TEXTMODE enumeration type. The values specify the new settings for the control's text mode and undo level parameters.

Specify one of the following values to set the text mode parameter. If you don't specify a text mode value, the text mode remains at its current setting.
Value | Meaning
TM_PLAINTEXT | Indicates plain text mode, in which the control is similar to a standard edit control. For more information about plain text mode, see the following Remarks section.
TM_RICHTEXT | Indicates rich text mode, in which the control has standard rich edit functionality. Rich text mode is the default setting.

Specify one of the following values to set the undo level parameter. If you don't specify an undo level value, the undo level remains at its current setting.
Value | Meaning
TM_SINGLELEVELUNDO | The control allows the user to undo only the last action that can be undone.
TM_MULTILEVELUNDO | The control supports multiple undo operations. This is the default setting. Use the EM_SETUNDOLIMIT message to set the maximum number of undo actions.

The TM_SINGLECODEPAGE and TM_MULTICODEPAGE values are not currently supported.

Return Values

If the message succeeds, the return value is zero.

If the message fails, the return value is nonzero.

Remarks

In rich text mode, a rich edit control has standard rich edit functionality. However, in plain text mode, the control is similar to a standard edit control.

  • The text in a plain text control can have only one format (such as "Bold, 10pt Arial").
  • The user cannot paste rich text formats, such as RTF, or embedded objects into a plain text control.
  • Rich text mode controls always have a default end-of-document marker or carriage return, to format paragraphs. Plain text controls, on the other hand, do not need the default end-of-document marker, so it is omitted.

The control must contain no text when it receives the EM_SETTEXTMODE message. To ensure there is no text, send a WM_SETTEXT message with an empty string ("").

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_GETTEXTMODE, TEXTMODE, WM_SETTEXT


EM_SETUNDOLIMIT

[This is preliminary documentation and subject to change.]

Rich Edit 2.0 and later: Send an EM_SETUNDOLIMIT message to a rich edit control to set the maximum number of actions that can stored in the undo queue.

Rich Edit 1.0: This message is not supported.

EM_SETUNDOLIMIT
wParam = (WPARAM) nMax;    // maximum number of undo actions
lParam = 0 ;               // not used; must be zero

Parameters

nMax
Value of wParam. Specifies the maximum number of actions that can be stored in the undo queue.

Return Values

The return value is the new maximum number of undo actions for the rich edit control. This value may be less than nMax if memory is limited.

Remarks

By default, the maximum number of actions in the undo queue is 100. If you increase this number, there must be enough available memory to accommodate the new number. For better performance, set the limit to the smallest possible value.

Setting the limit to zero disables the Undo feature.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_CANREDO, EM_GETREDONAME, EM_GETUNDONAME, EM_REDO, EM_UNDO


EM_SETWORDBREAKPROCEX

Sets the extended word-break procedure.

EM_SETWORDBREAKPROCEX
wParam = (WPARAM) 0;
lParam = (LPARAM) pfnWordBreakProcEx;

Parameters

pfnWordBreakprocEx
Address of an EditWordBreakProcEx function or NULL to use the default procedure.

Return Values

Returns the address of the previous extended word-break procedure.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EditWordBreakProcEx, EM_GETWORDBREAKPROCEX


EM_SETWORDWRAPMODE

Sets the word-wrapping and word-breaking options for the rich edit control. This message is available only in Asian-language versions of the operating system.

EM_SETWORDWRAPMODE
wParam = (WPARAM) (UINT) fOptions;
lParam = (LPARAM) 0:

Parameters

fOptions
Options flag. Can be a combination of the following values:
Value | Meaning
WBF_WORDWRAP | Enables Asian-specific word-wrap operation, such as Kinsoku in Japanese.
WBF_WORDBREAK Enables English word-breaking operation in Japanese and Chinese.

Enables Hangeul word-breaking operation.
WBF_OVERFLOW | Recognizes overflow punctuation. (Not currently supported.)
WBF_LEVEL1 | Sets level 1 punctuation table as default.
WBF_LEVEL2 | Sets level 2 punctuation table as default.
WBF_CUSTOM | Sets application-defined punctuation table.

Return Values

Returns the current word-wrapping and word-breaking options.

Remarks

This message must not be sent by the application-defined word-breaking procedure.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages


EM_STOPGROUPTYPING

[This is preliminary documentation and subject to change.]

Rich Edit 2.0 and later: Send an EM_STOPGROUPTYPING message to a rich edit control to stop the control from collecting additional typing actions into the current undo action. The control stores the next typing action, if any, into a new action in the undo queue.

Rich Edit 1.0: This message is not supported.

EM_GETUNDONAME
wParam = 0;    // not used; must be zero
lParam = 0 ;   // not used; must be zero

Parameters

The parameters are not used; they must be zero.

Return Values

The return value is zero. The message cannot fail.

Remarks

A rich edit control groups consecutive typing actions, including characters deleted by using the backspace key, into a single undo action until one of the following events occurs:

  • The control receives an EM_STOPGROUPTYPING message.
  • The control loses focus.
  • The user moves the current selection, either by using the arrow keys or by clicking the mouse.
  • The user presses the delete key.
  • The user performs any other action that is not typing, such as a paste operation.

You can send the EM_STOPGROUPTYPING message to break consecutive typing actions into smaller undo groups. For example, you could send EM_STOPGROUPTYPING after each character or at each word break.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_UNDO


EM_STREAMIN

The EM_STREAMIN message replaces the contents of a rich edit control with a stream of data provided by an application-defined EditStreamCallback callback function.

EM_STREAMIN
wParam = (WPARAM) (UINT) uFormat;
lParam = (LPARAM) (EDITSTREAM FAR *) lpStream;

Parameters

uFormat
A set of bit flags that indicate the data format and replacement options. This value must specify one of the following data formats.
Value | Meaning
SF_TEXT | Text
SF_RTF | Rich Text Format (RTF)

In addition, you can specify the following flags.
Value | Meaning
SFF_SELECTION | The data stream replaces the contents of the current selection. If this flag is not specified, the data stream replaces the entire contents of the control. You can combine this flag with the SF_TEXT or SF_RTF flags.
SFF_PLAINRTF | Language-specific RTF keywords in the stream are ignored. Only keywords common to all languages are streamed in. You can combine this flag with the SF_RTF flag.
SF_UNICODE | Rich Edit 2.0: Indicates Unicode text. You can combine this flag with the SF_TEXT flag.

lpStream
Pointer to an EDITSTREAM structure. On input, the pfnCallback member of this structure must point to an application-defined EditStreamCallback function. On output, the dwError member can contain a nonzero error code if an error occurred.

Return Values

Returns the number of characters read.

Remarks

When you send an EM_STREAMIN message, the rich edit control makes repeated calls to the EditStreamCallback function specified by the pfnCallback member of the EDITSTREAM structure. Each time the callback function is called, it fills a buffer with data to read into the control. This continues until the callback function indicates that the stream-in operation has been completed or an error occurs.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EDITSTREAM, EditStreamCallback, EM_STREAMOUT


EM_STREAMOUT

The EM_STREAMOUT message causes a rich edit control to pass its contents to an application-defined EditStreamCallback callback function. The callback function can then write the stream of data to a file or any other location that it chooses.

EM_STREAMOUT
wParam = (WPARAM) (UINT) uFormat;
lParam = (LPARAM) (EDITSTREAM FAR *) lpStream;

Parameters

uFormat
Value specifying one of the following data formats:
Value | Meaning
SF_TEXT | Text with spaces in place of OLE objects
SF_RTF | Rich Text Format (RTF)
SF_RTFNOOBJS | RTF with spaces in place of OLE object.
SF_TEXTIZED | Text with a text representation of OLE objects.

The SF_RTFNOOBJS option is useful if an application stores OLE objects itself, as RTF representation of OLE objects is not very compact. The control word "\objattph" followed by a space denotes the object position.

You can combine any of the data format values with the SFF_SELECTION flag. If you specify SFF_SELECTION, the rich edit control streams out only the contents of the current selection. Otherwise, the control streams out its entire contents.

You can combine the SF_RTF and SF_RTFNOOBJS values with the SFF_PLAINRTF flag. If you specify SFF_PLAINRTF, the rich edit control streams out only keywords common to all languages; it ignores language-specific RTF keywords.

lpStream
Pointer to an EDITSTREAM structure. On input, the pfnCallback member of this structure must point to an application-defined EditStreamCallback function. On output, the dwError member can contain a nonzero error code if an error occurred.

Return Values

Returns the number of characters written to the data stream.

Remarks

When you send an EM_STREAMOUT message, the rich edit control makes repeated calls to the EditStreamCallback function specified by the pfnCallback member of the EDITSTREAM structure. Each time it calls the callback function, the control passes a buffer containing a portion of the contents of the control. This process continues until the control has passed all its contents to the callback function, or until an error occurs.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EDITSTREAM, EditStreamCallback, EM_STREAMIN


Rich Edit Notification Messages

Rich edit controls support most of the notification messages used with edit controls, plus the following notification messages. A rich edit control sends the following notification messages only if they have been enabled by using the EM_SETEVENTMASK message.

EN_CORRECTTEXT
EN_DROPFILES
EN_IMECHANGE
EN_LINK
EN_MSGFILTER
EN_OLEOPFAILED
EN_PROTECTED
EN_REQUESTRESIZE
EN_SAVECLIPBOARD
EN_SELCHANGE
EN_STOPNOUNDO


EN_CORRECTTEXT

Notifies a rich edit control's parent window that a SYV_CORRECT gesture occurred. A rich edit control sends this notification message in the form of a WM_NOTIFY message.

EN_CORRECTTEXT
wParam = (WPARAM) (UINT) uID;
lParam = (LPARAM) (ENCORRECTTEXT FAR *) lpEnCorrectText;

Parameters

uID
Identifier of the rich edit control.
lpEnCorrectText
Pointer to an ENCORRECTTEXT structure specifying the selection to be corrected.

Return Values

Returns zero to ignore the action, nonzero to process it.

Remarks

This message is sent only if pen capabilities are available.

To receive EN_CORRECTTEXT notifications, specify the ENM_CORRECTTEXT flag in the mask sent with the EM_SETEVENTMASK message.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Notification Messages, ENCORRECTTEXT, WM_NOTIFY


EN_DROPFILES

The EN_DROPFILES notification message notifies a rich edit control's parent window that the user is attempting to drop files into the control. A rich edit control sends this notification message in the form of a WM_NOTIFY message when it receives the WM_DROPFILES message.

EN_DROPFILES
wParam = (WPARAM) (UINT) uID;
lParam = (LPARAM) (ENDROPFILES FAR *) lpEnDropFiles;

Parameters

uID
Identifier of the rich edit control.
lpEnDropFiles
Pointer to an ENDROPFILES structure.

Return Values

Returns a nonzero value to allow the drop operation or zero to ignore the drop.

Remarks

For a rich edit control to receive WM_DROPFILES messages, the parent window must register the control as a drop target by using the DragAcceptFiles function. The control does not register itself.

To receive EN_DROPFILES notifications, specify the ENM_DROPFILES flag in the mask sent with the EM_SETEVENTMASK message.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Notification Messages, DragAcceptFiles, ENDROPFILES, WM_DROPFILES, WM_NOTIFY


EN_IMECHANGE

Notifies a rich edit control's parent that the IME conversion status has changed. This message is available only for Asian-language versions of the operating system.

EN_IMECHANGE
wParam = (WPARAM) (UINT) uID;
lParam = (LPARAM) 0;

Parameters

uID
Identifier of the rich edit control.

Return Values

Returns zero.

Remarks

To receive EN_IMECHANGE notifications, specify the ENM_IMECHANGE flag in the mask sent with the EM_SETEVENTMASK message.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Unsupported.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Notification Messages


EN_LINK

[This is preliminary documentation and subject to change.]

A rich edit control sends EN_LINK notification messages when it receives various messages, such as mouse click messages, while the mouse pointer is over text that has the CFE_LINK effect. For more information about the CFE_LINK effect, see the following Remarks section.

The parent window of the control receives this notification message through the WM_NOTIFY message.

EN_LINK
idEditCtrl = (int) LOWORD(wParam); // identifier of edit control
pEnlink = (ENLINK *) lParam;       // pointer to ENLINK structure

Parameters

idEditCtrl
Identifier of the rich edit control.
pEnlink
Pointer to an ENLINK structure. The structure contains an NMHDR structure, information about the message received by the control, and a CHARRANGE structure that indicates the range of characters that have the CFE_LINK effect.

Return Values

If you return zero, the control proceeds with its normal handling of the message.

If you return a nonzero value, the control does not handle the message.

Remarks

To receive EN_LINK notifications, specify the ENM_LINK flag in the mask sent with the EM_SETEVENTMASK message.

A rich edit control sends EN_LINK notifications when it receives the following messages while the mouse pointer is over text that has the CFE_LINK effect:

WM_LBUTTONDBLCLK
WM_LBUTTONDOWN
WM_LBUTTONUP
WM_MOUSEMOVE
WM_RBUTTONDBLCLK
WM_RBUTTONDOWN
WM_RBUTTONUP
WM_SETCURSOR

The CFE_LINK effect typically identifies a range of text that contains a URL. Applications can handle the EN_LINK notification by changing the mouse pointer when it is over the URL, or by starting a browser to view the location identified by the URL.

Rich Edit 2.0 and later: If you send the EM_AUTOURLDETECT message to enable automatic URL detection, the rich edit control automatically sets the CFE_LINK effect for modified text that it identifies as a URL.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Notification Messages, CHARRANGE, EM_AUTOURLDETECT, ENLINK, NMHDR


EN_MSGFILTER

The EN_MSGFILTER notification message notifies a rich edit control's parent window of a keyboard or mouse event in the control. A rich edit control sends this notification message in the form of a WM_NOTIFY message.

EN_MSGFILTER
wParam = (WPARAM) (UINT) uID;
lParam = (LPARAM) (MSGFILTER) lpMsgFilter;

Parameters

uID
Identifier of the rich edit control.
lpMsgFilter
Pointer to a MSGFILTER structure containing information about the keyboard or mouse message. If the parent window modifies this structure and returns a nonzero value, the modified message is processed instead of the original one.

Return Values

Returns a nonzero value if the control should process the event, or zero if the control should ignore the event.

Remarks

To receive EN_MSGFILTER notifications for keyboard events, specify the ENM_KEYEVENTS flag in the mask sent with the EM_SETEVENTMASK message. To receive EN_MSGFILTER notifications for mouse events, specify the ENM_MOUSEEVENTS flag.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Notification Messages, MSGFILTER, WM_NOTIFY


EN_OLEOPFAILED

Notifies a rich edit control's parent window that a user action on an OLE object has failed.

EN_OLEOPFAILED
wParam = (WPARAM) (UINT) uID;
lParam = (LPARAM) (ENOLEOPFAILED *) lpeoof;

Parameters

uID
Identifier of the rich edit control.
lpeoof
Pointer to an ENOLEOPFAILED structure that contains information about the failure.

Return Values

Returns zero.

ENOLEOPFAILED

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Notification Messages


EN_PROTECTED

The EN_PROTECTED notification message notifies a rich edit control's parent window that the user is taking an action that would change a protected range of text. A rich edit control sends this notification message in the form of a WM_NOTIFY message.

EN_PROTECTED
wParam = (WPARAM) (UINT) uID;
lParam = (LPARAM) (ENPROTECTED FAR *) lpEnProtected;

Parameters

uID
Identifier of the rich edit control.
lpEnProtected
Pointer to an ENPROTECTED structure containing information about the message that triggered the notification.

Return Values

Returns zero to allow the operation or a nonzero value to prevent it.

Remarks

If zero is returned and the msg, wParam, and lParam members of the ENPROTECTED structure are changed, the control processes the revised message instead of the original message.

To receive EN_PROTECTED notifications, specify the ENM_PROTECTED flag in the mask sent with the EM_SETEVENTMASK message.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Notification Messages, ENPROTECTED, WM_NOTIFY


EN_REQUESTRESIZE

The EN_REQUESTRESIZE notification message notifies a rich edit control's parent window that the control's contents are either smaller or larger than the control's window size. A rich edit control sends this notification message in the form of a WM_NOTIFY message.

EN_REQUESTRESIZE
wParam = (WPARAM) (UINT) uID;
lParam = (LPARAM) (REQRESIZE FAR *) lpReSize;

Parameters

uID
Identifier of the rich edit control.
lpReSize
Pointer to a REQRESIZE structure.

Return Values

No return value.

Remarks

To support the bottomless behavior of a rich edit control, the parent window must resize the control when it receives this notification message.

To receive EN_REQUESTRESIZE notifications, specify the ENM_REQUESTRESIZE flag in the mask sent with the EM_SETEVENTMASK message.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Notification Messages, REQRESIZE, WM_NOTIFY


EN_SAVECLIPBOARD

Notifies the rich edit control's parent window that the control is closing and the clipboard contains information.

EN_SAVECLIPBOARD
wParam = (WPARAM) (UINT) uID;
lParam = (LPARAM) (ENSAVECLIPBOARD *) lpesc;

Parameters

uID
Identifier of the rich edit control.
lpesc
Pointer to an ENSAVECLIPBOARD structure that contains information about clipboard information.

Return Values

Returns zero if the clipboard should be made available to other applications, nonzero if the clipboard should not be saved.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Notification Messages, ENSAVECLIPBOARD


EN_SELCHANGE

The EN_SELCHANGE notification message notifies a rich edit control's parent window that the current selection has changed. A rich edit control sends this notification message in the form of a WM_NOTIFY message.

EN_SELCHANGE
wParam = (WPARAM) (UINT) uID;
lParam = (LPARAM) (SELCHANGE FAR *) lpSelChange;

Parameters

uID
Identifier of the rich edit control.
lpSelChange
Pointer to a SELCHANGE structure.

Return Values

No return value.

Remarks

To receive EN_SELCHANGE notifications, specify the ENM_SELCHANGE flag in the mask sent with the EM_SETEVENTMASK message.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Notification Messages, SELCHANGE, WM_NOTIFY


EN_STOPNOUNDO

Notifies a rich edit control's parent window that an action occurred for which the control cannot allocate enough memory to maintain the undo state. A rich edit control sends this notification message in the form of a WM_NOTIFY message.

EN_STOPNOUNDO
wParam = (WPARAM) (UINT) uID;
lParam = (LPARAM) (NMHDR FAR *) lpNmHdr;

Parameters

uID
Identifier of the rich edit control.
lpNmHdr
Pointer to an NMHDR structure.

Return Values

Returns zero to continue the action, nonzero to stop it.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Notification Messages, NMHDR, WM_NOTIFY


Rich Edit OLE Interfaces

The rich edit control supports the client functionality defined by OLE. The control provides full support for most OLE client features. It does not support linking to its contents. The client is responsible for dialogs and error messages, managing storage for OLE objects, and document and application window level in-place activation support. The client can use the EM_GETOLEINTERFACE message to obtain an IRichEditOle interface from the rich edit control which allows it to manage objects. The client uses the EM_SETOLECALLBACK message to register an IRichEditOleCallback interface that the control uses to obtain the required interfaces and storage.

The following OLE interfaces are used with rich text edit controls:

IRichEditOle
IRichEditOleCallback


IRichEditOle

Specifies an interface used by the client of a rich text edit control to carry out OLE-related operations. The IRichEditOle interface has the following methods:

Methods in Vtable Order

IUnknown Methods | Description
QueryInterface | Returns pointers to supported interfaces.
AddRef | Increments reference count.
Release | Decrements reference count.

IRichEditOle Methods | Description
GetClientSite | Retrieves an IOleClientSite interface to use when creating a new object.
GetObjectCount | Returns the number of objects contained in a rich edit control.
GetLinkCount | Returns the number of objects in a rich edit control that are links.
GetObject | Returns information from a REOBJECT structure about an object in a rich edit control.
InsertObject | Inserts an object into a rich edit control.
ConvertObject | Converts an object to a new type.
ActivateAs | Unloads objects of the old class, telling OLE to treat those objects as objects of the new class, and reloading the objects.
SetHostNames | Sets the "host names" to be given to objects as they are inserted to a rich edit control.
SetLinkAvailable | Sets the value of the link available bit in the object's flags.
SetDvaspect | Sets the aspect that a rich edit control uses to draw an object.
HandsOffStorage | Tells a rich edit control to release its reference to the storage interface associated with the specified object.
SaveCompleted | Tells a rich edit control that the most recent save operation has been completed, and that it should hold on to a different storage for the object.
InPlaceDeactivate | Tells a rich edit control to deactivate the currently active in-place object, if any.
ContextSensitiveHelp | Tells a rich edit control to transition into or out of context-sensitive help mode.
GetClipboardData | Retrieves a clipboard object for a range in an edit control.
ImportDataObject | Imports a clipboard object into a rich edit control, replacing the current selection.


IRichEditOle::ActivateAs

Handles OLE "Activate As" behavior by unloading all objects of the old class, telling OLE to treat those objects as objects of the new class, and reloading the objects. If objects cannot be reloaded, they are deleted.

HRESULT ActivateAs(
  REFCLSID rclsid,
  REFCLSID rclsidAs
);

Parameters

rclsid
Class identifier of the old class.
rclsidAs
Class identifier of the new class.

Return Values

Returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success or an SCODE returned from OLE.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit OLE Interfaces, IRichEditOle


IRichEditOle::ContextSensitiveHelp

Tells a rich edit control that it should transition into or out of context sensitive help mode. A rich edit control calls the ContextSensitiveHelp method of any in place object which is currently active if a state change is occuring.

HRESULT ContextSensitiveHelp(
  BOOL fEnterMode
);

Parameters

fEnterMode
TRUE if entering context sensitive help mode; otherwise, FALSE.

Return Values

Returns success status. Can use GetScode to retrieve an SCODE. Can be S_OK on success or some other value returned by OLE.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit OLE Interfaces, IRichEditOle


IRichEditOle::ConvertObject

Converts an object to a new type. This call does reload the object but does not force an update; the caller must do this.

HRESULT ConvertObject(
  LONG iob,
  REFCLSID rclsidNew,
  LPCSTR lpstrUserTypeNew
);

Parameters

iob
Index of the object to convert. If this parameter is REO_IOB_SELECTION, the selected object is to be converted.
rclsidNew
Class identifier of the class to which the object is to be converted.
szUserTypeNew
User-visible type name of the class to which the object is to be converted.

Return Values

Returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success or E_INVALIDARG if the index is invalid, or an SCODE returned from OLE.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit OLE Interfaces, IRichEditOle


IRichEditOle::GetClientSite

Retrieves an IOleClientSite interface to be used when creating a new object. All objects inserted into a rich edit control must use client site interfaces returned by this function. A client site may be used with exactly one object.

HRESULT GetClientSite(
  LPOLECLIENTSITE FAR *lplpolesite
);

Parameters

lplpoleclientsite
Pointer to the pointer variable that receives the address of the IOleClientSite interface.

Return Values

Returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success or E_OUTOFMEMORY if memory could not be allocated for the client site.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit OLE Interfaces, IRichEditOle


IRichEditOle::GetClipboardData

Retrieves a clipboard object for a range in an edit control.

HRESULT GetClipboardData(
  CHARRANGE FAR *lpchrg,
  DWORD reco,
  LPDATAOBJECT FAR *lplpdataobj
);

Parameters

lpchrg
Pointer to the CHARRANGE structure specifying the range to create the clipboard object for.
reco
Clipboard operation flag. Can be one of these values.
RECO_COPY | Copy to the clipboard.
RECO_CUT | Cut to the clipboard.
RECO_DRAG | Drag operation (drag and drop)
RECO_DROP | Drop operation (drag and drop).
RECO_PASTE | Paste from the clipboard.

lplpdataobj
Pointer to the DATAOBJECT structure that receives the clipboard object representing the range specified in the lpchrg parameter.

Return Values

Returns success status.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit OLE Interfaces, CHARRANGE, IRichEditOle


IRichEditOle::GetLinkCount

Returns the number of objects in a rich edit control that are links.

LONG GetLinkCount();

Return Values

Returns the number of links.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit OLE Interfaces, IRichEditOle


IRichEditOle::GetObject

Returns information from a REOBJECT structure about an object in a rich edit control.

HRESULT GetObject(
  LONG iob,
  REOBJECT FAR *lpreobject,
  DWORD dwFlags
);

Parameters

iob
Zero-based index specifying which object to return information about. If this parameter is REO_IOB_USE_CP, information about the object at the character position specified by the REOBJECT structure is returned.
lpreobject
Pointer to a REOBJECT structure that receives information about the object. The reference count of the interfaces returned in this structure has been incremented; it is the responsibility of the caller to use the Release function to decrement the count.
dwFlags
Operation flags specifying which interfaces to return in the structure. Can be a combination of these values:
REO_GETOBJ_POLEOBJ | Get OLE object interface.
REO_GETOBJ_PSTG | Get Storage interface.
REO_GETOBJ_POLESITE | Get OLE site interface.
REO_GETOBJ_NO_INTERFACES | Get no interfaces.
REO_GETOBJ_ALL_INTERFACES | Get all interfaces.

Return Values

Returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success or E_INVALIDARG if no buffer for the REOBJECT structure was given, or the iob or character position is invalid.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit OLE Interfaces, IRichEditOle, REOBJECT


IRichEditOle::GetObjectCount

Returns the number of objects currently contained in a rich edit control.

LONG GetObjectCount();

Return Values

Returns the number of objects.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit OLE Interfaces, IRichEditOle


IRichEditOle::HandsOffStorage

Tells a rich edit control to release its reference to the storage interface associated with the specified object. This call does not call the object's IPersistStorage::HandsOffStorage method, the caller must do that.

HRESULT HandsOffStorage(
  LONG iob
);

Parameters

iob
Index of the object whose storage is to be released. If this parameter is REO_IOB_SELECTION, the selected object's storage is to be released.

Return Values

Returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success or E_INVALIDARG if the index is invalid.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit OLE Interfaces, IPersistStorage::HandsOffStorage, IRichEditOle


IRichEditOle::ImportDataObject

Imports a clipboard object into a rich edit control, replacing the current selection.

HRESULT ImportDataObject(
  LPDATAOBJECT lpdataobj,
  CLIPFORMAT cf,
  HGLOBAL hMetaPict
);

Parameters

lpdataobj
Pointer to a DATAOBJECT structure specifying the clipboard object to import.
cf
Clipboard format to use or zero to use the best available format.
hMetaPict
Handle to a metafile containing the icon view of an object. Used only if the DVASPECT_ICON display aspect is required by Paste Special command.

Return Values

Returns success status.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit OLE Interfaces, IRichEditOle


IRichEditOle::InPlaceDeactivate

Tells a rich edit control to deactivate the currently active in-place object, if any.

HRESULT InPlaceDeactivate();

Return Values

Returns success status. Can use GetScode to retrieve an SCODE. Can be S_OK on success or some other value returned by OLE. No error is returned if there is no active in-place object.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit OLE Interfaces, IRichEditOle


IRichEditOle::InsertObject

Inserts an object into a rich edit control.

HRESULT InsertObject(
  REOBJECT FAR *lpreobject
);

Parameters

lpreobject
Pointer to a REOBJECT structure containing the object information and interfaces. The rich edit control automatically increments the reference count for the interfaces if it holds onto them, so the caller can safely release the interfaces if not needed.

Return Values

Returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success or E_OUTOFMEMORY if memory could not be allocated to insert the object.

If the cp member of the REOBJECT structure is REO_CP_SELECTION, the selection is replaced with the specified object.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit OLE Interfaces, IRichEditOle, REOBJECT


IRichEditOle::SaveCompleted

Tells a rich edit control that the most recent save operation has been completed, and that it should hold on to a different storage for the object.

HRESULT SaveCompleted(
  LONG iob,
  LPSTORAGE lpstg
);

Parameters

iob
Index of the object whose storage is being specified. If this parameter is REO_IOB_SELECTION, the selected object is used.
pstg
New storage for the object. If the storage is not NULL, the rich edit control releases any storage it is currently holding for the object, and uses this new storage instead.

Return Values

Returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success or E_INVALIDARG if the index is invalid.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit OLE Interfaces, IRichEditOle


IRichEditOle::SetDvaspect

Sets the aspect that a rich edit control uses to draw an object. This call does not change the drawing information cached in the object; this must be done by the caller. The call does cause the object to be redrawn.

HRESULT SetDvaspect(
  LONG iob,
  DWORD dvaspect
);

Parameters

iob
Index of the object whose aspect is to be set. If this parameter is REO_IOB_SELECTION, the aspect of the selected object is to be set.
dvaspect
Aspect to use when drawing. The values are defined by OLE.

Return Values

Returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success or E_INVALIDARG if the index is invalid.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit OLE Interfaces, IRichEditOle


IRichEditOle::SetHostNames

Sets the "host names" to be given to objects as they are inserted to a rich edit control. The host names are used in the user interface of servers to describe the container context of opened objects.

HRESULT SetHostNames(
  LPCSTR lpstrContainerApp,
  LPCSTR lpstrContainerObj
);

Parameters

szContainerApp
Null-terminated name of the container application.
szContainerObj
Null-terminated name of the container document or object.

Return Values

Returns success status. Use GetScode to retrieve an scode. Can be S_OK on success or E_OUTOFMEMORY if memory could not be allocated to remember the strings.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit OLE Interfaces, IRichEditOle


IRichEditOle::SetLinkAvailable

Sets the value of the link available bit in the object's flags. The link available bit defaults to TRUE. It should be set to FALSE if any errors occur on the link which would indicate problems connecting to the linked object or application. When those problems are repaired, the bit should be set to TRUE again.

HRESULT SetLinkAvailable(
  LONG iob,
  BOOL fAvailable
);

Parameters

iob
Index of object whose bit is to be set. If this parameter is REO_IOB_SELECTION, the bit on the selected object is to be set.
fAvailable
Value to set the bit to. Can be TRUE or FALSE.

Return Values

Returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success or E_INVALIDARG if the index is invalid.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit OLE Interfaces, IRichEditOle


IRichEditOleCallback

Specifies an interface used by a rich text edit control to retrieve OLE-related information from its client. A rich edit control's client is responsible for implementing this interface and assigning it to the control by using the EM_SETOLECALLBACK message. The IRichEditOleCallback interface has the following methods:

Methods in Vtable Order

IUnknown Methods | Description
QueryInterface | Returns pointers to supported interfaces.
AddRef | Increments reference count.
Release | Decrements reference count.

IRichEditOleCallback Methods | Description
GetNewStorage | Provides storage for a new object pasted from the clipboard or read in from an RTF stream.
GetInPlaceContext | Provides the application and document level interfaces and information required to support in-place activation.
ShowContainerUI | Tells the application whether to display its container user interface.
QueryInsertObject | Queries the application as to whether an object should be inserted.
DeleteObject | Notification that an object is about to be deleted from a rich edit control.
QueryAcceptData | Called on a paste or drag to determine if the data pasted/dragged should be accepted.
ContextSensitiveHelp | Tells the application that it should transition into or out of context sensitive help mode.
GetClipboardData | Allows the client to supply its own clipboard object.
GetDragDropEffect | Allows the client to specify the effects of a drop operation.
GetContextMenu | Queries the application for a context menu to use on a right mouse button down event.


IRichEditOleCallback::ContextSensitiveHelp

Tells the application that it should transition into or out of context sensitive help mode. This member should implement the functionality described for IOleInPlaceSite::ContextSensitiveHelp (as described in the OLE documentation).

HRESULT ContextSensitiveHelp(
  BOOL fEnterMode
);

Parameters

fEnterMode
TRUE if entering context sensitive help mode; otherwise, FALSE.

Return Values

Returns success status.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit OLE Interfaces, IRichEditOleCallback


IRichEditOleCallback::DeleteObject

Notification that an object is about to be deleted from a rich edit control. The object is not necessarily being released when this member is called.

HRESULT DeleteObject(
  LPOLEOBJECT lpoleobj
);

Parameters

lpoleobj
Pointer to the OLEOBJECT structure specifying the object that is being deleted.

Return Values

No return value.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit OLE Interfaces, IRichEditOleCallback


IRichEditOleCallback::GetClipboardData

Allows the client to supply its own clipboard object.

HRESULT GetClipboardData(
  CHARRANGE FAR *lpchrg,
  DWORD reco,
  LPDATAOBJECT FAR *lplpdataobj
);

Parameters

lpchrg
Pointer to the CHARRANGE structure specifying the range the clipboard object is for.
reco
Clipboard operation flag. Can be one of these values.
RECO_COPY | Copy to the clipboard.
RECO_CUT | Cut to the clipboard.
RECO_DRAG | Drag operation (drag and drop)
RECO_DROP | Drop operation (drag and drop).
RECO_PASTE | Paste from the clipboard.

lplpdataobj
Pointer to the pointer variable that receives the address of the IDataObject implementation representing the range specified in the lpchrg parameter. The value of lppdataobj is ignored if an error is returned.

Return Values

Returns success status. If the SCODE of the return value is E_NOTIMPL, the rich edit control creates its own clipboard object. If the SCODE of the return value is a failure other than E_NOTIMPL the operation fails.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit OLE Interfaces, CHARRANGE, IDataObject, IRichEditOleCallback


IRichEditOleCallback::GetContextMenu

Queries the application for a context menu to use on a right mouse down.

HRESULT GetContextMenu(
  WORD seltyp,
  LPOLEOBJECT lpoleobj,
  CHARRANGE FAR *lpchrg,
  HMENU FAR *lphmenu
);

Parameters

seltype
selection type
lpoleobj
Pointer to a OLEOBJECT structure specifying the first selected OLE object if the selection contains one or more objects NULL otherwise. The caller must use AddRef to increment the object reference count if it holds onto it.
lpchrg
Pointer to a CHARRANGE structure containing the current selection.
lphmenu
Pointer to a variable containing the handle of a context menu to use. This parameter is ignored if an error is returned. A rich edit control destroys the menu when it is finished with it so the client should not.

Return Values

Returns success status.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit OLE Interfaces, CHARRANGE, IRichEditOleCallback


IRichEditOleCallback::GetDragDropEffect

Allows the client to specify the effects of a drop operation.

HRESULT GetDragDropEffect(
  BOOL fDrag,
  DWORD grfKeyState,
  LPDWORD pdwEffect
);

Parameters

fDrag
TRUE if the query is for a IDropTarget::DragEnter or IDropTarget::DragOver FALSE if the query is for IDropTarget::Drop.
grfKeyState
Key state as defined by OLE.
pdwEffect
Pointer to the variable that contains the effect normally used by a rich edit control. On return, the variable is set to the effect to use.

Return Values

No return value.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit OLE Interfaces, IDropTarget::DragEnter, IDropTarget::DragOver, IDropTarget::Drop IRichEditOleCallback


IRichEditOleCallback::GetInPlaceContext

Provides the application and document level interfaces and information required to support in-place activation.

HRESULT GetInPlaceContext(
  LPOLEINPLACEFRAME FAR *lplpFrame,
  LPOLEINPLACEUIWINDOW FAR *lplpDoc,
  LPOLEINPLACEFRAMEINFO lpFrameInfo
);

Parameters

lplpframe
Pointer to the pointer variable that receives the address of the IOleInPlaceFrame interface that represents the frame window of the a rich edit control client. Use the AddRef method to increment the reference count the rich edit control releases the interface when it no longer needed.
lplpDoc
Pointer to the pointer variable that receives the address of the IOleInPlaceUIWindow interface that represents the document window of the rich edit control client. An interface need not be returned if the frame and document windows are the same. Use the AddRef method to increment the reference count the rich edit control releases the interface when it no longer needed.
lpFrameInfo
Pointer to the OLEINPLACEFRAMEINFO structure that receives the accelerator information.

Return Values

Returns success status.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit OLE Interfaces, IOleInPlaceFrame, IRichEditOleCallback, OLEINPLACEFRAMEINFO


IRichEditOleCallback::GetNewStorage

Provides storage for a new object pasted from the clipboard or read in from an RTF stream.

HRESULT GetNewStorage(
  LPSTORAGE FAR *lplpstg
);

Parameters

lplpstg
Address to the pointer variable that receives the address of the IStorage interface created for the new object.

Return Values

Returns success status.

This method must be implemented to allow cut/copy/paste and drag and drop of OLE objects.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit OLE Interfaces, IRichEditOleCallback, IStorage


IRichEditOleCallback::QueryAcceptData

Called on a paste or drag to determine if the data pasted/dragged should be accepted.

HRESULT QueryAcceptData(
  LPDATAOBJECT lpdataobj,
  CLIPFORMAT FAR *lpcfFormat,
  DWORD reco,
  BOOL fReally,
  HGLOBAL hMetaPict
);

Parameters

lpdataobj
Pointer to the DATAOBJECT structure specifying the data object being pasted or dragged.
lpcfFormat
Pointer to the clipboard format that will be used for the paste or drop operation. If the value pointed to by lpcfFormat is zero, the best available format will be used. If the callback changes the value pointed to by lpcfFormat, the rich edit control only uses that format and the operation will fail if the format is not available.
reco
Clipboard operation flag. Can be one of these values.
RECO_DROP | Drop operation (drag and drop).
RECO_PASTE | Paste from the clipboard.

fReally
Nonzero if the paste or drop is actually happening, zero if this is just a query, such as for EM_CANPASTE.
hMetaPict
Handle to a metafile containing the icon view of an object if DVASPECT_ICON is being imposed on a object by Paste Special.

Return Values

Returns success status. If the SCODE of the result is a failure SCODE, the rich edit control refuses the data and terminates the operation. If the SCODE of the result is S_OK, the control checks the data itself for acceptable formats. A return of a successful SCODE other than S_OK means that the callback either checked the data itself (if fReally is FALSE) or imported the data itself (if fReally is TRUE).

If the application returns a successful result other than S_OK, a rich edit control will not check the read-only state of the edit control.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit OLE Interfaces, IRichEditOleCallback


IRichEditOleCallback::QueryInsertObject

Queries the application as to whether an object should be inserted. This member is called when pasting and when reading RTF.

HRESULT QueryInsertObject(
  LPCLSID lpclsid,
  LPSTORAGE lpstg,
  LONG cp
);

Parameters

lpclsid
Class identifier of the object to be inserted.
lpstg
Storage containing the object.
cp
Character position at which the object will be inserted.

Return Values

Returns success status. If the SCODE of the result is not S_OK, the object is not inserted.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit OLE Interfaces, IRichEditOleCallback


IRichEditOleCallback::ShowContainerUI

Tells the application whether to display its container user interface. The rich edit control looks ahead for doubleclicks and defers the call if appropriate (as described in the OLE documentation). Applications may defer hiding adornments until an IOleInPlaceFrame::SetBorderSpace call is received.

HRESULT ShowContainerUI(
  BOOL fShow
);

Parameters

fShow
Show container UI flag. TRUE to show, FALSE otherwise.

Return Values

Returns success status.

This function is called by the OnUIActivate and OnUIDeActivate methods of the IOleInPlaceSite interface.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richole.h.

See Also

Rich Edit Controls Overview, Rich Edit OLE Interfaces, IRichEditOleCallback, OnUIActivate, OnUIDeActivate


Rich Edit Enumeration Types

[This is preliminary documentation and subject to change.]

The following enumeration types are used with rich edit controls.

TEXTMODE
UNDONAMEID


TEXTMODE

[This is preliminary documentation and subject to change.]

The TEXTMODE enumeration type contains values that indicate the text mode of a rich edit control. The EM_SETTEXTMODE and EM_GETTEXTMODE messages use this enumeration type.

typedef enum tagTextMode
{
    TM_PLAINTEXT        = 1,
    TM_RICHTEXT         = 2,    // default behavior
    TM_SINGLELEVELUNDO  = 4,
    TM_MULTILEVELUNDO   = 8,    // default behavior
    TM_SINGLECODEPAGE   = 16,
    TM_MULTICODEPAGE    = 32
} TEXTMODE;

Enumerator Value | Meaning
TM_PLAINTEXT | Indicates plain text mode, in which the control is similar to a standard edit control. For more information about plain text mode, see the following Remarks section.
TM_RICHTEXT | Indicates rich text mode, in which the control has the standard rich edit functionality. Rich text mode is the default setting.
TM_SINGLELEVELUNDO | The control allows the user to undo only the last action in the undo queue.
TM_MULTILEVELUNDO | The control supports multiple undo actions. This is the default setting. Use the EM_SETUNDOLIMIT message to set the maximum number of undo actions.
TM_SINGLECODEPAGE | Not supported.
TM_MULTICODEPAGE | Not supported.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Enumeration Types, EM_SETTEXTMODE, EM_GETTEXTMODE


UNDONAMEID

[This is preliminary documentation and subject to change.]

The UNDONAMEID enumeration type contains values that indicate types of rich edit control actions that can be undone or redone. The EM_GETREDONAME and EM_GETUNDONAME messages use this enumeration type to return a value.

typedef enum _undonameid {
    UID_UNKNOWN    = 0,
    UID_TYPING     = 1,
    UID_DELETE     = 2,
    UID_DRAGDROP   = 3,
    UID_CUT        = 4,
    UID_PASTE      = 5
} UNDONAMEID;

Enumerator Value | Meaning
UID_UNKNOWN | The type of undo action is unknown.
UID_TYPING | Typing operation.
UID_DELETE | Delete operation.
UID_DRAGDROP | Drag-drop operation.
UID_CUT | Cut operation.
UID_PASTE | Paste operation.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Enumeration Types, EM_GETREDONAME, EM_GETUNDONAME


Rich Edit Constants

The following sections describe constants used with rich edit controls.


Rich Edit Control Styles

The following window styles are unique to rich edit controls:

Style | Description
ES_DISABLENOSCROLL | Disables scrollbars instead of hiding them when they are not needed.
ES_EX_NOCALLOLEINIT | Prevents the control from calling the OleInitialize function when created. Useful only in dialog templates because CreateWindowEx does not accept this style.
ES_NOIME | Disables the input method editor (IME) operation. Available for Asian-languages only.
ES_SAVESEL | Preserves the selection when the control loses the focus. By default, the entire contents of the control are selected when it regains the focus.
ES_SELFIME | Directs the rich edit control to allow the application to handle all IME operations. Available for Asian-languages only.
ES_SUNKEN Displays the control with a sunken border style so that the rich edit control appears recessed into its parent window.

Windows 95: Applications developed for Windows 95 should use WS_EX_CLIENTEDGE instead of ES_SUNKEN.
ES_VERTICAL | Draws text and objects in a vertical direction. Available for Asian-languages only.

Rich edit controls also support the following edit control styles. To allow more than one line of text, you must specify the ES_MULTILINE style.

ES_AUTOHSCROLL | ES_NOHIDESEL
ES_AUTOVSCROLL | ES_READONLY
ES_CENTER | ES_RIGHT
ES_LEFT | ES_WANTRETURN
ES_MULTILINE |

Rich edit controls do not support the following edit control styles:

ES_LOWERCASE | ES_PASSWORD
ES_OEMCONVERT | ES_UPPERCASE


Rich Edit Control Event Mask Flags

The event mask specifies which notification messages a rich edit control sends its parent window. The event mask can be zero or more of these values:

Value | Meaning
ENM_CHANGE | Sends EN_CHANGE notifications.
ENM_CORRECTTEXT | Sends EN_CORRECTTEXT notifications.
ENM_DROPFILES | Sends EN_DROPFILES notifications.
ENM_KEYEVENTS | Sends EN_MSGFILTER notifications for keyboard events.
ENM_MOUSEEVENTS | Sends EN_MSGFILTER notifications for mouse events.
ENM_PROTECTED | Sends EN_PROTECTED notifications.
ENM_RESIZEREQUEST | Sends EN_REQUESTRESIZE notifications.
ENM_SCROLL | Sends EN_HSCROLL notifications.
ENM_SELCHANGE | Sends EN_SELCHANGE notifications.
ENM_UPDATE | Sends EN_UPDATE notifications.

The default event mask is ENM_NONE in which case no notification messages are sent to the parent window. You can retrieve and set the event mask for a rich edit control by using the ENM_GETEVENTMASK and ENM_SETEVENTMASK messages.


Scroll Bars

A window in an Win32-based application can display a data object, such as a document or a bitmap, that is larger than the window's client area. When provided with a scroll bar, the user can scroll a data object in the client area to bring into view the portions of the object that extend beyond the borders of the window.


About Scroll Bars

Scroll bars should be included in any window for which the content of the client area extends beyond the window's borders. A scroll bar's orientation determines the direction in which scrolling occurs when the user operates the scroll bar. A horizontal scroll bar enables the user to scroll the content of a window to the left or right. A vertical scroll bar enables the user to scroll the content up or down.


Parts of a Scroll Bar

A scroll bar consists of a shaded shaft with an arrow button at each end and a scroll box (sometimes called a thumb) between the arrow buttons. A scroll bar represents the overall length or width of a data object in a window's client area; the scroll box represents the portion of the object that is visible in the client area. The position of the scroll box changes whenever the user scrolls a data object to display a different portion of it. The system also adjusts the size of a scroll bar's scroll box so that it indicates what portion of the entire data object is currently visible in the window. If most of the object is visible, the scroll box occupies most of the scroll bar's shaft. Similarly, if only a small portion of the object is visible, the scroll box occupies a small part of the shaft.

The user scrolls the content of a window by clicking one of the arrow buttons, by clicking the area in the shaded shaft, or by dragging the scroll box. When the user clicks an arrow button, the application scrolls the content by one unit (typically a single line or column). When the user clicks the shaded areas, the application scrolls the content by one window. The amount of scrolling that occurs when the user drags the scroll box depends on the distance the user drags the scroll box and on the scrolling range of the scroll bar. For more information about the scrolling range, see Scroll Box Position and Scrolling Range.


Standard Scroll Bars and Scroll Bar Controls

A scroll bar is included in a window either as a standard scroll bar or as a scroll bar control. A standard scroll bar is located in the nonclient area of a window. It is created with the window and displayed when the window is displayed. The sole purpose of a standard scroll bar is to enable the user to generate scrolling requests for viewing the entire content of the client area. You can include a standard scroll bar in a window by specifying WS_HSCROLL, WS_VSCROLL, or both styles when you create the window. The WS_HSCROLL style creates a horizontal scroll bar positioned at the bottom of the client area. The WS_VSCROLL style creates a vertical scroll bar positioned at the right of the client area. The SM_CXHSCROLL and SM_CYHSCROLL system metric values define the width and height of a standard horizontal scroll bar. The SM_CXVSCROLL and SM_CYVSCROLL values define the width and height of a standard vertical scroll bar.

A scroll bar control is a control window that belongs to the SCROLLBAR window class. A scroll bar control appears and functions like a standard scroll bar, but it is a separate window. As a separate window, a scroll bar control receives direct input focus, indicated by a flashing caret displayed in the scroll box. Unlike a standard scroll bar, a scroll bar control also has a built-in keyboard interface that enables the user to direct scrolling. You can use as many scroll bar controls as needed in a single window. When you create a scroll bar control, you must specify the scroll bar's size and position. However, if a scroll bar control's window can be resized, adjustments to the scroll bar's size must be made whenever the size of the window changes.

The advantage of using a standard scroll bar is that the system creates the scroll bar and automatically sets its size and position. However, standard scroll bars are sometimes too restrictive. For example, suppose that you want to divide a client area into quadrants and use a separate set of scroll bars to control the content of each quadrant. You cannot use standard scroll bars because you can only create one set of scroll bars for a particular window. Use scroll bar controls instead, because you can add as many of them to a window as you want.

Applications can provide scroll bar controls for purposes other than scrolling the content of a window. For example, a screen saver application might provide a scroll bar for setting the speed at which graphics are moved about on the screen.

A scroll bar control can have a number of styles that serves to control the orientation and position of the scroll bar. You specify the styles that you want when you call the CreateWindowEx function to create a scroll bar control. Some of the styles create a scroll bar control that uses a default width or height. However, you must always specify the x- and y-coordinates and the other dimensions of the scroll bar.

For a table of scroll bar control styles, see Scroll Bar Control Styles.


Scroll Box Position and Scrolling Range

The position of the scroll box is represented as an integer; it is relative to the left or upper end of the scroll bar, depending on whether the scroll bar is horizontal or vertical. The position must be within the minimum and maximum values of the scrolling range. For example, in a scroll bar with a range of 0 through 100, position 50 is in the middle, with the remaining positions distributed equally along the scroll bar. The initial range depends on the scroll bar. Standard scroll bars have an initial range of 0 through 100; scroll bar controls have an empty range (both minimum and maximum values are zero), unless you supply an explicit range when the control is created. You can change the range at any time. You can use the SetScrollInfo function to set the range values, and the GetScrollInfo function to retrieve the current range values.

An application typically adjusts the scroll range to convenient integers, making it easy to translate the scroll box position into a value corresponding to the data object to be scrolled. For example, if an application must display 260 lines of a text file in a window that can show only 16 lines at a time, the vertical scroll bar range can be set to 1 through 244. If the scroll box is at position 1, the first line will be at the top of the window. If the scroll box is at position 244, the last line (line 260) will be at the bottom of the window. If an application attempts to specify a position value that is less than the minimum or more than the maximum, the minimum or maximum scrolling range value is used instead.

You can set a page size for a scroll bar. The page size represents the number of data units that can fit in the client area of the owner window given its current size. For example, if the client area can hold 16 lines of text, an application would set the page size to 16. The system uses the page size, along with the scrolling range and length of the scroll shaft, to set the size of the scroll box. Whenever a window containing a scroll bar is resized, an application should call the SetScrollInfo function to set the page size. An application can retrieve the current page size by calling the sending GetScrollInfo function.

To establish a useful relationship between the scroll bar range and the data object, an application must adjust the range whenever the size of the data object changes.

As the user moves the scroll box in a scroll bar, the scroll bar reports the scroll box position as an integer in the scrolling range. If the position is the minimum value, the scroll box is at the top of a vertical scroll bar or at the left end of a horizontal scroll bar. If the position is the maximum value, the scroll box is at the bottom of a vertical scroll bar or at right end of a horizontal scroll bar.

The maximum value that a scroll bar can report (that is, the maximum scrolling position) depends on the page size. If the scroll bar has a page size greater than one, the maximum scrolling position is less than the maximum range value. You can use the following formula to calculate the maximum scrolling position:

MaxScrollPos = MaxRangeValue - (PageSize - 1)

An application must move the scroll box in a scroll bar. Although the user makes a request for scrolling in a scroll bar, the scroll bar does not automatically update the scroll box position. Instead, it passes the request to the parent window, which must scroll the data and update the scroll box position. An application uses the SetScrollInfo function to update the scroll box position; otherwise, it uses the SetScrollPos function. Because it controls the scroll box movement, the application can move the scroll box in increments that work best for the data being scrolled.


Scroll Bar Visibility

The system hides and disables a standard scroll bar when equal minimum and maximum values are specified. The system also hides and disables a standard scroll bar if you specify a page size that includes the entire scroll range of the scroll bar. This is the way to temporarily hide a scroll bar when it is not needed for the content of the client area. There is no need to make scrolling requests through the scroll bar when it is hidden. The system enables the scroll bar and shows it again when you set the minimum and maximum values to unequal values or when the page size that does not include the entire scroll range. The ShowScrollBar function can also be used to hide or show a scroll bar. It does not affect the scroll bar's range, page size, or scroll box position.

The EnableScrollBar function can be used to disable one or both arrows of a scroll bar. An application displays disabled arrows in gray and does not respond to user input.


Scroll Bar Requests

The user makes scrolling requests by clicking various parts of a scroll bar. The system sends the request to the given window in the form of a WM_HSCROLL or WM_VSCROLL message. A horizontal scroll bar sends the WM_HSCROLL message; a vertical scroll bar sends the WM_VSCROLL message. Each message includes a notification code that corresponds to the user's action, to the handle to the scroll bar (scroll bar controls only), and, in some cases, to the position of the scroll box.

The following figure shows the notification messages that the user generates when clicking various parts of a scroll bar.

The scroll bar notification codes specify the action the user takes. An application examines the codes that accompany the WM_HSCROLL and WM_VSCROLL messages and then performs the appropriate scrolling operation. In the following table of notification messages, the user's action is specified for each message, followed by the application's response. In each case, a unit is defined by the application as appropriate for the given data. For example, the typical unit for scrolling text vertically is a line of text.

Notification message | Action | Response
SB_LINEUP | The user clicks the top scroll arrow. | Decrements the scroll box position; scrolls toward the top of the data by one unit.
SB_LINEDOWN | The user clicks the bottom scroll arrow. | Increments the scroll box position; scrolls toward the bottom of the data by one unit.
SB_LINELEFT | The user clicks the left scroll arrow. | Decrements the scroll box position; scrolls toward the left end of the data by one unit.
SB_LINERIGHT | The user clicks the right scroll arrow. | Increments the scroll box position; scrolls toward the right end of the data by one unit.
SB_PAGEUP | The user clicks the scroll bar shaft above the scroll box. | Decrements the scroll box position by the number of data units in the window; scrolls toward the top of the data by the same number of units.
SB_PAGEDOWN | The user clicks the scroll bar shaft below the scroll box. | Increments the scroll box position by the number of data units in the window; scrolls toward the bottom of the data by the same number of units.
SB_PAGELEFT | The user clicks the scroll bar shaft to the left of the scroll box. | Decrements the scroll box position by the number of data units in the window; scrolls toward the left end of the data by the same number of units.
SB_PAGERIGHT | The user clicks the scroll bar shaft to the right of the scroll box. | Increments the scroll box position by the number of data units in the window; scrolls toward the right end of the data by the same number of units.
SB_THUMBPOSITION | The user releases the scroll box after dragging it. | Sets the scroll box to the position given in the message; scrolls the data by the same number of units the scroll box has moved.
SB_THUMBTRACK | The user drags the scroll box. | Sets the scroll box to the position given in the message and scrolls the data by the same number of units the scroll box has moved for applications that draw data quickly. Applications that cannot draw data quickly must wait for the SB_THUMBPOSITION message before moving the scroll box and scrolling the data.
SB_ENDSCROLL | The user releases the mouse after holding it on an arrow or in the scroll bar shaft. | No response is needed.

A scroll bar generates the SB_THUMBPOSITION and SB_THUMBTRACK notification messages when the user clicks and drags the scroll box. An application should be programmed to process either the SB_THUMBTRACK or the SB_THUMBPOSITION notification message.

The SB_THUMBPOSITION notification message occurs when the user releases the mouse button after clicking the scroll box. An application that processes this message performs the scrolling operation after the user has dragged the scroll box to the desired position and released the mouse button.

SB_THUMBTRACK notification messages occur as the user drags the scroll box. If an application processes SB_THUMBTRACK messages, it can scroll the content of a window as the user drags the scroll box. However, a scroll bar can generate many SB_THUMBTRACK notification messages in a short period, so an application should process these messages only if it can quickly repaint the content of the window.


Keyboard Interface for a Scroll Bar

A scroll bar control provides a built-in keyboard interface that enables the user to issue scrolling requests by using the keyboard; a standard scroll bar does not. When a scroll bar control has the keyboard focus, it sends WM_HSCROLL and WM_VSCROLL messages to its parent window when the user presses the arrow keys. The notification message is sent with each message corresponding to the arrow key the user has pressed. Following are the arrow keys and their corresponding notification messages.

Arrow key | Notification message
down | SB_LINEDOWN or SB_LINERIGHT
end | SB_BOTTOM
home | SB_TOP
left | SB_LINEUP or SB_LINELEFT
pgdn | SB_PAGEDOWN or SB_PAGERIGHT
pgup | SB_PAGEUP or SB_PAGELEFT
right | SB_LINEDOWN or SB_LINERIGHT
up | SB_LINEUP or SB_LINELEFT

Note The keyboard interface of a scroll bar control sends the SB_TOP and SB_BOTTOM notification messages. The SB_TOP message indicates that the user has reached the top value of the scrolling range. An application scrolls the window content downward so that the top of the data object is visible. The SB_BOTTOM message indicates that the user has reached the bottom value of the scrolling range. If an application processes the SB_BOTTOM message, it scrolls the window content upward so that the bottom of the data object is visible.

If you want a keyboard interface for a standard scroll bar, you can create one yourself by processing the WM_KEYDOWN message in your window procedure and then performing the appropriate scrolling action based on the virtual-key code that accompanies the message. For information about how to create a keyboard interface for a scroll bar, see Creating a Keyboard Interface for a Standard Scroll Bar.


Scrolling the Client Area

The simplest way to scroll the content of a client area is to erase and then redraw it. This is the method an application is likely to use with SB_PAGEUP, SB_PAGEDOWN, and SB_TOP notification messages, which typically require completely new content.

For some notification messages, such as SB_LINEUP and SB_LINEDOWN, not all the content need be erased, because some remains visible after scrolling occurs. The ScrollWindowEx function preserves a portion of the client area's content, move the preserved portion a specified amount, and then prepares the rest of the client area for painting new information. ScrollWindowEx uses the BitBlt function to move a specific part of the data object to a new location within the client area. Any uncovered part of the client area (anything not preserved) is invalidated, erased, and painted when the next WM_PAINT message occurs.

The ScrollWindowEx function can be used to exclude a portion of the client area from the scrolling operation. This keeps items with fixed positions, such as child windows, from moving within the client area. It automatically invalidates the portion of the client area that is to receive the new information, so the application does not have to compute its own clipping regions. For more information on clipping, see Clipping.

Usually an application scrolls the content of a window in the direction opposite that indicated by the scroll bar. For example, when the user clicks the shaft in the area below the scroll box, an application scrolls the object in the window upward to reveal a portion of the object that is below the visible portion.

You can also scroll a rectangular region using the ScrollDC function.


Scroll Bar Colors and Metrics

The system-defined color value, COLOR_SCROLLBAR, controls the color within a scroll bar's shaft. Use the GetSysColor function to determine the color of the shaft and the SetSysColors function to set the color of the shaft. Note, however, that this change of color affects all scroll bars in the system.

You can get the dimensions of the bitmaps that the system uses in standard scroll bars by calling the GetSystemMetrics function. Following are the system metric values associated with scroll bars.

System metric | Description
SM_CXHSCROLL | Width of arrow bitmap on horizontal scroll bar
SM_CXHTHUMB | Width of scroll box on horizontal scroll bar. This value retrieves the width a scroll bar that has a page size of zero.
SM_CXVSCROLL | Width of arrow bitmap on vertical scroll bar
SM_CYHSCROLL | Height of arrow bitmap on horizontal scroll bar
SM_CYVSCROLL | Height of arrow bitmap on vertical scroll bar
SM_CYVTHUMB | Height of scroll box on vertical scroll bar. This value retrieves the height of a scroll bar that has a page size of zero.


Using Scroll Bars

  • Creating scroll bars
  • Scrolling text
  • Scrolling a bitmap
  • Creating a keyboard interface for a standard scroll bar


Creating Scroll Bars

When creating an overlapped, pop-up, or child window, you can add standard scroll bars by using the CreateWindowEx function and specifying WS_HSCROLL, WS_VSCROLL, or both styles. Doing this adds a horizontal or vertical scroll bar, or both, to the window. The following example creates a window with standard horizontal and vertical scroll bars.

hwnd = CreateWindowEx(
    0L,                          // no extended styles
    "MyAppClass",                // window class
    "Scroll Bar Application",    // text for window title bar
    WS_OVERLAPPEDWINDOW |        // window styles
        WS_HSCROLL |
        WS_VSCROLL,
    CW_USEDEFAULT,             // default horizontal position
    CW_USEDEFAULT,             // default vertical position
    CW_USEDEFAULT,             // default width
    CW_USEDEFAULT,             // default height
    (HWND) NULL,         // no parent for overlapped windows
    (HMENU) NULL,        // window class menu
    hinst,               // instance owning this window
    (LPVOID) NULL        // pointer not needed
);

To process scroll bar messages for these scroll bars, you must include appropriate code in the main window procedure.

When using the CreateWindowEx function to create a window, you can add a scroll bar control by specifying the scrollbar window class. This creates a horizontal or vertical scroll bar, depending on whether SBS_HORZ or SBS_VERT is specified as the window style. The scroll bar size and its position relative to its parent window can also be specified. The following example creates a horizontal scroll bar control and positions it in the upper right corner of the window.

hwndScroll = CreateWindowEx(
    0L,                          // no extended styles
    "SCROLLBAR",                 // scroll bar control class
    (LPSTR) NULL,                // text for window title bar
    WS_CHILD | SBS_HORZ,         // scroll bar styles
    0,                           // horizontal position
    0,                           // vertical position
    200,                         // width of the scroll bar
    CW_USEDEFAULT,               // default height
    hwnd,                   // handle to main window
    (HMENU) NULL,           // no menu for a scroll bar
    hinst,                  // instance owning this window
    (LPVOID) NULL           // pointer not needed
);


Scrolling Text

This section describes the changes you can make to an application's main window procedure to enable a user to scroll text. The example in Example of Scrolling Text, creates and displays an array of text strings and processes WM_HSCROLL and WM_VSCROLL messages generated by the scroll bars so that the user can scroll text both vertically and horizontally.


Scrolling Text with the WM_CREATE Message

Scrolling units are typically set while processing the WM_CREATE message. It is convenient to base the scrolling units on the dimensions of the font associated with the window's display context (DC). To retrieve the font dimensions for a specific DC, use the GetTextMetrics function.

In the example in Example of Scrolling Text, one vertical scrolling unit is equivalent to the height of a character cell, plus external leading. One horizontal scrolling unit is equivalent to the average width of a character cell. The horizontal scrolling positions, therefore, do not correspond to actual characters, unless the screen font is fixed-width.


Scrolling Text with the WM_SIZE Message

When processing the WM_SIZE message, it is convenient to adjust the scrolling range and scrolling position to reflect the dimensions of the client area as well as the number of lines of text that will be displayed.

The SetScrollInfo function sets the minimum and maximum position values, the page size, and the scrolling position for a scroll bar.


Scrolling Text with the WM_HSCROLL and WM_VSCROLL Messages

The scroll bar sends WM_HSCROLL and WM_VSCROLL messages to the window procedure whenever the user clicks the scroll bar or drags the scroll box. The low-order words of WM_VSCROLL and WM_HSCROLL each contain a notification message that indicates the direction and magnitude of the scrolling action.

When the WM_HSCROLL and WM_VSCROLL messages are processed, the scroll bar notification message is examined and the scrolling increment is calculated. After the increment is applied to the current scrolling position, the window is scrolled to the new position by using the ScrollWindowEx function, and the position of the scroll box is adjusted by using the SetScrollInfo function.

After a window is scrolled, part of its client area is made invalid. To ensure that the invalid region is updated, the UpdateWindow function is used to generate a WM_PAINT message.


Scrolling Text with the WM_PAINT Message

When processing the WM_PAINT message, it is convenient to draw the lines of text that you want to appear in the invalid portion of the window. The example in the following section uses the current scrolling position and the dimensions of the invalid region to determine the range of lines within the invalid region to display them.


Example of Scrolling Text

The following example shows how to have your application scroll text in response to input from the horizontal and vertical scroll bars.

HDC hdc;
PAINTSTRUCT ps;
TEXTMETRIC tm;
SCROLLINFO si;

// These variables are required to display text.

static int xClient;     // width of client area
static int yClient;     // height of client area
static int xClientMax;  // maximum width of client area

static int xChar;       // horizontal scrolling unit
static int yChar;       // vertical scrolling unit
static int xUpper;      // average width of uppercase letters

static int xPos;        // current horizontal scrolling position
static int yPos;        // current vertical scrolling position

static int xMax;        // maximum horizontal scrolling position
static int yMax;        // maximum vertical scrolling position

int xInc;               // horizontal scrolling increment
int yInc;               // vertical scrolling increment

int i;                  // loop counter
int x, y;               // horizontal and vertical coordinates

int FirstLine;          // first line in the invalidated area
int LastLine;           // last line in the invalidated area

// Create an array of lines to display.

#define LINES 27
static char *abc[] = { "anteater", "bear", "cougar", "dingo",
  "elephant", "frog", "gazelle", "hyena", "iguana", "jackal",
  "kangaroo", "llama", "moose", "newt", "octopus", "penguin",
  "quail", "rat", "squid", "tortoise", "urus", "vole",
  "walrus", "xylophone", "yak", "zebra",
  "This line contains many words, but no character. Go figure." };

switch (uMsg)
{
    case WM_CREATE :

        // Get the handle to the client area's device context.

        hdc = GetDC (hwnd);

        // Extract font dimensions from the text metrics.

        GetTextMetrics (hdc, &tm);
        xChar = tm.tmAveCharWidth;
        xUpper = (tm.tmPitchAndFamily & 1 ? 3 : 2) * xChar/2;
        yChar = tm.tmHeight + tm.tmExternalLeading;

        // Free the device context.

        ReleaseDC (hwnd, hdc);

        // Set an arbitrary maximum width for client area.
        // (xClientMax is the sum of the widths of 48 average
        // lowercase letters and 12 uppercase letters.)

        xClientMax = 48 * xChar + 12 * xUpper;

        return 0;

    case WM_SIZE:

        // Retrieve the dimensions of the client area.

        yClient = HIWORD (lParam);
        xClient = LOWORD (lParam);

        // Determine the maximum vertical scrolling position.
        // The two is added for extra space below the lines
        // of text.

        yMax = max (0, LINES + 2 - yClient/yChar);

        // Make sure the current vertical scrolling position
        // does not exceed the maximum.

        yPos = min (yPos, yMax);

        // Adjust the vertical scrolling range and scroll box
        // position to reflect the new yMax and yPos values.

        si.cbSize = sizeof(si);
        si.fMask  = SIF_RANGE | SIF_PAGE | SIF_POS;
        si.nMin   = 0;
        si.nMax   = yMax;
        si.nPage  = yClient / yChar;
        si.nPos   = yPos;
        SetScrollInfo(hwnd, SB_VERT, &si, TRUE);

        // Determine the maximum horizontal scrolling position.
        // The two is added for extra space to the right of the
        // lines of text.

        xMax = max (0, 2 + (xClientMax - xClient)/xChar);

        // Make sure the current horizontal scrolling position
        // does not exceed the maximum.

        xPos = min (xPos, xMax);

        // Adjust the horizontal scrolling range and scroll box
        // position to reflect the new xMax and xPos values.

        si.cbSize = sizeof(si);
        si.fMask  = SIF_RANGE | SIF_PAGE | SIF_POS;
        si.nMin   = 0;
        si.nMax   = xMax;
        si.nPage  = xClient / xChar;
        si.nPos   = xPos;
        SetScrollInfo(hwnd, SB_HORZ, &si, TRUE);

        return 0;

    case WM_PAINT:

        // Prepare the window for painting.

        hdc = BeginPaint(hwnd, &ps);

        // Use the current vertical scrolling position and
        // coordinates of the invalid rectangle to determine
        // the range of new lines that should be drawn in the
        // client area.

        FirstLine = max (0, yPos + ps.rcPaint.top/yChar - 1);
        LastLine = min (LINES, yPos + ps.rcPaint.bottom/yChar);

        // Display these lines.

        for (i = FirstLine;i < LastLine;i++)
        {
            x = xChar * (1 - xPos);
            y = yChar * (1 - yPos + i);

            TextOut (hdc, x, y, abc[i], lstrlen(abc[i]));
        }

        // Indicate that painting is finished.

        EndPaint(hwnd, &ps);
        break;

    case WM_HSCROLL:
        switch(LOWORD (wParam))
        {
            // User clicked shaft left of the scroll box.

            case SB_PAGEUP:
                 xInc = -8;
                 break;

            // User clicked shaft right of the scroll box.

            case SB_PAGEDOWN:
                 xInc = 8;
                 break;

            // User clicked the left arrow.

            case SB_LINEUP:
                 xInc = -1;
                 break;

            // User clicked the right arrow.

            case SB_LINEDOWN:
                 xInc = 1;
                 break;

            // User dragged the scroll box.

            case SB_THUMBTRACK:
                 xInc = HIWORD(wParam) - xPos;
                 break;

            default:
                 xInc = 0;

        }

        // If applying the horizontal scrolling increment does not
        // take the scrolling position out of the scrolling range,
        // increment the scrolling position, adjust the position
        // of the scroll box, and update the window.

        if (xInc = max (-xPos, min (xInc, xMax - xPos)))
        {
            xPos += xInc;
            ScrollWindowEx (hwnd, -xChar * xInc, 0,
                (CONST RECT *) NULL, (CONST RECT *) NULL,
                (HRGN) NULL, (LPRECT) NULL, SW_INVALIDATE);
            si.cbSize = sizeof(si);
            si.fMask  = SIF_POS;
            si.nPos   = xPos;
            SetScrollInfo(hwnd, SB_HORZ, &si, TRUE);
            UpdateWindow (hwnd);
        }

        return 0;

    case WM_VSCROLL:
        switch(LOWORD (wParam))
        {
            // User clicked the shaft above the scroll box.

            case SB_PAGEUP:
                 yInc = min(-1, -yClient / yChar);
                 break;

            // User clicked the shaft below the scroll box.

            case SB_PAGEDOWN:
                 yInc = max(1, yClient / yChar);
                 break;

            // User clicked the top arrow.

            case SB_LINEUP:
                 yInc = -1;
                 break;

            // User clicked the bottom arrow.

            case SB_LINEDOWN:
                 yInc = 1;
                 break;

            // User dragged the scroll box.

            case SB_THUMBTRACK:
                 yInc = HIWORD(wParam) - yPos;
                 break;

            default:
                 yInc = 0;

        }

        // If applying the vertical scrolling increment does not
        // take the scrolling position out of the scrolling range,
        // increment the scrolling position, adjust the position
        // of the scroll box, and update the window. UpdateWindow
        // sends the WM_PAINT message.

        if (yInc = max(-yPos, min(yInc, yMax - yPos)))
        {
            yPos += yInc;
            ScrollWindow(hwnd, 0, -yChar * yInc,
                (CONST RECT *) NULL, (CONST RECT *) NULL,
                (HRGN) NULL, (LPRECT) NULL, SW_INVALIDATE);
            si.cbSize = sizeof(si);
            si.fMask  = SIF_POS;
            si.nPos   = YPos;
            SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
            UpdateWindow (hwnd);
        }

        return 0;


Scrolling a Bitmap

This section describes changes you can make to an application's main window procedure to enable the user to scroll a bitmap. The example in Example of Scrolling a Bitmap includes a menu item that copies the screen content to a bitmap and displays the bitmap in the client area.

The example also processes the WM_HSCROLL and WM_VSCROLL messages generated by the scroll bars so that the user may scroll the bitmap horizontally and vertically. Unlike the example for scrolled text, the bitmap example employs the BitBlt function to draw the invalid portion of the client area.


Scrolling a Bitmap with the WM_CREATE Message

When the WM_CREATE message is processed, the variables required for scrolling are initialized. Use the CreateCompatibleDC function to create a compatible device context (DC), the CreateBitmap function to create a bitmap, and the SelectObject function to select the bitmap for the DC. Note that a compatible DC is also known as a memory DC.

The device-specific information about the display device is retrieved. If a compatible DC is created for the screen, as in the example, use the GetDeviceCaps function to get this information. The information includes the number of adjacent color bits per pixel, the number of color planes, and the height and width of the DC.


Scrolling a Bitmap with the WM_SIZE Message

Processing of the WM_SIZE message requires adjusting the scrolling range and position, so it reflects the dimensions of the client area and the bitmap that will be displayed.

The SetScrollInfo function sets the minimum and maximum position values, the page size, and the scrolling position for a scroll bar.


Scrolling a Bitmap with the WM_HSCROLL and WM_VSCROLL Messages

When the WM_HSCROLL and WM_VSCROLL messages are processed, the scroll bar notification message is examined and the scrolling position is set to a new value that reflects the scrolling action of the user. If the scrolling position is within the scrolling range, the window is scrolled to the new position by using the ScrollWindow function. The position of the scroll box is then adjusted by using the SetScrollInfo function.

After a window is scrolled, part of its client area is made invalid. To ensure that the invalid region is updated, use the UpdateWindow function to generate a WM_PAINT message. When processing the WM_PAINT message, an application must repaint the invalid region at the bottom of the client area. When scrolling or resizing the client area, the example uses the BitBlt function to copy the appropriate portion of the bitmap to the invalid portion of the client area.


Example of Scrolling a Bitmap

The following example enables the user to capture the screen content into a bitmap and scroll the bitmap in the client area.

HDC hdc;
PAINTSTRUCT ps;
SCROLLINFO si;

// These variables are required by BitBlt.

static HDC hdcWin;           // window DC
static HDC hdcScreen;        // DC for entire screen
static HDC hdcScreenCompat;  // memory DC for screen
static HBITMAP hbmpCompat;   // bitmap handle for old DC
static BITMAP bmp;           // bitmap data structure
static BOOL fBlt;            // TRUE if BitBlt occurred
static BOOL fScroll;         // TRUE if scrolling occurred
static BOOL fSize;           // TRUE if fBlt & WM_SIZE

// These variables are required for horizontal scrolling.

static int xMinScroll;       // minimum horizontal scroll value
static int xCurrentScroll;   // current horizontal scroll value
static int xMaxScroll;       // maximum horizontal scroll value

// These variables are required for vertical scrolling.

static int yMinScroll;       // minimum vertical scroll value
static int yCurrentScroll;   // current vertical scroll value
static int yMaxScroll;       // maximum vertical scroll value

switch (uMsg)
{
    case WM_CREATE:

        // Create a normal DC and a memory DC for the entire
        // screen. The normal DC provides a snapshot of the
        // screen contents. The memory DC keeps a copy of this
        // snapshot in the associated bitmap.

        hdcScreen = CreateDC("DISPLAY", (LPCSTR) NULL,
            (LPCSTR) NULL, (CONST DEVMODE *) NULL);
        hdcScreenCompat = CreateCompatibleDC(hdcScreen);

        // Retrieve the metrics for the bitmap associated with the
        // regular device context.

        bmp.bmBitsPixel =
            (BYTE) GetDeviceCaps(hdcScreen, BITSPIXEL);
        bmp.bmPlanes = (BYTE) GetDeviceCaps(hdcScreen, PLANES);
        bmp.bmWidth = GetDeviceCaps(hdcScreen, HORZRES);
        bmp.bmHeight = GetDeviceCaps(hdcScreen, VERTRES);

        // The width must be byte-aligned.

        bmp.bmWidthBytes = ((bmp.bmWidth + 15) &~15)/8;

        // Create a bitmap for the compatible DC.

        hbmpCompat = CreateBitmap(bmp.bmWidth, bmp.bmHeight,
            bmp.bmPlanes, bmp.bmBitsPixel, (CONST VOID *) NULL);

        // Select the bitmap for the compatible DC.

        SelectObject(hdcScreenCompat, hbmpCompat);

        // Initialize the flags.

        fBlt = FALSE;
        fScroll = FALSE;
        fSize = FALSE;

        // Initialize the horizontal scrolling variables.

        xMinScroll = 0;
        xCurrentScroll = 0;
        xMaxScroll = 0;

        // Initialize the vertical scrolling variables.

        yMinScroll = 0;
        yCurrentScroll = 0;
        yMaxScroll = 0;

        break;

    case WM_SIZE:
    {
        int xNewSize;
        int yNewSize;

        xNewSize = LOWORD(lParam);
        yNewSize = HIWORD(lParam);

        if (fBlt)
            fSize = TRUE;

        // The horizontal scrolling range is defined by
        // (bitmap_width) - (client_width). The current horizontal
        // scroll value remains within the horizontal scrolling range.

        xMaxScroll = max(bmp.bmWidth-xNewSize, 0);
        xCurrentScroll = min(xCurrentScroll, xMaxScroll);
        si.cbSize = sizeof(si);
        si.fMask  = SIF_RANGE | SIF_PAGE | SIF_POS;
        si.nMin   = xMinScroll;
        si.nMax   = xMaxScroll;
        si.nPage  = xNewSize;
        si.nPos   = xCurrentScroll;
        SetScrollInfo(hwnd, SB_HORZ, &si, TRUE);

        // The vertical scrolling range is defined by
        // (bitmap_height) - (client_height). The current vertical
        // scroll value remains within the vertical scrolling range.

        yMaxScroll = max(bmp.bmHeight - yNewSize, 0);
        yCurrentScroll = min(yCurrentScroll, yMaxScroll);
        si.cbSize = sizeof(si);
        si.fMask  = SIF_RANGE | SIF_PAGE | SIF_POS;
        si.nMin   = yMinScroll;
        si.nMax   = yMaxScroll;
        si.nPage  = yNewSize;
        si.nPos   = yCurrentScroll;
        SetScrollInfo(hwnd, SB_VERT, &si, TRUE);

    }
        break;

    case WM_PAINT:
    {
        PRECT prect;

        hdc = BeginPaint(hwnd, &ps);

        // If the window has been resized and the user has
        // captured the screen, use the following call to
        // BitBlt to paint the window's client area.

        if (fSize)
        {
            BitBlt(ps.hdc,
                0, 0,
                bmp.bmWidth, bmp.bmHeight,
                hdcScreenCompat,
                xCurrentScroll, yCurrentScroll,
                SRCCOPY);

            fSize = FALSE;
        }

        // If scrolling has occurred, use the following call to
        // BitBlt to paint the invalid rectangle.
        //
        // The coordinates of this rectangle are specified in the
        // RECT structure to which prect points.
        //
        // Note that it is necessary to increment the seventh
        // argument (prect->left) by xCurrentScroll and the
        // eighth argument (prect->top) by yCurrentScroll in
        // order to map the correct pixels from the source bitmap.

        if (fScroll)
        {
            prect = &ps.rcPaint;

            BitBlt(ps.hdc,
                prect->left, prect->top,
                (prect->right - prect->left),
                (prect->bottom - prect->top),
                hdcScreenCompat,
                prect->left + xCurrentScroll,
                prect->top + yCurrentScroll,
                SRCCOPY);

            fScroll = FALSE;
        }

        EndPaint(hwnd, &ps);
    }
        break;

    case WM_HSCROLL:
    {
        int xDelta;     // xDelta = new_pos - current_pos
        int xNewPos;    // new position
        int yDelta = 0;

        switch (LOWORD(wParam))
        {
            // User clicked the shaft left of the scroll box.

            case SB_PAGEUP:
                xNewPos = xCurrentScroll - 50;
                break;

            // User clicked the shaft right of the scroll box.

            case SB_PAGEDOWN:
                xNewPos = xCurrentScroll + 50;
                break;

            // User clicked the left arrow.

            case SB_LINEUP:
                xNewPos = xCurrentScroll - 5;
                break;

            // User clicked the right arrow.

            case SB_LINEDOWN:
                xNewPos = xCurrentScroll + 5;
                break;

            // User dragged the scroll box.

            case SB_THUMBPOSITION:
                xNewPos = HIWORD(wParam);
                break;

            default:
                xNewPos = xCurrentScroll;
        }

        // New position must be between 0 and the screen width.

        xNewPos = max(0, xNewPos);
        xNewPos = min(xMaxScroll, xNewPos);

        // If the current position does not change, do not scroll.

        if (xNewPos == xCurrentScroll)
            break;

        // Set the scroll flag to TRUE.

        fScroll = TRUE;

        // Determine the amount scrolled (in pixels).

        xDelta = xNewPos - xCurrentScroll;

        // Reset the current scroll position.

        xCurrentScroll = xNewPos;

        // Scroll the window. (The system repaints most of the
        // client area when ScrollWindowEx is called; however, it is
        // necessary to call UpdateWindow in order to repaint the
        // rectangle of pixels that were invalidated.)

        ScrollWindowEx(hwnd, -xDelta, -yDelta, (CONST RECT *) NULL,
            (CONST RECT *) NULL, (HRGN) NULL, (LPRECT) NULL,
            SW_INVALIDATE);
        UpdateWindow(hwnd);

        // Reset the scroll bar.

        si.cbSize = sizeof(si);
        si.fMask  = SIF_POS;
        si.nPos   = xCurrentScroll;
        SetScrollInfo(hwnd, SB_HORZ, &si, TRUE);

    }
        break;

    case WM_VSCROLL:
    {
        int xDelta = 0;
        int yDelta;     // yDelta = new_pos - current_pos
        int yNewPos;    // new position

        switch (LOWORD(wParam))
        {
            // User clicked the shaft above the scroll box.

            case SB_PAGEUP:
                yNewPos = yCurrentScroll - 50;
                break;

            // User clicked the shaft below the scroll box.

            case SB_PAGEDOWN:
                yNewPos = yCurrentScroll + 50;
                break;

            // User clicked the top arrow.

            case SB_LINEUP:
                yNewPos = yCurrentScroll - 5;
                break;

            // User clicked the bottom arrow.

            case SB_LINEDOWN:
                yNewPos = yCurrentScroll + 5;
                break;

            // User dragged the scroll box.

            case SB_THUMBPOSITION:
                yNewPos = HIWORD(wParam);
                break;

            default:
                yNewPos = yCurrentScroll;
        }

        // New position must be between 0 and the screen height.

        yNewPos = max(0, yNewPos);
        yNewPos = min(yMaxScroll, yNewPos);

        // If the current position does not change, do not scroll.

        if (yNewPos == yCurrentScroll)
            break;

        // Set the scroll flag to TRUE.

        fScroll = TRUE;

        // Determine the amount scrolled (in pixels).

        yDelta = yNewPos - yCurrentScroll;

        // Reset the current scroll position.

        yCurrentScroll = yNewPos;

        // Scroll the window. (The system repaints most of the
        // client area when ScrollWindowEx is called; however, it is
        // necessary to call UpdateWindow in order to repaint the
        // rectangle of pixels that were invalidated.)

        ScrollWindowEx(hwnd, -xDelta, -yDelta, (CONST RECT *) NULL,
            (CONST RECT *) NULL, (HRGN) NULL, (LPRECT) NULL,
            SW_INVALIDATE);
        UpdateWindow(hwnd);

        // Reset the scroll bar.

        si.cbSize = sizeof(si);
        si.fMask  = SIF_POS;
        si.nPos   = yCurrentScroll;
        SetScrollInfo(hwnd, SB_VERT, &si, TRUE);

    }
        break;

    case WM_COMMAND:        // uMsg: command from app. menu
        switch(wParam)
        {
            case IDM_STC:

                // Copy the contents of the current screen
                // into the compatible DC.

                BitBlt(hdcScreenCompat, 0, 0, bmp.bmWidth,
                    bmp.bmHeight, hdcScreen, 0, 0, SRCCOPY);

                // Copy the compatible DC to the client area.

                hdcWin = GetDC(hwnd);

                BitBlt(hdcWin, 0, 0, bmp.bmWidth, bmp.bmHeight,
                    hdcScreenCompat, 0, 0, SRCCOPY);

                ReleaseDC(hwnd, hdcWin);

                fBlt = TRUE;
                break;

            default:
                return (DefWindowProc(hwnd, uMsg,
                    wParam, lParam));
        }
        break;


Creating a Keyboard Interface for a Standard Scroll Bar

Although a scroll bar control provides a built-in keyboard interface, a standard scroll bar does not. To implement a keyboard interface for a standard scroll bar, a window procedure must process the WM_KEYDOWN message and examine the virtual-key code specified by the wParam parameter. If the virtual-key code corresponds to an arrow key, the window procedure sends itself a WM_HSCROLL or WM_VSCROLL message with the low-order word of the wParam parameter set to the appropriate scroll bar notification message. For example, when the user presses the up arrow key, the window procedure receives a WM_KEYDOWN message with wParam equal to VK_UP. In response, the window procedure sends itself a WM_VSCROLL message with the low-order word of wParam set to the SB_LINEUP notification message.

The following example shows how to include a keyboard interface for a standard scroll bar.

WORD wScrollNotify = 0xFFFF;

case WM_KEYDOWN:
    switch (wParam)
    {
        case VK_UP:
            wScrollNotify = SB_LINEUP;
            break;

        case VK_PRIOR:
            wScrollNotify = SB_PAGEUP;
            break;

        case VK_NEXT:
            wScrollNotify = SB_PAGEDOWN;
            break;

        case VK_DOWN:
            wScrollNotify = SB_LINEDOWN;
            break;

        case VK_HOME:
            wScrollNotify = SB_TOP;
            break;

        case VK_END:
            wScrollNotify = SB_BOTTOM;
            break;
    }

    if (wScrollNotify != -1)
        SendMessage(hwnd, WM_VSCROLL, MAKELONG(wScrollNotify, 0), 0L);

    break;


Scroll Bar Reference

The following functions, structures, messages, and styles are associated with scroll bars.


Scroll Bar Functions

The following functions are used with scroll bars.

EnableScrollBar
GetScrollInfo
ScrollDC
ScrollWindowEx
SetScrollInfo
ShowScrollBar

Obsolete Functions

GetScrollPos
GetScrollRange
ScrollWindow
SetScrollPos
SetScrollRange


EnableScrollBar

The EnableScrollBar function enables or disables one or both scroll bar arrows.

BOOL EnableScrollBar(
  HWND hWnd,     // handle to window or scroll bar
  UINT wSBflags, // scroll bar type flag
  UINT wArrows   // scroll bar arrow flag
);

Parameters

hWnd
Handle to a window or a scroll bar control, depending on the value of the wSBflags parameter.
wSBflags
Specifies the scroll bar type. This parameter can be one of the following values:
Value | Meaning
SB_BOTH | Enables or disables the arrows on the horizontal and vertical scroll bars associated with the specified window. The hWnd parameter must be the handle to the window.
SB_CTL | Identifies the scroll bar as a scroll bar control. The hWnd parameter must be the handle to the scroll bar control.
SB_HORZ | Enables or disables the arrows on the horizontal scroll bar associated with the specified window. The hWnd parameter must be the handle to the window.
SB_VERT | Enables or disables the arrows on the vertical scroll bar associated with the specified window. The hWnd parameter must be the handle to the window.

wArrows
Specifies whether the scroll bar arrows are enabled or disabled and indicates which arrows are enabled or disabled. This parameter can be one of the following values:
Value | Meaning
ESB_DISABLE_BOTH | Disables both arrows on a scroll bar.
ESB_DISABLE_DOWN | Disables the down arrow on a vertical scroll bar.
ESB_DISABLE_LEFT | Disables the left arrow on a horizontal scroll bar.
ESB_DISABLE_LTUP | Disables the left arrow on a horizontal scroll bar or the up arrow of a vertical scroll bar.
ESB_DISABLE_RIGHT | Disables the right arrow on a horizontal scroll bar.
ESB_DISABLE_RTDN | Disables the right arrow on a horizontal scroll bar or the down arrow of a vertical scroll bar.
ESB_DISABLE_UP | Disables the up arrow on a vertical scroll bar.
ESB_ENABLE_BOTH | Enables both arrows on a scroll bar.

Return Values

If the arrows are enabled or disabled as specified, the return value is nonzero.

If the arrows are already in the requested state or an error occurs, the return value is zero. To get extended error information, call GetLastError.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Scroll Bars Overview, Scroll Bar Functions, ShowScrollBar


GetScrollInfo

The GetScrollInfo function retrieves the parameters of a scroll bar, including the minimum and maximum scrolling positions, the page size, and the position of the scroll box (thumb).

BOOL GetScrollInfo(
  HWND hwnd,         // handle to window with scroll bar
  int fnBar,         // scroll bar flag
  LPSCROLLINFO lpsi  // pointer to structure for scroll parameters
);

Parameters

hwnd
Handle to a scroll bar control or a window with a standard scroll bar, depending on the value of the fnBar parameter.
fnBar
Specifies the type of scroll bar for which to retrieve parameters. This parameter can be one of the following values:
Value | Meaning
SB_CTL | Retrieves the parameters for a scroll bar control. The hwnd parameter must be the handle to the scroll bar control.
SB_HORZ | Retrieves the parameters for the given window's standard horizontal scroll bar.
SB_VERT | Retrieves the parameters for the given window's standard vertical scroll bar.

lpsi
Pointer to a SCROLLINFO structure. Before calling GetScrollInfo, set the cbSize member of the structure to sizeof(SCROLLINFO), and set the fMask member to specify the scroll bar parameters to retrieve. Before returning, the function copies the specified parameters to the appropriate members of the structure.

The fMask member can be a combination of the following values:
Value | Meaning
SIF_PAGE | Copies the scroll page to the nPage member of the SCROLLINFO structure pointed to by lpsi.
SIF_POS | Copies the scroll position to the nPos member of the SCROLLINFO structure pointed to by lpsi.
SIF_RANGE | Copies the scroll range to the nMin and nMax members of the SCROLLINFO structure pointed to by lpsi.
SIF_TRACKPOS | Copies the current scroll box tracking position to the nTrackPos member of the SCROLLINFO structure pointed to by lpsi.

Return Values

If the function retrieved any values, the return value is nonzero.

If the function does not retrieve any values, the return value is zero. To get extended error information, call GetLastError.

Remarks

The GetScrollInfo function enables applications to use 32-bit scroll positions. Although the messages that indicate scroll-bar position, WM_HSCROLL and WM_VSCROLL, provide only 16 bits of position data, the functions SetScrollInfo and GetScrollInfo provide 32 bits of scroll-bar position data. Thus, an application can call GetScrollInfo while processing either the WM_HSCROLL or WM_VSCROLL messages to obtain 32-bit scroll-bar position data.

To get the 32-bit position of the scroll box (thumb) during a SB_THUMBTRACK notification in a WM_HSCROLL or WM_VSCROLL message, call GetScrollInfo with the SIF_TRACKPOS value in the fMask member of the SCROLLINFO structure. The function returns the tracking position of the scroll box in the nTrackPos member of the SCROLLINFO structure. This allows you to get the position of the scroll box as the user moves it. The following sample code illustrates the technique.

SCROLLINFO si;
case WM_HSCROLL:
    switch(LOWORD(wparam)) {
        case SB_THUMBTRACK:
          // Initialize SCROLLINFO structure

            ZeroMemory(&si, sizeof(SCROLLINFO));
            si.cbSize = sizeof(SCROLLINFO);
            si.fMask = SIF_TRACKPOS;

          // Call GetScrollInfo to get current tracking
          //    position in si.nTrackPos

            if (!GetScrollInfo(hwnd, SB_HORZ, &si) )
                return 1; // GetScrollInfo failed
            break;
        .
        .
        .
    }

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Scroll Bars Overview, Scroll Bar Functions, SCROLLINFO, SetScrollInfo, WM_HSCROLL, WM_VSCROLL


GetScrollPos

The GetScrollPos function retrieves the current position of the scroll box (thumb) in the specified scroll bar. The current position is a relative value that depends on the current scrolling range. For example, if the scrolling range is 0 through 100 and the scroll box is in the middle of the bar, the current position is 50.

The GetScrollPos function is provided for backward compatibility. New applications should use the GetScrollInfo function.

int GetScrollPos(
  HWND hWnd, // handle to window with scroll bar
  int nBar   // scroll bar flags
);

Parameters

hWnd
Handle to a scroll bar control or a window with a standard scroll bar, depending on the value of the nBar parameter.
nBar
Specifies the scroll bar to be examined. This parameter can be one of the following values:
Value | Meaning
SB_CTL | Retrieves the position of the scroll box in a scroll bar control. The hWnd parameter must be the handle to the scroll bar control.
SB_HORZ | Retrieves the position of the scroll box in a window's standard horizontal scroll bar.
SB_VERT | Retrieves the position of the scroll box in a window's standard vertical scroll bar.

Return Values

If the function succeeds, the return value is the current position of the scroll box.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The GetScrollPos function enables applications to use 32-bit scroll positions. Although the messages that indicate scroll bar position, WM_HSCROLL and WM_VSCROLL, are limited to 16 bits of position data, the functions SetScrollPos, SetScrollRange, GetScrollPos, and GetScrollRange support 32-bit scroll bar position data. Thus, an application can call GetScrollPos while processing either the WM_HSCROLL or WM_VSCROLL messages to obtain 32-bit scroll bar position data.

To get the 32-bit position of the scroll box (thumb) during a SB_THUMBTRACK notification in a WM_HSCROLL or WM_VSCROLL message, use the GetScrollInfo function.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Scroll Bars Overview, Scroll Bar Functions, GetScrollInfo, GetScrollRange, SetScrollInfo, SetScrollPos, SetScrollRange, WM_HSCROLL, WM_VSCROLL


GetScrollRange

The GetScrollRange function retrieves the current minimum and maximum scroll box (thumb) positions for the specified scroll bar.

The GetScrollRange function is provided for compatibility only. New applications should use the GetScrollInfo function.

BOOL GetScrollRange(
  HWND hWnd, // handle to window with scroll bar
  int nBar,  // scroll bar flags
  LPINT lpMinPos,
             // address of variable that receives minimum position
  LPINT lpMaxPos
             // address of variable that receives maximum position
);

Parameters

hWnd
Handle to a scroll bar control or a window with a standard scroll bar, depending on the value of the nBar parameter.
nBar
Specifies the scroll bar from which the positions are retrieved. This parameter can be one of the following values:
Value | Meaning
SB_CTL | Retrieves the positions of a scroll bar control. The hWnd parameter must be the handle to the scroll bar control.
SB_HORZ | Retrieves the positions of the window's standard horizontal scroll bar.
SB_VERT | Retrieves the positions of the window's standard vertical scroll bar.

lpMinPos
Pointer to the integer variable that receives the minimum position.
lpMaxPos
Pointer to the integer variable that receives the maximum position.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

If the specified window does not have standard scroll bars or is not a scroll bar control, the GetScrollRange function copies zero to the lpMinPos and lpMaxPos parameters.

The default range for a standard scroll bar is 0 through 100. The default range for a scroll bar control is empty (both values are zero).

The messages that indicate scroll bar position, WM_HSCROLL and WM_VSCROLL, are limited to 16 bits of position data. However, because SetScrollInfo, SetScrollPos, SetScrollRange, GetScrollInfo, GetScrollPos, and GetScrollRange support 32-bit scroll bar position data, there is a way to circumvent the 16-bit barrier of the WM_HSCROLL and WM_VSCROLL messages. See the GetScrollInfo function for a description of the technique.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Scroll Bars Overview, Scroll Bar Functions, GetScrollInfo, GetScrollPos, SetScrollInfo, SetScrollPos, SetScrollRange, WM_HSCROLL, WM_VSCROLL


ScrollDC

The ScrollDC function scrolls a rectangle of bits horizontally and vertically.

BOOL ScrollDC(
  HDC hDC,          // handle to device context
  int dx,           // horizontal scroll units
  int dy,           // vertical scroll units
  CONST RECT *lprcScroll,
                    // address of structure for scrolling rectangle
  CONST RECT *lprcClip,
                    // address of structure for clipping rectangle
  HRGN hrgnUpdate,  // handle to scrolling region
  LPRECT lprcUpdate
                    // address of structure for update rectangle
);

Parameters

hDC
Handle to the device context that contains the bits to be scrolled.
dx
Specifies the amount, in device units, of horizontal scrolling. This parameter must be a negative value to scroll to the left.
dy
Specifies the amount, in device units, of vertical scrolling. This parameter must be a negative value to scroll up.
lprcScroll
Pointer to the RECT structure containing the coordinates of the scrolling rectangle.
lprcClip
Pointer to the RECT structure containing the coordinates of the clipping rectangle. Only device bits within the clipping rectangle are affected. Bits scrolled from the outside of the rectangle to the inside are painted; bits scrolled from the inside of the rectangle to the outside are not painted.
hrgnUpdate
Handle to the region uncovered by the scrolling process. ScrollDC defines this region; it is not necessarily a rectangle.
lprcUpdate
Pointer to the RECT structure that receives the coordinates of the rectangle bounding the scrolling update region. This is the largest rectangular area that requires repainting. When the function returns, the values in the structure are in client coordinates, regardless of the mapping mode for the specified device context. This allows applications to use the update region in a call to the InvalidateRgn function, if required.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

If the lprcUpdate parameter is NULL, the system does not compute the update rectangle. If both the hrgnUpdate and lprcUpdate parameters are NULL, the system does not compute the update region. If hrgnUpdate is not NULL, the system proceeds as though it contains a valid handle to the region uncovered by the scrolling process (defined by ScrollDC).

When you must scroll the entire client area of a window, use the ScrollWindowEx function.

Windows CE: Only one of the dx and dy parameters can be nonzero.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Scroll Bars Overview, Scroll Bar Functions, InvalidateRgn, RECT, ScrollWindowEx


ScrollWindow

The ScrollWindow function scrolls the content of the specified window's client area. The ScrollWindow function exists for backward compatibility. New applications should use the ScrollWindowEx function.

BOOL ScrollWindow(
  HWND hWnd,    // handle to window to scroll
  int XAmount,  // amount of horizontal scrolling
  int YAmount,  // amount of vertical scrolling
  CONST RECT *lpRect,
                // address of structure with scroll rectangle
  CONST RECT *lpClipRect
                // address of structure with clip rectangle
);

Parameters

hWnd
Handle to the window where the client area is to be scrolled.
XAmount
Specifies the amount, in device units, of horizontal scrolling. If the window being scrolled has the CS_OWNDC or CS_CLASSDC style, then this parameter uses logical units rather than device units. This parameter must be a negative value to scroll the content of the window to the left.
YAmount
Specifies the amount, in device units, of vertical scrolling. If the window being scrolled has the CS_OWNDC or CS_CLASSDC style, then this parameter uses logical units rather than device units. This parameter must be a negative value to scroll the content of the window up.
lpRect
Pointer to the RECT structure specifying the portion of the client area to be scrolled. If this parameter is NULL, the entire client area is scrolled.
lpClipRect
Pointer to the RECT structure containing the coordinates of the clipping rectangle. Only device bits within the clipping rectangle are affected. Bits scrolled from the outside of the rectangle to the inside are painted; bits scrolled from the inside of the rectangle to the outside are not painted.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

If the caret is in the window being scrolled, ScrollWindow automatically hides the caret to prevent it from being erased and then restores the caret after the scrolling is finished. The caret position is adjusted accordingly.

The area uncovered by ScrollWindow is not repainted, but it is combined into the window's update region. The application eventually receives a WM_PAINT message notifying it that the region must be repainted. To repaint the uncovered area at the same time the scrolling is in action, call the UpdateWindow function immediately after calling ScrollWindow.

If the lpRect parameter is NULL, the positions of any child windows in the window are offset by the amount specified by the XAmount and YAmount parameters; invalid (unpainted) areas in the window are also offset. ScrollWindow is faster when lpRect is NULL.

If lpRect is not NULL, the positions of child windows are not changed and invalid areas in the window are not offset. To prevent updating problems when lpRect is not NULL, call UpdateWindow to repaint the window before calling ScrollWindow.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Scroll Bars Overview, Scroll Bar Functions, RECT, ScrollDC, ScrollWindowEx, UpdateWindow


ScrollWindowEx

The ScrollWindowEx function scrolls the content of the specified window's client area.

int ScrollWindowEx(
  HWND hWnd,        // handle to window to scroll
  int dx,           // amount of horizontal scrolling
  int dy,           // amount of vertical scrolling
  CONST RECT *prcScroll,
                    // address of structure with scroll rectangle
  CONST RECT *prcClip,
                    // address of structure with clip rectangle
  HRGN hrgnUpdate,  // handle to update region
  LPRECT prcUpdate, // address of structure for update rectangle
  UINT flags        // scrolling flags
);

Parameters

hWnd
Handle to the window where the client area is to be scrolled.
dx
Specifies the amount, in device units, of horizontal scrolling. This parameter must be a negative value to scroll to the left.
dy
Specifies the amount, in device units, of vertical scrolling. This parameter must be a negative value to scroll up.
prcScroll
Pointer to the RECT structure specifying the portion of the client area to be scrolled. If this parameter is NULL, the entire client area is scrolled.
prcClip
Pointer to the RECT structure containing the coordinates of the clipping rectangle. Only device bits within the clipping rectangle are affected. Bits scrolled from the outside of the rectangle to the inside are painted; bits scrolled from the inside of the rectangle to the outside are not painted.
hrgnUpdate
Handle to the region that is modified to hold the region invalidated by scrolling. This parameter may be NULL.
prcUpdate
Pointer to the RECT structure receiving the boundaries of the rectangle invalidated by scrolling. This parameter may be NULL.
flags
Specifies flags that control scrolling. This parameter can be one of the following values:
Value | Meaning
SW_ERASE | Erases the newly invalidated region by sending a WM_ERASEBKGND message to the window when specified with the SW_INVALIDATE flag.
SW_INVALIDATE | Invalidates the region identified by the hrgnUpdate parameter after scrolling.
SW_SCROLLCHILDREN | Scrolls all child windows that intersect the rectangle pointed to by the prcScroll parameter. The child windows are scrolled by the number of pixels specified by the dx and dy parameters. The system sends a WM_MOVE message to all child windows that intersect the prcScroll rectangle, even if they do not move.
SW_SMOOTHSCROLL | Windows NT 5.0 and later: Scrolls using smooth scrolling. Use the HIWORD portion of the flags parameter to indicate how much time the smooth-scrolling operation should take.

Return Values

If the function succeeds, the return value is SIMPLEREGION (rectangular invalidated region), COMPLEXREGION (nonrectangular invalidated region; overlapping rectangles), or NULLREGION (no invalidated region).

If the function fails, the return value is ERROR. To get extended error information, call GetLastError.

Remarks

If the SW_INVALIDATE and SW_ERASE flags are not specified, ScrollWindowEx does not invalidate the area that is scrolled from. If either of these flags is set, ScrollWindowEx invalidates this area. The area is not updated until the application calls the UpdateWindow function, calls the RedrawWindow function (specifying the RDW_UPDATENOW or RDW_ERASENOW flag), or retrieves the WM_PAINT message from the application queue.

If the window has the WS_CLIPCHILDREN style, the returned areas specified by hrgnUpdate and prcUpdate represent the total area of the scrolled window that must be updated, including any areas in child windows that need updating.

If the SW_SCROLLCHILDREN flag is specified, the system does not properly update the screen if part of a child window is scrolled. The part of the scrolled child window that lies outside the source rectangle is not erased and is not properly redrawn in its new destination. To move child windows that do not lie completely within the rectangle specified by prcScroll, use the DeferWindowPos function. The cursor is repositioned if the SW_SCROLLCHILDREN flag is set and the caret rectangle intersects the scroll rectangle.

All input and output coordinates (for prcScroll, prcClip, prcUpdate, and hrgnUpdate) are determined as client coordinates, regardless of whether the window has the CS_OWNDC or CS_CLASSDC class style. Use the LPtoDP and DPtoLP functions to convert to and from logical coordinates, if necessary.

Windows CE: The flags parameter does not support SW_SCROLLCHILDREN.

Only one of the dx and dy parameters can be nonzero.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Scroll Bars Overview, Scroll Bar Functions, DeferWindowPos, DPtoLP, LPtoDP, RECT, RedrawWindow, UpdateWindow


SetScrollInfo

The SetScrollInfo function sets the parameters of a scroll bar, including the minimum and maximum scrolling positions, the page size, and the position of the scroll box (thumb). The function also redraws the scroll bar, if requested.

int SetScrollInfo(
  HWND hwnd,    // handle to window with scroll bar
  int fnBar,    // scroll bar flag
  LPSCROLLINFO lpsi,
                // pointer to structure with scroll parameters
  BOOL fRedraw  // redraw flag
);

Parameters

hwnd
Handle to a scroll bar control or a window with a standard scroll bar, depending on the value of the fnBar parameter.
fnBar
Specifies the type of scroll bar for which to set parameters. This parameter can be one of the following values:
Value | Meaning
SB_CTL | Sets the parameters of a scroll bar control. The hwnd parameter must be the handle to the scroll bar control.
SB_HORZ | Sets the parameters of the given window's standard horizontal scroll bar.
SB_VERT | Sets the parameters of the given window's standard vertical scroll bar.

lpsi
Pointer to a SCROLLINFO structure. Before calling SetScrollInfo, set the cbSize member of the structure to sizeof(SCROLLINFO), set the fMask member to indicate the parameters to set, and specify the new parameter values in the appropriate members.

The fMask member can be a combination of the following values:
Value | Meaning
SIF_DISABLENOSCROLL | Disables the scroll bar instead of removing it, if the scroll bar's new parameters make the scroll bar unnecessary.
SIF_PAGE | Sets the scroll page to the value specified in the nPage member of the SCROLLINFO structure pointed to by lpsi.
SIF_POS | Sets the scroll position to the value specified in the nPos member of the SCROLLINFO structure pointed to by lpsi.
SIF_RANGE | Sets the scroll range to the value specified in the nMin and nMax members of the SCROLLINFO structure pointed to by lpsi.

fRedraw
Specifies whether the scroll bar is redrawn to reflect the changes to the scroll bar. If this parameter is TRUE, the scroll bar is redrawn, otherwise, it is not redrawn.

Return Values

The return value is the current position of the scroll box.

Remarks

The SetScrollInfo function performs range checking on the values specified by the nPage and nPos members of the SCROLLINFO structure. The nPage member must specify a value from 0 to nMax - nMin +1. The nPos member must specify a value between nMin and nMax - max(nPage – 1, 0). If either value is beyond its range, the function sets it to a value that is just within the range.

Windows CE: In Windows CE 2.0, if you pass a null pointer in the lpsi parameter, SetScrollInfo returns zero, rather than the current position of the scroll box.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Scroll Bars Overview, Scroll Bar Functions, GetScrollInfo, SCROLLINFO


SetScrollPos

The SetScrollPos function sets the position of the scroll box (thumb) in the specified scroll bar and, if requested, redraws the scroll bar to reflect the new position of the scroll box.

The SetScrollPos function is provided for backward compatibility. New applications should use the SetScrollInfo function.

int SetScrollPos(
  HWND hWnd,     // handle to window with scroll bar
  int nBar,      // scroll bar flag
  int nPos,      // new position of scroll box
  BOOL bRedraw   // redraw flag
);

Parameters

hWnd
Handle to a scroll bar control or a window with a standard scroll bar, depending on the value of the nBar parameter.
nBar
Specifies the scroll bar to be set. This parameter can be one of the following values:
Value | Meaning
SB_CTL | Sets the position of the scroll box in a scroll bar control. The hWnd parameter must be the handle to the scroll bar control.
SB_HORZ | Sets the position of the scroll box in a window's standard horizontal scroll bar.
SB_VERT | Sets the position of the scroll box in a window's standard vertical scroll bar.

nPos
Specifies the new position of the scroll box. The position must be within the scrolling range. For more information about the scrolling range, see the SetScrollRange function.
bRedraw
Specifies whether the scroll bar is redrawn to reflect the new scroll box position. If this parameter is TRUE, the scroll bar is redrawn. If it is FALSE, the scroll bar is not redrawn.

Return Values

If the function succeeds, the return value is the previous position of the scroll box.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

If the scroll bar is redrawn by a subsequent call to another function, setting the bRedraw parameter to FALSE is useful.

Because the messages that indicate scroll bar position, WM_HSCROLL and WM_VSCROLL, are limited to 16 bits of position data, applications that rely solely on those messages for position data have a practical maximum value of 65,535 for the SetScrollPos function's nPos parameter.

However, because the SetScrollInfo, SetScrollPos, SetScrollRange, GetScrollInfo, GetScrollPos, and GetScrollRange functions support 32-bit scroll bar position data, there is a way to circumvent the 16-bit barrier of the WM_HSCROLL and WM_VSCROLL messages. See GetScrollInfo for a description of the technique.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Scroll Bars Overview, Scroll Bar Functions, GetScrollInfo, GetScrollPos, GetScrollRange, SetScrollInfo, SetScrollRange


SetScrollRange

The SetScrollRange function sets the minimum and maximum position values for the specified scroll bar.

The SetScrollRange function is provided for backward compatibility. New applications should use the SetScrollInfo function.

BOOL SetScrollRange(
  HWND hWnd,    // handle to window with scroll bar
  int nBar,     // scroll bar flag
  int nMinPos,  // minimum scrolling position
  int nMaxPos,  // maximum scrolling position
  BOOL bRedraw  // redraw flag
);

Parameters

hWnd
Handle to a scroll bar control or a window with a standard scroll bar, depending on the value of the nBar parameter.
nBar
Specifies the scroll bar to be set. This parameter can be one of the following values:
Value | Meaning
SB_CTL | Sets the range of a scroll bar control. The hWnd parameter must be the handle to the scroll bar control.
SB_HORZ | Sets the range of a window's standard horizontal scroll bar.
SB_VERT | Sets the range of a window's standard vertical scroll bar.

nMinPos
Specifies the minimum scrolling position.
nMaxPos
Specifies the maximum scrolling position.
bRedraw
Specifies whether the scroll bar should be redrawn to reflect the change. If this parameter is TRUE, the scroll bar is redrawn. If it is FALSE, the scroll bar is not redrawn.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

You can use SetScrollRange to hide the scroll bar by setting nMinPos and nMaxPos to the same value. An application should not call the SetScrollRange function to hide a scroll bar while processing a scroll bar message. New applications should use the ShowScrollBar function to hide the scroll bar.

If the call to SetScrollRange immediately follows a call to the SetScrollPos function, the bRedraw parameter in SetScrollPos must be zero to prevent the scroll bar from being drawn twice.

The default range for a standard scroll bar is 0 through 100. The default range for a scroll bar control is empty (both the nMinPos and nMaxPos parameter values are zero). The difference between the values specified by the nMinPos and nMaxPos parameters must not be greater than the value of MAXLONG.

Because the messages that indicate scroll bar position, WM_HSCROLL and WM_VSCROLL, are limited to 16 bits of position data, applications that rely solely on those messages for position data have a practical maximum value of 65,535 for the SetScrollRange function's nMaxPos parameter.

However, because the SetScrollInfo, SetScrollPos, SetScrollRange, GetScrollInfo, GetScrollPos, and GetScrollRange functions support 32-bit scroll bar position data, there is a way to circumvent the 16-bit barrier of the WM_HSCROLL and WM_VSCROLL messages. See GetScrollInfo for a description of the technique.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Scroll Bars Overview, Scroll Bar Functions, GetScrollInfo, GetScrollPos, GetScrollRange, SetScrollInfo, SetScrollPos, ShowScrollBar


ShowScrollBar

The ShowScrollBar function shows or hides the specified scroll bar.

BOOL ShowScrollBar(
  HWND hWnd,  // handle to window with scroll bar
  int wBar,   // scroll bar flag
  BOOL bShow  // scroll bar visibility flag
);

Parameters

hWnd
Handle to a scroll bar control or a window with a standard scroll bar, depending on the value of the wBar parameter.
wBar
Specifies the scroll bar(s) to be shown or hidden. This parameter can be one of the following values:
Value | Meaning
SB_BOTH | Shows or hides a window's standard horizontal and vertical scroll bars.
SB_CTL | Shows or hides a scroll bar control. The hWnd parameter must be the handle to the scroll bar control.
SB_HORZ | Shows or hides a window's standard horizontal scroll bars.
SB_VERT | Shows or hides a window's standard vertical scroll bar.

bShow
Specifies whether the scroll bar is shown or hidden. If this parameter is TRUE, the scroll bar is shown; otherwise, it is hidden.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

You should not call this function to hide a scroll bar while processing a scroll bar message.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Scroll Bars Overview, Scroll Bar Functions, EnableScrollBar


Scroll Bar Structures

The following structure is used with scroll bars.

SCROLLINFO


SCROLLINFO

The SCROLLINFO structure contains scroll bar parameters to be set by the SetScrollInfo function (or SBM_SETSCROLLINFO message), or retrieved by the GetScrollInfo function (or SBM_GETSCROLLINFO message).

typedef struct tagSCROLLINFO {  // si
    UINT cbSize;
    UINT fMask;
    int  nMin;
    int  nMax;
    UINT nPage;
    int  nPos;
    int  nTrackPos;
}   SCROLLINFO;
typedef SCROLLINFO FAR *LPSCROLLINFO;

Members

cbSize
Specifies the size, in bytes, of this structure.
fMask
Specifies the scroll bar parameters to set or retrieve. This member can be a combination of the following values:
Value | Meaning
SIF_ALL | Combination of SIF_PAGE, SIF_POS, SIF_RANGE, and SIF_TRACKPOS.
SIF_DISABLENOSCROLL | This value is used only when setting a scroll bar's parameters. If the scroll bar's new parameters make the scroll bar unnecessary, disable the scroll bar instead of removing it.
SIF_PAGE | The nPage member contains the page size for a proportional scroll bar.
SIF_POS | The nPos member contains the scroll box position, which is not updated while the user drags the scroll box.
SIF_RANGE | The nMin and nMax members contain the minimum and maximum values for the scrolling range.
SIF_TRACKPOS | The nTrackPos member contains the current position of the scroll box while the user is dragging it.

nMin
Specifies the minimum scrolling position.
nMax
Specifies the maximum scrolling position.
nPage
Specifies the page size. A scroll bar uses this value to determine the appropriate size of the proportional scroll box.
nPos
Specifies the position of the scroll box.
nTrackPos
Specifies the immediate position of a scroll box that the user is dragging. An application can retrieve this value while processing the SB_THUMBTRACK notification message. An application cannot set the immediate scroll position; the SetScrollInfo function ignores this member.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Scroll Bars Overview, Scroll Bar Structures, SBM_GETSCROLLINFO, SBM_SETSCROLLINFO, GetScrollInfo, SetScrollInfo


Scroll Bar Messages

The following messages are used with scroll bars.

SBM_ENABLE_ARROWS
SBM_GETPOS
SBM_GETRANGE
SBM_GETSCROLLINFO
SBM_SETPOS
SBM_SETRANGE
SBM_SETRANGEREDRAW
SBM_SETSCROLLINFO
WM_CTLCOLORSCROLLBAR
WM_HSCROLL
WM_VSCROLL


SBM_ENABLE_ARROWS

An application sends the SBM_ENABLE_ARROWS message to enable or disable one or both arrows of a scroll bar control.

SBM_ENABLE_ARROWS
wParam = (WPARAM) fuArrowFlags; // scroll-bar arrow flags
lParam = 0;                     // not used; must be zero

Parameters

fuArrowFlags
Specifies whether the scroll bar arrows are enabled or disabled and indicates which arrows are enabled or disabled. This parameter can be one of the following values:
Value | Meaning
ESB_DISABLE_BOTH | Disables both arrows on a scroll bar.
ESB_DISABLE_DOWN | Disables the down arrow on a vertical scroll bar.
ESB_DISABLE_LTUP | Disables the left arrow on a horizontal scroll bar or the up arrow on a vertical scroll bar.
ESB_DISABLE_LEFT | Disables the left arrow on a horizontal scroll bar.
ESB_DISABLE_RTDN | Disables the right arrow on a horizontal scroll bar or the down arrow on a vertical scroll bar.
ESB_DISABLE_UP | Disables the up arrow on a vertical scroll bar.
ESB_ENABLE_BOTH | Enables both arrows on a scroll bar.

Return Values

If the message succeeds, the return value is TRUE; otherwise, it is FALSE.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

Scroll Bars Overview, Scroll Bar Messages


SBM_GETPOS

An application sends the SBM_GETPOS message to retrieve the current position of the scroll box of a scroll bar control. The current position is a relative value that depends on the current scrolling range. For example, if the scrolling range is 0 through 100 and the scroll box is in the middle of the bar, the current position is 50.

SBM_GETPOS
wParam = 0; // not used; must be zero
lParam = 0; // not used; must be zero

Parameters

This message has no parameters.

Return Values

If the message succeeds, the return value is the current position of the scroll box in the scroll bar.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

Scroll Bars Overview, Scroll Bar Messages, SBM_GETRANGE, SBM_SETPOS, SBM_SETRANGE, SBM_SETRANGEREDRAW


SBM_GETRANGE

An application sends the SBM_GETRANGE message to a scroll bar control to retrieve the minimum and maximum position values for the control.

SBM_GETRANGE
wParam = (WPARAM) (LPINT) lpnMinPos; // minimum position
lParam = (LPARAM) (LPINT) lpnMaxPos; // maximum position

Parameters

lpnMinPos
Pointer to a value that receives the minimum scrolling position.
lpnMaxPos
Pointer to a value that receives the maximum scrolling position.

Return Values

This message does not return a value.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

Scroll Bars Overview, Scroll Bar Messages, SBM_GETPOS, SBM_SETPOS, SBM_SETRANGE, SBM_SETRANGEREDRAW


SBM_GETSCROLLINFO

An application sends the SBM_GETSCROLLINFO message to retrieve the parameters of a scroll bar.

SBM_GETSCROLLINFO
wParam = 0;                             // not used, must be zero
lParam = (LPARAM) (LPSCROLLINFO) lpsi;  // scroll bar parameters

Parameters

lpsi
Value of lParam. Pointer to a SCROLLINFO structure. Before sending the message, set the cbSize member of the structure to sizeof(SCROLLINFO), and set the fMask member to specify the scroll bar parameters to retrieve. Before returning, the message copies the specified parameters to the appropriate members of the structure.

The fMask member can be a combination of the following values:
Value | Meaning
SIF_ALL | Combination of SIF_PAGE, SIF_POS, SIF_RANGE, and SIF_TRACKPOS.
SIF_PAGE | Copies the scroll page to the nPage member of the SCROLLINFO structure pointed to by lpsi.
SIF_POS | Copies the scroll position to the nPos member of the SCROLLINFO structure pointed to by lpsi.
SIF_RANGE | Copies the scroll range to the nMin and nMax members of the SCROLLINFO structure pointed to by lpsi.
SIF_TRACKPOS | Copies the current scroll box tracking position to the nTrackPos member of the SCROLLINFO structure pointed to by lpsi.

Return Values

If the message retrieved any values, the return value is TRUE; otherwise, it is FALSE.

Remarks

The messages that indicate scroll-bar position, WM_HSCROLL and WM_VSCROLL, provide only 16 bits of position data. However, the SCROLLINFO structure used by SBM_GETSCROLLINFO, SBM_SETSCROLLINFO, GetScrollInfo, and SetScrollInfo provides 32 bits of scroll-bar position data. You can use these messages and functions while processing either the WM_HSCROLL or WM_VSCROLL messages to obtain 32-bit scroll-bar position data.

To get the 32-bit position of the scroll box (thumb) during a SB_THUMBTRACK notification in a WM_HSCROLL or WM_VSCROLL message, send SBM_GETSCROLLINFO with the SIF_TRACKPOS value in the fMask member of the SCROLLINFO structure. The message returns the tracking position of the scroll box in the nTrackPos member of the SCROLLINFO structure. This allows you to get the position of the scroll box as the user moves it. Alternatively, you can use the GetScrollInfo function to get the same information.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Scroll Bars Overview, Scroll Bar Messages, GetScrollInfo, SBM_SETSCROLLINFO, SCROLLINFO, SetScrollInfo


SBM_SETPOS

An application sends the SBM_SETPOS message to a scroll bar control to set the position of the scroll box (thumb) and, if requested, redraw the scroll bar to reflect the new position of the scroll box.

SBM_SETPOS
wParam = (WPARAM) nPos;           // new position of scroll box
lParam = (LPARAM) (BOOL) fRedraw; // redraw flag

Parameters

nPos
Specifies the new position of the scroll box. It must be within the scrolling range.
fRedraw
Specifies whether the scroll bar should be redrawn to reflect the new scroll box position. If this parameter is TRUE, the scroll bar is redrawn. If it is FALSE, the scroll bar is not redrawn.

Return Values

If the position of the scroll box changed, the return value is the previous position of the scroll box; otherwise, it is zero.

Remarks

If the scroll bar control is redrawn by a subsequent call to another function, setting the fRedraw parameter to FALSE is useful.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

Scroll Bars Overview, Scroll Bar Messages, SBM_GETPOS, SBM_GETRANGE, SBM_SETRANGE, SBM_SETRANGEREDRAW


SBM_SETRANGE

An application sends the SBM_SETRANGE message to a scroll bar control to set the minimum and maximum position values for the control.

SBM_SETRANGE
wParam = (WPARAM) nMinPos; // minimum scrolling position
lParam = (LPARAM) nMaxPos; // maximum scrolling position

Parameters

nMinPos
Specifies the minimum scrolling position.
fMaxPos
Specifies the maximum scrolling position.

Return Values

If the position of the scroll box changed, the return value is the previous position of the scroll box; otherwise, it is zero.

Remarks

The default minimum and maximum position values are zero. The difference between the values specified by the nMinPos and nMaxPos parameters must not be greater than the value of MAXLONG.

If the minimum and maximum position values are equal, the scroll bar control is hidden and, in effect, disabled.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

Scroll Bars Overview, Scroll Bar Messages, SBM_GETPOS, SBM_GETRANGE, SBM_SETPOS, SBM_SETRANGEREDRAW


SBM_SETRANGEREDRAW

An application sends the SBM_SETRANGEREDRAW message to a scroll bar control to set the minimum and maximum position values and to redraw the control.

SBM_SETRANGEREDRAW
wParam = (WPARAM) nMinPos; // minimum scrolling position
lParam = (LPARAM) nMaxPos  // maximum scrolling position

Parameters

nMinPos
Specifies the minimum scrolling position.
fMaxPos
Specifies the maximum scrolling position.

Return Values

If the position of the scroll box changed, the return value is the previous position of the scroll box; otherwise, it is zero.

Remarks

The default minimum and maximum position values are zero. The difference between the values specified by the nMinPos and nMaxPos parameters must not be greater than the value of MAXLONG.

If the minimum and maximum position values are equal, the scroll bar control is hidden and, in effect, disabled.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

Scroll Bars Overview, Scroll Bar Messages, SBM_GETPOS, SBM_GETRANGE, SBM_SETPOS, SBM_SETRANGE


SBM_SETSCROLLINFO

An application sends the SBM_GETSCROLLINFO message to set the parameters of a scroll bar.

SBM_SETSCROLLINFO
wParam = (WPARAM) fRedraw;              // redraw flag
lParam = (LPARAM) (LPSCROLLINFO) lpsi;  // scroll bar parameters

Parameters

fRedraw
Value of wParam. Specifies whether the scroll bar is redrawn to reflect the new scroll box position. If this parameter is TRUE, the scroll bar is redrawn. If it is FALSE, the scroll bar is not redrawn.
lpsi
Value of lParam. Pointer to a SCROLLINFO structure. Before sending the message, set the cbSize member of the structure to sizeof(SCROLLINFO), set the fMask member to indicate the parameters to set, and specify the new parameter values in the appropriate members.

The fMask member can be a combination of the following values:
Value | Meaning
SIF_DISABLENOSCROLL | Disables the scroll bar instead of removing it, if the scroll bar's new parameters make the scroll bar unnecessary.
SIF_PAGE | Sets the scroll page to the value specified in the nPage member of the SCROLLINFO structure pointed to by lpsi.
SIF_POS | Sets the scroll position to the value specified in the nPos member of the SCROLLINFO structure pointed to by lpsi.
SIF_RANGE | Sets the scroll range to the value specified in the nMin and nMax members of the SCROLLINFO structure pointed to by lpsi.

Return Values

The return value is the current position of the scroll box.

Remarks

The messages that indicate scroll-bar position, WM_HSCROLL and WM_VSCROLL, provide only 16 bits of position data. However, the SCROLLINFO structure used by SBM_GETSCROLLINFO, SBM_SETSCROLLINFO, GetScrollInfo, and SetScrollInfo provides 32 bits of scroll-bar position data. You can use these messages and functions while processing either the WM_HSCROLL or WM_VSCROLL messages to obtain 32-bit scroll-bar position data.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Scroll Bars Overview, Scroll Bar Messages, GetScrollInfo, SBM_GETSCROLLINFO, SCROLLINFO, SetScrollInfo


WM_CTLCOLORSCROLLBAR

The WM_CTLCOLORSCROLLBAR message is sent to the parent window of a scroll bar control when the control is about to be drawn. By responding to this message, the parent window can use the given display context handle to set the background color of the scroll bar control.

WM_CTLCOLORSCROLLBAR
hdcSB  = (HDC) wParam;   // handle to scroll-bar display context
hwndSB = (HWND) lParam;  // handle to scroll bar

Parameters

hdcSB
Value of wParam. Handle to the device context for the scroll bar control.
hwndSB
Value of lParam. Handle to the scroll bar.

Return Values

If an application processes this message, it must return the handle to a brush. The system uses the brush to paint the background of the scroll bar control.

Default Action

The DefWindowProc function selects the default system colors for the scroll bar control.

Remarks

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_CTLCOLORSCROLLBAR message is never sent between threads; it is only sent 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.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

Scroll Bars Overview, Scroll Bar Messages, DefWindowProc, RealizePalette, SelectPalette, WM_CTLCOLORBTN, WM_CTLCOLORDLG, WM_CTLCOLOREDIT, WM_CTLCOLORLISTBOX, WM_CTLCOLORMSGBOX, WM_CTLCOLORSTATIC


WM_HSCROLL

The WM_HSCROLL message is sent to a window when a scroll event occurs in the window's standard horizontal scroll bar. This message is also sent to the owner of a horizontal scroll bar control when a scroll event occurs in the control.

WM_HSCROLL
nScrollCode = (int) LOWORD(wParam);  // scroll bar value
nPos = (short int) HIWORD(wParam);   // scroll box position
hwndScrollBar = (HWND) lParam;       // handle to scroll bar

Parameters

nScrollCode
Value of the low-order word of wParam. Specifies a scroll bar value that indicates the user's scrolling request. This parameter can be one of the following values:
Value | Meaning
SB_ENDSCROLL | Ends scroll.
SB_LEFT | Scrolls to the upper left.
SB_RIGHT | Scrolls to the lower right.
SB_LINELEFT | Scrolls left by one unit.
SB_LINERIGHT | Scrolls right by one unit.
SB_PAGELEFT | Scrolls left by the width of the window.
SB_PAGERIGHT | Scrolls right by the width of the window.
SB_THUMBPOSITION | The user has dragged the scroll box (thumb) and released the mouse button. The nPos parameter indicates the position of the scroll box at the end of the drag operation.
SB_THUMBTRACK | The user is dragging the scroll box. This message is sent repeatedly until the user releases the mouse button. The nPos parameter indicates the position that the scroll box has been dragged to.

nPos
Value of the high-order word of wParam. Specifies the current position of the scroll box if the nScrollCode parameter is SB_THUMBPOSITION or SB_THUMBTRACK; otherwise, nPos is not used.
hwndScrollBar
Value of lParam. If the message is sent by a scroll bar, then hwndScrollBar is the handle to the scroll bar control. If the message is not sent by a scroll bar, hwndScrollBar is NULL.

Return Values

If an application processes this message, it should return zero.

Remarks

The SB_THUMBTRACK notification message is typically used by applications that provide feedback as the user drags the scroll box.

If an application scrolls the content of the window, it must also reset the position of the scroll box by using the SetScrollPos function.

Note that the WM_HSCROLL message carries only 16 bits of scroll box position data. Thus, applications that rely solely on WM_HSCROLL (and WM_VSCROLL) for scroll position data have a practical maximum position value of 65,535.

However, because the SetScrollInfo, SetScrollPos, SetScrollRange, GetScrollInfo, GetScrollPos, and GetScrollRange functions support 32-bit scroll bar position data, there is a way to circumvent the 16-bit barrier of the WM_HSCROLL and WM_VSCROLL messages. See GetScrollInfo for a description of the technique.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Scroll Bars Overview, Scroll Bar Messages, GetScrollInfo, GetScrollPos, GetScrollRange, SetScrollInfo, SetScrollPos, SetScrollRange, WM_VSCROLL


WM_VSCROLL

The WM_VSCROLL message is sent to a window when a scroll event occurs in the window's standard vertical scroll bar. This message is also sent to the owner of a vertical scroll bar control when a scroll event occurs in the control.

WM_VSCROLL
nScrollCode = (int) LOWORD(wParam); // scroll bar value
nPos = (short int) HIWORD(wParam);  // scroll box position
hwndScrollBar = (HWND) lParam;      // handle to scroll bar

Parameters

nScrollCode
Value of the low-order word of wParam. Specifies a scroll bar value that indicates the user's scrolling request. This parameter can be one of the following values:
Value | Meaning
SB_BOTTOM | Scrolls to the lower right.
SB_ENDSCROLL | Ends scroll.
SB_LINEDOWN | Scrolls one line down.
SB_LINEUP | Scrolls one line up.
SB_PAGEDOWN | Scrolls one page down.
SB_PAGEUP | Scrolls one page up.
SB_THUMBPOSITION | The user has dragged the scroll box (thumb) and released the mouse button. The nPos parameter indicates the position of the scroll box at the end of the drag operation.
SB_THUMBTRACK | The user is dragging the scroll box. This message is sent repeatedly until the user releases the mouse button. The nPos parameter indicates the position that the scroll box has been dragged to.
SB_TOP | Scrolls to the upper left.

nPos
Value of the high-order word of wParam. Specifies the current position of the scroll box if the nScrollCode parameter is SB_THUMBPOSITION or SB_THUMBTRACK; otherwise, nPos is not used.
hwndScrollBar
Value of lParam. If the message is sent by a scroll bar, then hwndScrollBar is the handle to the scroll bar control. If the message is not sent by a scroll bar, hwndScrollBar is NULL.

Return Values

If an application processes this message, it should return zero.

Remarks

The SB_THUMBTRACK notification message is typically used by applications that provide feedback as the user drags the scroll box.

If an application scrolls the content of the window, it must also reset the position of the scroll box by using the SetScrollPos function.

Note that the WM_VSCROLL message carries only 16 bits of scroll box position data. Thus, applications that rely solely on WM_VSCROLL (and WM_HSCROLL) for scroll position data have a practical maximum position value of 65,535.

However, because the SetScrollInfo, SetScrollPos, SetScrollRange, GetScrollInfo, GetScrollPos, and GetScrollRange functions support 32-bit scroll bar position data, there is a way to circumvent the 16-bit barrier of the WM_HSCROLL and WM_VSCROLL messages. See GetScrollInfo for a description of the technique.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Scroll Bars Overview, Scroll Bar Messages, GetScrollInfo, GetScrollPos, GetScrollRange, SetScrollInfo, SetScrollPos, SetScrollRange, WM_HSCROLL


Scroll Bar Control Styles

To create a scroll bar control using the CreateWindow or CreateWindowEx function specify the SCROLLBAR class, appropriate window style constants, and a combination of the following scroll bar control styles. Some of the styles create a scroll bar control that uses a default width or height. However, you must always specify the x- and y-coordinates and the other dimensions of the scroll bar when you call CreateWindow or CreateWindowEx.

Style | Meaning
SBS_BOTTOMALIGN | Aligns the bottom edge of the scroll bar with the bottom edge of the rectangle defined by the x, y, nWidth, and nHeight parameters of CreateWindowEx function. The scroll bar has the default height for system scroll bars. Use this style with the SBS_HORZ style.
SBS_HORZ | Designates a horizontal scroll bar. If neither the SBS_BOTTOMALIGN nor SBS_TOPALIGN style is specified, the scroll bar has the height, width, and position specified by the x, y, nWidth, and nHeight parameters of CreateWindowEx.
SBS_LEFTALIGN | Aligns the left edge of the scroll bar with the left edge of the rectangle defined by the x, y, nWidth, and nHeight parameters of CreateWindowEx. The scroll bar has the default width for system scroll bars. Use this style with the SBS_VERT style.
SBS_RIGHTALIGN | Aligns the right edge of the scroll bar with the right edge of the rectangle defined by the x, y, nWidth, and nHeight parameters of CreateWindowEx. The scroll bar has the default width for system scroll bars. Use this style with the SBS_VERT style.
SBS_SIZEBOX | Designates a size box. If you specify neither the SBS_SIZEBOXBOTTOMRIGHTALIGN nor the SBS_SIZEBOXTOPLEFTALIGN style, the size box has the height, width, and position specified by the x, y, nWidth, and nHeight parameters of CreateWindowEx.
SBS_SIZEBOXBOTTOMRIGHT ALIGN | Aligns the lower right corner of the size box with the lower right corner of the rectangle specified by the x, y, nWidth, and nHeight parameters of CreateWindowEx. The size box has the default size for system size boxes. Use this style with the SBS_SIZEBOX style.
SBS_SIZEBOXTOPLEFTALIGN | Aligns the upper left corner of the size box with the upper left corner of the rectangle specified by the x, y, nWidth, and nHeight parameters of CreateWindowEx. The size box has the default size for system size boxes. Use this style with the SBS_SIZEBOX style.
SBS_SIZEGRIP | Same as SBS_SIZEBOX, but with a raised edge.
SBS_TOPALIGN | Aligns the top edge of the scroll bar with the top edge of the rectangle defined by the x, y, nWidth, and nHeight parameters of CreateWindowEx. The scroll bar has the default height for system scroll bars. Use this style with the SBS_HORZ style.
SBS_VERT | Designates a vertical scroll bar. If you specify neither the SBS_RIGHTALIGN nor the SBS_LEFTALIGN style, the scroll bar has the height, width, and position specified by the x, y, nWidth, and nHeight parameters of CreateWindowEx.


Static Controls

Dialog boxes and controls support communication between an application and the user. A static control is a control that enables an application to provide the user with informational text and graphics that typically require no response.


About Static Controls

Applications often use static controls to label other controls or to separate a group of controls. Although static controls are child windows, they cannot be selected. Therefore, they cannot receive the keyboard focus and cannot have a keyboard interface. A static control that has the SS_NOTIFY style receives mouse input, notifying the parent window when the user clicks or double clicks the control. Static controls belong to the STATIC window class.

Although static controls can be used in overlapped, pop-up, and child windows, they are designed for use in dialog boxes, where the system standardizes their behavior. By using static controls outside dialog boxes, a developer increases the risk that the application might behave in a nonstandard fashion. Typically, a developer either uses static controls in dialog boxes or uses the SS_OWNERDRAW style to create customized static controls.

For more information about dialog boxes, see Dialog Boxes. For more information about window classes, see Window Classes. For more information about window subclassing, see Window Procedures.


Static Control Types

There are four types of static controls:

  • simple graphics
  • text
  • image
  • owner-drawn

Each type has one or more styles. For a table of static control styles, see Static Control Styles.


Simple Graphics Static Control

A simple graphics static control displays a frame or a filled rectangle. A frame can be drawn in a number of styles, included black, gray, or white. In addition, a frame and can drawn with an etched style to give it a three-dimensional appearance. The frame styles include SS_BLACKFRAME, SS_GRAYFRAME, SS_WHITEFRAME, SS_ETCHEDHORZ, SS_ETCHEDVERT, and SS_ETCHEDFRAME.

A rectangle can be filled with color in one of three styles: black, gray, or white. These styles are defined by the constants SS_BLACKRECT, SS_GRAYRECT, and SS_WHITERECT.


Text Static Control

A text static control displays text in a rectangle in one of five styles:

  • left-aligned without word wrap
  • left aligned with word wrap
  • centered
  • right-aligned
  • simple

These styles are defined by the constants SS_LEFTNOWORDWRAP, SS_LEFT, SS_CENTER, SS_RIGHT, and SS_SIMPLE, respectively. The system rearranges the text in these controls in predefined ways, except for "simple" text, which is not rearranged.

An application can change the text in a text static control at any time by using the SetWindowText function or the WM_SETTEXT message.

The system displays as much text as it can in the static control and clips whatever does not fit. To calculate an appropriate size for the control, retrieve the font metrics for the text. For more information about fonts and font metrics, see Fonts and Text.


Image Static Control

An image static control can display bitmaps, icons (including animated icons), or enhanced metafiles. The type of graphic that a particular static control displays depends on the control's style: SS_BITMAP, SS_ICON, or SS_ENHMETAFILE. An application specifies the style when it creates the control and also specifies a handle to the bitmap, icon, or metafile for the control to display. After the control is created, an application can associate a different graphic with the control by sending it an STM_SETIMAGE message, specifying a handle to the new graphic object. An application can retrieve a handle to the graphic object currently associated with a static control by sending it an STM_GETIMAGE message. An application sends messages to a static control by using the SendDlgItemMessage function.


Owner-Drawn Static Control

By using the SS_OWNERDRAW style, an application can take responsibility for painting a static control. The parent window of an owner-drawn static control (its owner) receives a WM_DRAWITEM message whenever the static control needs to be painted. The message includes the address of a DRAWITEMSTRUCT structure that contains information that the owner window uses when drawing the control.


Static Control Default Message Processing

The window procedure for the predefined static control window class performs default processing for all messages that the static control procedure does not process. When the static control returns FALSE for any message, the predefined window procedure checks the messages and carries out the default action described in the following table. In the table, a text static control is a static control with the style SS_LEFTNOWORDWRAP, SS_LEFT, SS_CENTER, SS_RIGHT, or SS_SIMPLE.

Message | Default action
WM_CREATE | Loads the graphic object and sizes the window to the object's size, for graphic static controls. Takes no action for other static controls.
WM_DESTROY | Frees and destroys any graphic object, for graphic static controls. Takes no action for other static controls.
WM_ENABLE | Repaints visible static controls.
WM_ERASEBKGND | Returns TRUE, indicating the control erases the background.
WM_GETDLGCODE | Returns DLGC_STATIC.
WM_GETFONT | Returns a handle to the font for text static controls.
WM_GETTEXTLENGTH | Returns the length, in characters, of the text for a text static control.
WM_LBUTTONDBLCLK | Sends the parent window an STN_DBLCLK notification message if the control style is SS_NOTIFY.
WM_LBUTTONDOWN | Sends the parent window an STN_CLICKED notification message if the control style is SS_NOTIFY.
WM_NCLBUTTONDBLCLK | Sends the parent window an STN_DBLCLK notification message if the control style is SS_NOTIFY.
WM_NCLBUTTONDOWN | Sends the parent window an STN_CLICKED notification message if the control style is SS_NOTIFY.
WM_NCHITTEST | Returns HTCLIENT if the control style is SS_NOTIFY; otherwise, returns HTTRANSPARENT.
WM_PAINT | Repaints the control.
WM_SETFONT | Sets the font and repaints for text static controls.
WM_SETTEXT | Sets the text and repaints for text static controls.

The predefined window procedure passes all other messages to DefWindowProc for default processing.


Using Static Controls

The following example uses a timer and the STM_SETIMAGE message to animate an icon in a dialog box. The icon handles and the icon identifier (IDI_ICON) are defined in a global header file.

LRESULT CALLBACK StaticProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
    UINT idTimer = 1;
    static UINT i;

    static HICON aIcons[11];

    switch (message)
    {
        case WM_INITDIALOG:
            i = 0;

            // Load icons("hinst" is defined globally).

            hiconOne    = LoadIcon(hinst, "OneIco");
            aIcons[i]   = hiconOne;
            hiconTwo    = LoadIcon(hinst, "TwoIco");
            aIcons[++i] = hiconTwo;

            // Continue with the remaining icons.
            // ...

            i = 0;

            // Use STM_SETIMAGE to associate an icon with the
            // IDI_ICON identifier.

            SendDlgItemMessage(hDlg,  // dialog box window handle
               IDI_ICON,              // icon identifier
               STM_SETIMAGE,          // message to send
               (WPARAM) IMAGE_ICON,   // image type
               (LPARAM) aIcons[i++]); // icon handle

            // Set a timer for 50-millisecond intervals.

            SetTimer(hDlg, idTimer, 50, (TIMERPROC) NULL);
            return TRUE;

        case WM_TIMER:

            // Use STM_SETIMAGE to associate a new icon with
            // the IDI_ICON identifier whenever a WM_TIMER
            // message is received.

            SendDlgItemMessage(hDlg,  // dialog box window handle
               IDI_ICON,              // icon identifier
               STM_SETIMAGE,          // message to send
               (WPARAM) IMAGE_ICON,   // image type
               (LPARAM) aIcons[i++]); // new icon handle

            if (i == 10)
                i = 0;

            break;

        case WM_COMMAND:
            if (wParam == IDOK
                || wParam == IDCANCEL)
            {
                EndDialog(hDlg, TRUE);
                return TRUE;
            }
            return 0;

        case WM_DESTROY: // clean up
            KillTimer(hDlg, idTimer);
            DeleteObject(hiconOne);
            DeleteObject(hiconTwo);

            // Continue with the remaining icons.
            //  ...

            return 0;
    }
    return FALSE;
        UNREFERENCED_PARAMETER(lParam);
}


Static Control Reference

The following elements are used with static controls.

  • Static Control Messages
  • Static Control Notification Messages
  • Static Control Styles


Static Control Messages

The following messages are used with static controls. (STM_GETICON and STM_SETICON are used only with icons.)

STM_GETICON
STM_GETIMAGE
STM_SETICON
STM_SETIMAGE


STM_GETICON

An application sends the STM_GETICON message to retrieve a handle to the icon associated with a static control that has the SS_ICON style.

STM_GETICON
wParam = 0; // not used; must be zero
lParam = 0; // not used; must be zero

Parameters

This message has no parameters.

Return Values

The return value is a handle to the icon, or NULL if either the static control has no associated icon or if an error occurred.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Static Controls Overview, Static Control Messages, STM_SETICON


STM_GETIMAGE

An application sends an STM_GETIMAGE message to retrieve a handle to the image associated with a static control.

STM_GETIMAGE
wParam = (WPARAM) fImageType;  // image-type flag
lParam = 0;                    // not used; must be zero

Parameters

fImageType
Value of wParam. Specifies the type of image to retrieve. This parameter can be one of the following values:

IMAGE_BITMAP
IMAGE_CURSOR
IMAGE_ENHMETAFILE
IMAGE_ICON

Return Values

The return value is a handle to the image, if any; otherwise, it is NULL.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Static Controls Overview, Static Control Messages, STM_SETIMAGE


STM_SETICON

An application sends the STM_SETICON message to associate an icon with an icon control.

STM_SETICON
wParam = (WPARAM) (HICON) hicon;    // handle to the icon
lParam = 0;                         // not used; must be zero

Parameters

hicon
Value of wParam. Handle to the icon to associate with the icon control.

Return Values

The return value is a handle to the icon previously associated with the icon control, or zero if an error occurs.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Static Controls Overview, Static Control Messages, LoadIcon, STM_GETICON


STM_SETIMAGE

An application sends an STM_SETIMAGE message to associate a new image (icon or bitmap) with a static control.

STM_SETIMAGE
wParam = (WPARAM) fImageType;       // image-type flag
lParam = (LPARAM) (HANDLE) hImage;  // handle to the image

Parameters

fImageType
Value of wParam. Specifies the type of image to associate with the static control. This parameter can be one of the following values:

IMAGE_BITMAP
IMAGE_CURSOR
IMAGE_ENHMETAFILE
IMAGE_ICON

hImage
Value of lParam. Handle to the image to associate with the static control.

Return Values

The return value is a handle to the image previously associated with the static control, if any; otherwise, it is NULL.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Static Controls Overview, Static Control Messages, STM_GETIMAGE


Static Control Notification Messages

Static controls with the SS_NOTIFY style send the following notification messages to their parent window.

STN_CLICKED
STN_DBLCLK
STN_DISABLE
STN_ENABLE
WM_CTLCOLORSTATIC


STN_CLICKED

The STN_CLICKED notification message is sent when the user clicks a static control that has the SS_NOTIFY style. The parent window of the control receives this notification message through the WM_COMMAND message.

STN_CLICKED
idStatic = (int) LOWORD(wParam);    // identifier of static control
hwndStatic = (HWND) LOWORD(lParam); // handle to static control

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Static Controls Overview, Static Control Notification Messages, STN_DBLCLK, WM_COMMAND


STN_DBLCLK

The STN_DBLCLK notification message is sent when the user double-clicks a static control that has the SS_NOTIFY style. The parent window of the control receives this notification message through the WM_COMMAND message.

STN_DBLCLK
idStatic = (int) LOWORD(wParam);    // identifier of static control
hwndStatic = (HWND) LOWORD(lParam); // handle to static control

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Static Controls Overview, Static Control Notification Messages, STN_CLICKED, WM_COMMAND


STN_DISABLE

The STN_DISABLE notification message is sent when a static control is disabled. The static control must have the SS_NOTIFY style to receive this notification message. The parent window of the control receives this notification message through the WM_COMMAND message.

STN_DISABLE
idStatic = (int) LOWORD(wParam);    // identifier of static control
hwndStatic = (HWND) LOWORD(lParam); // handle to static control

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Static Controls Overview, Static Control Notification Messages, STN_ENABLE, WM_COMMAND


STN_ENABLE

The STN_ENABLE notification message is sent when a static control is enabled. The static control must have the SS_NOTIFY style to receive this notification message. The parent window of the control receives this notification message through the WM_COMMAND message.

STN_ENABLE
idStatic = (int) LOWORD(wParam);    // identifier of static control
hwndStatic = (HWND) LOWORD(lParam); // handle to static control

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Static Controls Overview, Static Control Notification Messages, STN_DISABLE, WM_COMMAND


WM_CTLCOLORSTATIC

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.

WM_CTLCOLORSTATIC
hdcStatic = (HDC) wParam;   // handle to display context
hwndStatic = (HWND) lParam; // handle to static control

Parameters

hdcStatic
Value of wParam. Handle to the device context for the static control window.
hwndStatic
Value of lParam. Handle to the static control.

Return Values

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.

Default Action

The DefWindowProc function selects the default system colors for the static control.

Remarks

Edit controls that are not read-only or disabled do not send the WM_CTLCOLORSTATIC message; instead, they send the WM_CTLCOLOREDIT message. However, for compatibility purposes, the system sends the WM_CTLCOLOREDIT message for read-only and disabled edit controls if the application was designed for Windows 3.1 or earlier.

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.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

Static Controls Overview, Static Control Notification Messages, DefWindowProc, RealizePalette, SelectPalette, WM_CTLCOLORBTN, WM_CTLCOLORDLG, WM_CTLCOLOREDIT, WM_CTLCOLORLISTBOX, WM_CTLCOLORMSGBOX, WM_CTLCOLORSCROLLBAR


Static Control Styles

To create a static control using the CreateWindow or CreateWindowEx function, specify the STATIC class, appropriate window style constants, and a combination of the following static control styles.

Style | Description
SS_BITMAP | Specifies a bitmap is to be displayed in the static control. The given text is the name of a bitmap (not a filename) defined elsewhere in the resource file. The style ignores the nWidth and nHeight parameters; the control automatically sizes itself to accommodate the bitmap.
SS_BLACKFRAME | Specifies a box with a frame drawn in the same color as the window frames. This color is black in the default color scheme.
SS_BLACKRECT | Specifies a rectangle filled with the current window frame color. This color is black in the default color scheme.
SS_CENTER | Specifies a simple rectangle and centers the given text in the rectangle. The text is formatted before it is displayed. Words that extend past the end of a line are automatically wrapped to the beginning of the next centered line.
SS_CENTERIMAGE | Specifies that, if the bitmap or icon is smaller than the client area of the static control, the rest of the client area is filled with the color of the pixel in the top left corner of the bitmap or icon. If the static control contains a single line of text, the text is centered vertically in the client area of the control.
SS_ENDELLIPSIS or
SS_PATHELLIPSIS 		Replaces part of the given string with ellipses, if necessary, so that the result fits in the specified rectangle.

You can specify SS_END_ELLIPSIS to replace characters at the end of the string, or SS_PATHELLIPSIS to replace characters in the middle of the string. If the string contains backslash (\) characters, SS_PATHELLIPSIS preserves as much of the text after the last backslash as possible.

SS_ENHMETAFILE | Specifies an enhanced metafile is to be displayed in the static control. The given text is the name of a metafile. An enhanced metafile static control has a fixed size; the metafile is scaled to fit the static control's client area.
SS_ETCHEDFRAME | Draws the frame of the static control using the EDGE_ETCHED edge style. For more information, see the DrawEdge function.
SS_ETCHEDHORZ | Draws the top and bottom edges of the static control using the EDGE_ETCHED edge style. For more information, see the DrawEdge function.
SS_ETCHEDVERT | Draws the left and right edges of the static control using the EDGE_ETCHED edge style. For more information, see the DrawEdge function.
SS_GRAYFRAME | Specifies a box with a frame drawn with the same color as the screen background (desktop). This color is gray in the default color scheme.
SS_GRAYRECT | Specifies a rectangle filled with the current screen background color. This color is gray in the default color scheme.
SS_ICON | Specifies an icon is to be displayed in the dialog box. The given text is the name of an icon (not a filename) defined elsewhere in the resource file. The icon can be an animated cursor. The style ignores the nWidth and nHeight parameters; the control automatically sizes itself to accommodate the icon.
SS_LEFT | Specifies a simple rectangle and left-aligns the given text in the rectangle. The text is formatted before it is displayed. Words that extend past the end of a line are automatically wrapped to the beginning of the next left-aligned line.
SS_LEFTNOWORDWRAP | Specifies a simple rectangle and left-aligns the given text in the rectangle. Tabs are expanded, but words are not wrapped. Text that extends past the end of a line is clipped.
SS_NOPREFIX | Prevents interpretation of any ampersand (&) characters in the control's text as accelerator prefix characters. These are displayed with the ampersand removed and the next character in the string underlined. This static control style may be included with any of the defined static controls. You can combine SS_NOPREFIX with other styles. This can be useful when filenames or other strings that may contain an ampersand (&) must be displayed in a static control in a dialog box.
SS_NOTIFY | Sends the parent window STN_CLICKED, STN_DBLCLK, STN_DISABLE, and STN_ENABLE notification messages when the user clicks or double-clicks the control.
SS_OWNERDRAW | Specifies that the owner of the static control is responsible for drawing the control. The owner window receives a WM_DRAWITEM message whenever the control needs to be drawn.
SS_REALSIZEIMAGE | Prevents a static icon or bitmap control (that is, static controls that have the SS_ICON or SS_BITMAP style) from being resized as it is loaded or drawn. If the icon or bitmap is larger than the destination area, the image is clipped.
SS_RIGHT | Specifies a simple rectangle and right-aligns the given text in the rectangle. The text is formatted before it is displayed. Words that extend past the end of a line are automatically wrapped to the beginning of the next right-aligned line.
SS_RIGHTJUST | Specifies that the lower right corner of a static control with the SS_BITMAP or SS_ICON style is to remain fixed when the control is resized. Only the top and left sides are adjusted to accommodate a new bitmap or icon.
SS_SIMPLE | Specifies a simple rectangle and displays a single line of left-aligned text in the rectangle. The text line cannot be shortened or altered in any way. The control's parent window or dialog box must not process the WM_CTLCOLORSTATIC message.
SS_SUNKEN | Draws a half-sunken border around a static control.
SS_WHITEFRAME | Specifies a box with a frame drawn with the same color as the window background. This color is white in the default color scheme.
SS_WHITERECT | Specifies a rectangle filled with the current window background color. This color is white in the default color scheme.
SS_WORDELLIPSIS | Truncates text that does not fit and adds ellipses.


Carets

A caret is a blinking line, block, or bitmap in the client area of a window. The caret typically indicates the place at which text or graphics will be inserted. The following illustration shows some common variations in the appearance of the caret.

A Win32-based application can create a caret, change its blink time, and display, hide, or relocate the caret.


About Carets

The system provides one caret per message queue. A window should create a caret only when it has the keyboard focus or is active. The window should destroy the caret before losing the keyboard focus or becoming inactive. For more information on keyboard input, see Keyboard Input.

Use the CreateCaret function to specify the parameters for a caret. The system forms a caret by inverting the pixel color within the rectangle specified by the caret's position, width, and height. The width and height are specified in logical units; therefore, the appearance of a caret is subject to the window's mapping mode.


Caret Visibility

After the caret is defined, use the ShowCaret function to make the caret visible. When the caret appears, it automatically begins flashing. To display a solid caret, the system inverts every pixel in the rectangle; to display a gray caret, the system inverts every other pixel; to display a bitmap caret, the system inverts only the white bits of the bitmap.


Caret Blink Time

The elapsed time, in milliseconds, required to invert the caret is called the blink time. The caret will blink as long as the thread that owns the message queue has a message pump processing the messages.

The user can set the blink time of the caret using the Control Panel and applications should respect the settings that the user has chosen. An application can determine the caret's blink time by using the GetCaretBlinkTime function. If you are writing an application that allows the user to adjust the blink time, such as a Control Panel applet, use the SetCaretBlinkTime function to set the rate of the blink time to a specified number of milliseconds.

The flash time is the elapsed time, in milliseconds, required to display, invert, and restore the caret's display. The flash time of a caret is twice as much as the blink time.


Caret Position

You can determine the position of the caret using the GetCaretPos function. The position, in client coordinates, is copied to a POINT structure specified by a parameter in GetCaretPos. An application can move a caret in a window by using the SetCaretPos function. A window can move a caret only if it already owns the caret. SetCaretPos can move the caret whether it is visible or not.


Removing a Caret

You can temporarily remove a caret by hiding it, or you can permanently remove the caret by destroying it. To hide the caret, use the HideCaret function. This is useful when your application must redraw the screen while processing a message, but must keep the caret out of the way. When the application finishes drawing, it can display the caret again by using the ShowCaret function. Hiding the caret does not destroy its shape or invalidate the insertion point. Hiding the caret is cumulative; that is, if the application calls HideCaret five times, it must also call ShowCaret five times before the caret will reappear.

To remove the caret from the screen and destroy its shape, use using the DestroyCaret function. DestroyCaret destroys the caret only if the window involved in the current task owns the caret.


Using Carets

  • Creating and displaying a caret
  • Hiding a caret
  • Destroying a caret
  • Adjusting the blink time
  • Processing keyboard input


Creating and Displaying a Caret

Upon receiving the keyboard focus, the window should create and display the caret. Use the CreateCaret function to create a caret in the given window. You can then call SetCaretPos to set the current position of the caret and ShowCaret to make the caret visible.

The system sends the WM_SETFOCUS message to the window receiving keyboard focus; therefore, an application should create and display the caret while processing this message.

HWND hwnd,       // window handle
int x;           // horizontal coordinate of cursor
int y;           // vertical coordinate of cursor
int nWidth;      // width of cursor
int nHeight;     // height of cursor
char *lpszChar;  // pointer to character

    case WM_SETFOCUS:

    // Create a solid black caret.
        CreateCaret(hwnd, (HBITMAP) NULL, nWidth, nHeight);

    // Adjust the caret position, in client coordinates.
        SetCaretPos(x, y);

    // Display the caret.
        ShowCaret(hwnd);

        break;

To create a caret based on a bitmap, you must specify a bitmap handle when using CreateCaret. You can use a graphics application to create the bitmap and a resource compiler to add the bitmap to your application's resources. Your application can then use the LoadBitmap function to load the bitmap handle. For example, you could replace the CreateCaret line in the preceding example with the following lines to create a bitmap caret.

// Load the application-defined caret resource.

    hCaret = LoadBitmap(hinst, MAKEINTRESOURCE(120));

// Create a bitmap caret.

    CreateCaret(hwnd, hCaret, 0, 0);

Alternatively, you can use the CreateBitmap or CreateDIBitmap function to retrieve the handle of the caret bitmap. For more information about bitmaps, see Bitmaps.

If your application specifies a bitmap handle, CreateCaret ignores the width and height parameters. The bitmap defines the size of the caret.


Hiding a Caret

Whenever your application redraws a screen while processing a message other than WM_PAINT, it must make the caret invisible by using the HideCaret function. When your application is finished drawing, redisplay the caret by using the ShowCaret function. If your application processes the WM_PAINT message, it is not necessary to hide and redisplay the caret, because this function does this automatically.

The following code sample shows how to have your application hide the caret while drawing a character on the screen and while processing the WM_CHAR message.

HWND hwnd,   // window handle
HDC hdc;     // device context

    case WM_CHAR:
        switch (wParam)
        {
            case 0x08:

             // Process a backspace.

                break;

            case 0x09:

             // Process a tab.

                break;

            case 0x0D:

             // Process a carriage return.

                break;

            case 0x1B:

             // Process an escape.

                break;

            case 0x0A:

             // Process a linefeed.

                break;

            default:
                // Hide the caret.

                HideCaret(hwnd);

                // Draw the character on the screen.

                hdc = GetDC(hwnd);
                SelectObject(hdc,
                    GetStockObject(SYSTEM_FIXED_FONT));

                TextOut(hdc, x, y, lpszChar, 1);

                ReleaseDC(hwnd, hdc);

                // Display the caret.

                ShowCaret(hwnd);

        }

If your application calls the HideCaret function several times without calling ShowCaret, the caret will not be displayed until the application also calls ShowCaret the same number of times.


Destroying a Caret

When a window loses the keyboard focus, the system sends the WM_KILLFOCUS message to the window. Your application should destroy the caret while processing this message by using the DestroyCaret function. The following code shows how to destroy a caret in a window that no longer has the keyboard focus.

case WM_KILLFOCUS:

// The window is losing the keyboard focus, so destroy the caret.

    DestroyCaret();

    break;


Adjusting the Blink Time

In 16-bit Windows, a Windows-based application could call the GetCaretBlinkTime function to save the current blink time, then call the SetCaretBlinkTime function to adjust the blink time during its processing of the WM_SETFOCUS message. The application would restore the saved blink time for the use of other applications by calling SetCaretBlinkTime during its processing of the WM_KILLFOCUS message. However, this technique does not work on 32-bit Windows and Windows NT, because they are robust, multithreaded environments. Specifically, the deactivation of one application is not synchronized with the activation of another application, so that if one application hangs, another application can still be activated.

Win32-based applications should respect the blink time chosen by the user. The SetCaretBlinkTime function should only be called by an application that allows the user to set the blink time.


Processing Keyboard Input

The following example demonstrates how to use a caret in a simple text editor. The example updates the caret position as the user types printable characters and uses various keys to move through the client area.

#define TEXTMATRIX(x, y) *(pTextMatrix + (y * nWindowCharsX) + x)

// Global variables.

HINSTANCE hinst;      // current instance
HBITMAP hCaret;       // caret bitmap
HDC hdc;              // device context
PAINTSTRUCT ps;       // client area paint info
static char *pTextMatrix = NULL; // points to text matrix
static int  nCharX,   // width of char. in logical units
            nCharY,   // height of char. in logical units
            nWindowX, // width of client area
            nWindowY, // height of client area
            nWindowCharsX, // width of client area
            nWindowCharsY, // height of client area
            nCaretPosX,    // x-position of caret
            nCaretPosY;    // y-position of caret
static UINT uOldBlink;     // previous blink rate
int x, y;    // x and y coordinates to use in text matrix
TEXTMETRIC tm;             // font information

LONG APIENTRY MainWndProc(
    HWND hwnd,            // window handle
    UINT message,         // type of message
    UINT wParam,          // additional information
    LONG lParam)          // additional information
{

    switch (message)
    {
        case WM_CREATE:
        // Select a fixed-width system font, and get its text metrics.

            hdc = GetDC(hwnd);
            SelectObject(hdc,
                GetStockObject(SYSTEM_FIXED_FONT));
            GetTextMetrics(hdc, &tm);
            ReleaseDC(hwnd, hdc);

        // Save the avg. width and height of characters.

            nCharX = tm.tmAveCharWidth;
            nCharY = tm.tmHeight;

            return 0;

        case WM_SIZE:
        // Determine the width of the client area, in pixels
        // and in number of characters.

            nWindowX = LOWORD(lParam);
            nWindowCharsX = max(1, nWindowX/nCharX);

            // Determine the height of the client area, in
            // pixels and in number of characters.

            nWindowY = HIWORD(lParam);
            nWindowCharsY = max(1, nWindowY/nCharY);

            // Clear the buffer that holds the text input.

            if (pTextMatrix != NULL)
                free(pTextMatrix);

            // If there is enough memory, allocate space for the
            // text input buffer.

            pTextMatrix = malloc(nWindowCharsX * nWindowCharsY);

            if (pTextMatrix == NULL)
                ErrorHandler("Not enough memory.");
            else
                for (y = 0; y < nWindowCharsY; y++)
                    for (x = 0; x < nWindowCharsX; x++)
                        TEXTMATRIX(x, y) = ' ';

            // Move the caret to the origin.

            SetCaretPos(0, 0);

            return 0;

        case WM_KEYDOWN:
            switch (wParam)
            {
                case VK_HOME:       // Home
                    nCaretPosX = 0;
                    break;

                case VK_END:        // End
                    nCaretPosX = nWindowCharsX - 1;
                    break;

                case VK_PRIOR:      // Page Up
                    nCaretPosY = 0;
                    break;

                case VK_NEXT:       // Page Down
                    nCaretPosY = nWindowCharsY -1;
                    break;

                case VK_LEFT:       // Left arrow
                    nCaretPosX = max(nCaretPosX - 1, 0);
                    break;

                case VK_RIGHT:      // Right arrow
                    nCaretPosX = min(nCaretPosX + 1,
                        nWindowCharsX - 1);
                    break;

                case VK_UP:         // Up arrow
                    nCaretPosY = max(nCaretPosY - 1, 0);
                    break;

                case VK_DOWN:       // Down arrow
                    nCaretPosY = min(nCaretPosY + 1,
                        nWindowCharsY - 1);
                    break;

                case VK_DELETE:     // Delete

                // Move all the characters that followed the
                // deleted character (on the same line) one
                // space back (to the left) in the matrix.

                    for (x = nCaretPosX; x < nWindowCharsX; x++)
                        TEXTMATRIX(x, nCaretPosY) =
                            TEXTMATRIX(x + 1, nCaretPosY);

                    // Replace the last character on the
                    // line with a space.

                    TEXTMATRIX(nWindowCharsX - 1,
                        nCaretPosY) = ' ';

                    // The application will draw outside the
                    // WM_PAINT message processing, so hide the caret.

                    HideCaret(hwnd);

                    // Redraw the line, adjusted for the
                    // deleted character.

                    hdc = GetDC(hwnd);
                    SelectObject(hdc,
                        GetStockObject(SYSTEM_FIXED_FONT));

                    TextOut(hdc, nCaretPosX * nCharX,
                        nCaretPosY * nCharY,
                        &TEXTMATRIX(nCaretPosX, nCaretPosY),
                        nWindowCharsX - nCaretPosX);

                    ReleaseDC(hwnd, hdc);

                    // Display the caret.

                    ShowCaret(hwnd);

                    break;
            }

            // Adjust the caret position based on the
            // virtual-key processing.

            SetCaretPos(nCaretPosX * nCharX,
                nCaretPosY * nCharY);

            return 0;

        case WM_CHAR:
            switch (wParam)
            {
                case 0x08:          // Backspace
                // Move the caret back one space, and then
                // process this like the DEL key.

                    if (nCaretPosX > 0)
                    {
                        nCaretPosX--;
                        SendMessage(hwnd, WM_KEYDOWN,
                            VK_DELETE, 1L);
                    }
                    break;

                case 0x09:          // Tab
                // Tab stops exist every four spaces, so add
                // spaces until the user hits the next tab.

                    do
                    {
                        SendMessage(hwnd, WM_CHAR, ' ', 1L);
                    } while (nCaretPosX % 4 != 0);
                    break;

                case 0x0D:          // Carriage return
                // Go to the beginning of the next line.
                // The bottom line wraps around to the top.

                    nCaretPosX = 0;

                    if (++nCaretPosY == nWindowCharsY)
                        nCaretPosY = 0;
                    break;

                case 0x1B:        // Escape
                case 0x0A:        // Linefeed
                    MessageBeep((UINT) -1);
                    break;

                default:
                // Add the character to the text buffer.

                    TEXTMATRIX(nCaretPosX, nCaretPosY) =
                        (char) wParam;

                // The application will draw outside the
                // WM_PAINT message processing, so hide the caret.

                    HideCaret(hwnd);

                // Draw the character on the screen.

                    hdc = GetDC(hwnd);
                    SelectObject(hdc,
                        GetStockObject(SYSTEM_FIXED_FONT));

                    TextOut(hdc, nCaretPosX * nCharX,
                        nCaretPosY * nCharY,
                        &TEXTMATRIX(nCaretPosX, nCaretPosY), 1);

                    ReleaseDC(hwnd, hdc);

                    // Display the caret.

                    ShowCaret(hwnd);

                    // Prepare to wrap around if you reached the
                    // end of the line.

                    if (++nCaretPosX == nWindowCharsX)
                    {
                        nCaretPosX = 0;
                        if (++nCaretPosY == nWindowCharsY)
                            nCaretPosY = 0;
                    }
                    break;
            }

            // Adjust the caret position based on the
            // character processing.

            SetCaretPos(nCaretPosX * nCharX,
                nCaretPosY * nCharY);

            return 0;

        case WM_PAINT:
        // Draw all the characters in the buffer, line by line.

            hdc = BeginPaint(hwnd, &ps);

            SelectObject(hdc,
                GetStockObject(SYSTEM_FIXED_FONT));

            for (y = 0; y < nWindowCharsY; y++)
                TextOut(hdc, 0, y * nCharY, &TEXTMATRIX(0, y),
                    nWindowCharsX);

            EndPaint(hwnd, &ps);

        case WM_SETFOCUS:
        // The window has the input focus. Load the
        // application-defined caret resource.

            hCaret = LoadBitmap(hinst, MAKEINTRESOURCE(120));

            // Create the caret.

            CreateCaret(hwnd, hCaret, 0, 0);

            // Adjust the caret position.

            SetCaretPos(nCaretPosX * nCharX,
                nCaretPosY * nCharY);

            // Display the caret.

            ShowCaret(hwnd);

            break;

        case WM_KILLFOCUS:
        // The window is losing the input focus,
        // so destroy the caret.

            DestroyCaret();

            break;

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

    }

    return NULL;
}


Caret Reference

The following elements are used with carets.

  • Caret Functions


Caret Functions

The following functions are used with carets.

CreateCaret
DestroyCaret
GetCaretBlinkTime
GetCaretPos
HideCaret
SetCaretBlinkTime
SetCaretPos
ShowCaret


CreateCaret

The CreateCaret function creates a new shape for the system caret and assigns ownership of the caret to the specified window. The caret shape can be a line, a block, or a bitmap.

BOOL CreateCaret(
  HWND hWnd,        // handle to owner window
  HBITMAP hBitmap,  // handle to bitmap for caret shape
  int nWidth,       // caret width
  int nHeight       // caret height
);

Parameters

hWnd
Identifies the window that owns the caret.
hBitmap
Identifies the bitmap that defines the caret shape. If this parameter is NULL, the caret is solid. If this parameter is (HBITMAP) 1, the caret is gray. If this parameter is a bitmap handle, the caret is the specified bitmap. The bitmap handle must have been created by the CreateBitmap, CreateDIBitmap, or LoadBitmap function.

If hBitmap is a bitmap handle, CreateCaret ignores the nWidth and nHeight parameters; the bitmap defines its own width and height.

nWidth
Specifies the width of the caret in logical units. If this parameter is zero, the width is set to the system-defined window border width. If hBitmap is a bitmap handle, CreateCaret ignores this parameter.
nHeight
Specifies the height, in logical units, of the caret. If this parameter is zero, the height is set to the system-defined window border height. If hBitmap is a bitmap handle, CreateCaret ignores this parameter.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The nWidth and nHeight parameters specify the caret's width and height, in logical units; the exact width and height, in pixels, depend on the window's mapping mode.

CreateCaret automatically destroys the previous caret shape, if any, regardless of the window that owns the caret. The caret is hidden until the application calls the ShowCaret function to make the caret visible.

The system provides one caret per queue. A window should create a caret only when it has the keyboard focus or is active. The window should destroy the caret before losing the keyboard focus or becoming inactive.

You can retrieve the width or height of the system's window border by using the GetSystemMetrics function, specifying the SM_CXBORDER and SM_CYBORDER values. Using the window border width or height guarantees that the caret will be visible on a high-resolution screen.

Windows CE: Windows CE does not support the hBitmap parameter and it should be set to NULL. Windows CE defaults to a solid caret.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Carets Overview, Caret Functions, CreateBitmap, CreateDIBitmap, DestroyCaret, GetSystemMetrics, HideCaret, LoadBitmap, ShowCaret


DestroyCaret

The DestroyCaret function destroys the caret's current shape, frees the caret from the window, and removes the caret from the screen.

If the caret shape is based on a bitmap, DestroyCaret does not free the bitmap.

BOOL DestroyCaret(VOID)

Parameters

This function has no parameters.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

DestroyCaret destroys the caret only if a window in the current task owns the caret. If a window that is not in the current task owns the caret, DestroyCaret does nothing and returns FALSE.

The system provides one caret per queue. A window should create a caret only when it has the keyboard focus or is active. The window should destroy the caret before losing the keyboard focus or becoming inactive.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Carets Overview, Caret Functions, CreateCaret, HideCaret, ShowCaret


GetCaretBlinkTime

The GetCaretBlinkTime function returns the elapsed time, in milliseconds, required to invert the caret's pixels. The user can set this value using the Control Panel.

UINT GetCaretBlinkTime(VOID)

Parameters

This function has no parameters.

Return Values

If the function succeeds, the return value is the blink time, in milliseconds.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Carets Overview, Caret Functions, SetCaretBlinkTime


GetCaretPos

The GetCaretPos function copies the caret's position, in client coordinates, to the specified POINT structure.

BOOL GetCaretPos(
  LPPOINT lpPoint   // address of structure to receive coordinates
);

Parameters

lpPoint
Pointer to the POINT structure that is to receive the client coordinates of the caret.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The caret position is always given in the client coordinates of the window that contains the caret.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Carets Overview, Caret Functions, SetCaretPos, POINT


HideCaret

The HideCaret function removes the caret from the screen. Hiding a caret does not destroy its current shape or invalidate the insertion point.

BOOL HideCaret(
  HWND hWnd   // handle to the window with the caret
);

Parameters

hWnd
Identifies the window that owns the caret. If this parameter is NULL, HideCaret searches the current task for the window that owns the caret.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

HideCaret hides the caret only if the specified window owns the caret. If the specified window does not own the caret, HideCaret does nothing and returns FALSE.

Hiding is cumulative. If your application calls HideCaret five times in a row, it must also call ShowCaret five times before the caret is displayed.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Carets Overview, Caret Functions, CreateCaret, DestroyCaret, GetCaretPos, SetCaretPos, ShowCaret


SetCaretBlinkTime

The SetCaretBlinkTime function sets the caret blink time to the specified number of milliseconds. The blink time is the elapsed time, in milliseconds, required to invert the caret's pixels.

BOOL SetCaretBlinkTime(
  UINT uMSeconds   // blink time, in milliseconds
);

Parameters

uMSeconds
Specifies the new blink time, in milliseconds.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The user can set the blink time using the Control Panel. Applications should respect the setting that the user has chosen. The SetCaretBlinkTime function should only be used by application that allow the user to set the blink time, such as a Control Panel applet.

If you change the blink time, subsequently activated applications will use the modified blink time, even if you restore the previous blink time when you lose the keyboard focus or become inactive. This is due to the multithreaded environment, where deactivation of your application is not synchronized with the activation of another application. This feature allows the system to activate another application even if the current application is hung.

Windows CE: In Windows CE, changing the caret blink time in one application will not affect the blink time in subsequently loaded applications.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Carets Overview, Caret Functions, GetCaretBlinkTime


SetCaretPos

The SetCaretPos function moves the caret to the specified coordinates. If the window that owns the caret was created with the CS_OWNDC class style, then the specified coordinates are subject to the mapping mode of the device context associated with that window.

BOOL SetCaretPos(
  int X,  // horizontal position
  int Y   // vertical position
);

Parameters

X
Specifies the new x-coordinate of the caret.
Y
Specifies the new y-coordinate of the caret.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

SetCaretPos moves the caret whether or not the caret is hidden.

The system provides one caret per queue. A window should create a caret only when it has the keyboard focus or is active. The window should destroy the caret before losing the keyboard focus or becoming inactive. A window can set the caret position only if it owns the caret.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Carets Overview, Caret Functions, GetCaretPos, HideCaret, ShowCaret


ShowCaret

The ShowCaret function makes the caret visible on the screen at the caret's current position. When the caret becomes visible, it begins flashing automatically.

BOOL ShowCaret(
  HWND hWnd   // handle of window with caret
);

Parameters

hWnd
Identifies the window that owns the caret. If this parameter is NULL, ShowCaret searches the current task for the window that owns the caret.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

ShowCaret shows the caret only if the specified window owns the caret, the caret has a shape, and the caret has not been hidden two or more times in a row. If one or more of these conditions is not met, ShowCaret does nothing and returns FALSE.

Hiding is cumulative. If your application calls HideCaret five times in a row, it must also call ShowCaret five times before the caret reappears.

The system provides one caret per queue. A window should create a caret only when it has the keyboard focus or is active. The window should destroy the caret before losing the keyboard focus or becoming inactive.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Carets Overview, Caret Functions, CreateCaret, DestroyCaret, GetCaretPos, HideCaret, SetCaretPos


Cursors

A cursor is a small picture whose location on the screen is controlled by a pointing device, such as a mouse, pen, or trackball. In the remainder of this overview, the term mouse refers to any pointing device.

When the user moves the mouse, the system moves the cursor accordingly. The Win32 cursor functions enable applications to create, load, display, move, confine, and destroy cursors.


About Cursors

The Win32 API provides a set of standard cursors that are available for any application to use at any time. The SDK header files contain identifiers for the standard cursors — the identifiers begin with the "IDC_" prefix.

Each standard cursor has a corresponding default image associated with it. The user or an application can replace the default image associated with any standard cursor at any time. An application replaces a default image by using the SetSystemCursor function.

An application can use the GetIconInfo function to retrieve the current image for a cursor, and can draw the cursor by using the DrawIconEx function. To draw the default image for a standard cursor, specify the DI_COMPAT flag in the call to DrawIconEx. If you do not specify the DI_COMPAT flag, DrawIconEx draws the standard cursor using the image that the user specified.

Custom cursors are designed for use in a specific application and can be any design the developer defines. The following illustration shows several custom cursors.

Cursors can be either monochrome or color, and either static or animated. The type of cursor used on a particular computer system depends on the system's display. Old displays such as VGA do not support color or animated cursors, but new displays (whose display drivers use the DIB engine) do support them.

Cursors and icons are similar and can be used interchangeably in many situations. The only difference between them is that an image specified as a cursor must be in the format that the display can support. For example, a cursor must be monochrome for a VGA display.


The Hot Spot

In the cursor, a pixel called the hot spot marks the exact screen location that is affected by a mouse event, such as clicking a mouse button. Typically, the hot spot is the focal point of the cursor. The system tracks and recognizes this point as the position of the cursor. For example, typical hot spots are the pixel at the tip of an arrow-shaped cursor and the pixel in the middle of a crosshair-shaped cursor.

When a mouse input event occurs, the mouse driver translates the event into an appropriate mouse message that includes the coordinates of the hot spot. The system sends the mouse message to the window that contains the hot spot or to the window that is capturing mouse input. For more information, see Mouse Input.


The Mouse and the Cursor

The system reflects the movement of the mouse by moving the cursor on the screen accordingly. As the cursor moves over different parts of windows or into different windows, the system (or an application) changes the appearance of the cursor. For example, when the cursor crosses a window border, the system changes the cursor into a two-headed arrow.

If the system does not have a mouse, the system displays and moves the cursor only when the user chooses certain system commands, such as those used to size or move a window. To provide the user with a method of displaying and moving the cursor when a mouse isn't available, an application can use the cursor functions to simulate mouse movement. Given this simulation capability, the user can use the arrow keys to move the cursor.


Cursor Creation

Because standard cursors are predefined, it is not necessary to create them. To use a standard cursor, an application retrieves a cursor handle by using the LoadCursor or LoadImage function. A cursor handle is a unique value of the HCURSOR type that identifies a standard or custom cursor.

To create a custom cursor for an application, you would typically use a graphics application and include the cursor as a resource in the application's resource-definition file. At run time, call LoadCursor to retrieve the cursor handle. Cursor resources contain data for several different display devices. The LoadCursor function automatically selects the most appropriate data for the current display device. To load a cursor directly from a .CUR or .ANI file, use the LoadCursorFromFile function.

You can also create a custom cursor at run time by using the CreateIconIndirect function, which creates a cursor based on the content of an ICONINFO structure. The GetIconInfo function fills this structure with hot spot coordinates and information concerning the associated bitmask and color.

Applications should implement custom cursors as resources and use LoadCursor, LoadCursorFromFile, or LoadImage rather than create the cursor at run time. Using cursor resources avoids device dependence, simplifies localization, and enables applications to share cursor designs.

The CreateIconFromResourceEx function enables an application to create icons and cursors based on resource data. CreateIconFromResourceEx creates a cursor based on binary resource data from other executable (.EXE) files or dynamic-link libraries (DLLs). It must be preceded by calls to the LookupIconIdFromDirectoryEx function, as well as several resource functions. LookupIconIdFromDirectoryEx identifies the most appropriate cursor data for the current display device. For more information about resource functions, see Resources.


Cursor Location and Appearance

The system automatically displays a cursor for the mouse and updates its position on the screen. You can obtain current screen coordinates of the cursor and move the cursor to any location on the screen by using the GetCursorPos and SetCursorPos functions, respectively.

You can also retrieve the handle to the current cursor by using the GetCursor function and you can set the cursor by using the SetCursor function. After you call SetCursor, the appearance of the cursor does not change until either the mouse moves, the cursor is explicitly set to a different cursor, or a system command is executed.

When the user moves the mouse, the system redraws the cursor at the new location. The system automatically redraws the cursor design associated with the window to which the cursor is pointing.

You can hide and redisplay the cursor, without changing the cursor design, by using the ShowCursor function. This function uses an internal counter to determine when to hide or display the cursor. An attempt to show the cursor increments the counter; an attempt to hide the cursor decrements the counter. The cursor is visible only if this counter is greater than or equal to zero.


The Window Class Cursor

When you register a window class, using the RegisterClass function, you can assign it a default cursor, known as the class cursor. After the application registers the window class, each window of that class will have the specified class cursor.

To override the class cursor, process the WM_SETCURSOR message. You can also replace a class cursor by using the SetClassLong function. This function changes the default window settings for all windows of a given class. For more information, see Window Classes.


Cursor Confinement

You can confine the cursor to a rectangular area on the screen by using the ClipCursor function. This is useful for when the user must respond to a certain event within the confined area of the rectangle. For example, you might use ClipCursor to confine the cursor to a modal dialog box, preventing the user from interacting with other windows until the dialog box is closed.

The GetClipCursor function retrieves the screen coordinates of the rectangular area to which the cursor is temporarily confined. When it is necessary to confine the cursor, you can also use this function to save the coordinates of the original area in which the cursor can move. Then, you can restore the cursor to the original area when the new confinement is no longer necessary.


Cursor Destruction

You can destroy the cursor handle and free the memory the cursor used by calling the DestroyCursor function. However, this function has no effect on a shared cursor. A shared cursor is valid as long as the module from which it was loaded remains in memory. The following functions obtain a shared cursor:

  • LoadCursor
  • LoadCursorFromFile
  • LoadImage (if you use the LR_SHARED flag)
  • CopyImage (if you use the LR_COPYRETURNORG flag and the hImage is a shared cursor)

When you no longer need a cursor you created by using the CreateIconIndirect function, you should destroy the cursor. The DestroyIcon function destroys the cursor handle and frees any memory the cursor used. Use this function only on cursors that were created with CreateIconIndirect.


Cursor Duplication

The CopyCursor function copies a cursor handle. This enables application or DLL code to retrieve the handle to a cursor owned by another module. Then, if the other module is freed, the module that copied the cursor will still be able to use the cursor design.

For information on how to add, remove, or replace cursor resources in executable files, see Resources.


Using Cursors

  • Creating a cursor
  • Displaying a cursor
  • Confining a cursor
  • Using cursor functions to create a mousetrap
  • Using the keyboard to move the cursor


Creating a Cursor

The following example creates two cursor handles: one for the standard hourglass cursor and one for a custom cursor included as a resource in the application's resource-definition file.

HINSTANCE hinst;            // handle to current instance
HCURSOR hCurs1, hCurs2;     // cursor handles

// Create a standard hourglass cursor.

hCurs1 = LoadCursor(NULL, IDC_WAIT);

// Create a custom cursor based on a resource.

hCurs2 = LoadCursor(hinst, MAKEINTRESOURCE(240));

You should implement custom cursors as resources. Rather than create the cursors at run time, use the LoadCursor, LoadCursorFromFile, or LoadImage function to avoid device dependence, to simplify localization, and to enable applications to share cursor designs.

The following example uses the CreateCursor function to create a custom cursor at run time. The example is included here to illustrate how the system interprets cursor bitmasks.

HINSTANCE hinst;            // handle to current instance
HCURSOR hCurs1, hCurs2;     // cursor handles

HCURSOR hCurs3;             // cursor handle

// Yin cursor AND bitmask

BYTE ANDmaskCursor[] =
{
    0xFF, 0xFC, 0x3F, 0xFF,   // line 1
    0xFF, 0xC0, 0x1F, 0xFF,   // line 2
    0xFF, 0x00, 0x3F, 0xFF,   // line 3
    0xFE, 0x00, 0xFF, 0xFF,   // line 4

    0xF7, 0x01, 0xFF, 0xFF,   // line 5
    0xF0, 0x03, 0xFF, 0xFF,   // line 6
    0xF0, 0x03, 0xFF, 0xFF,   // line 7
    0xE0, 0x07, 0xFF, 0xFF,   // line 8

    0xC0, 0x07, 0xFF, 0xFF,   // line 9
    0xC0, 0x0F, 0xFF, 0xFF,   // line 10
    0x80, 0x0F, 0xFF, 0xFF,   // line 11
    0x80, 0x0F, 0xFF, 0xFF,   // line 12

    0x80, 0x07, 0xFF, 0xFF,   // line 13
    0x00, 0x07, 0xFF, 0xFF,   // line 14
    0x00, 0x03, 0xFF, 0xFF,   // line 15
    0x00, 0x00, 0xFF, 0xFF,   // line 16

    0x00, 0x00, 0x7F, 0xFF,   // line 17
    0x00, 0x00, 0x1F, 0xFF,   // line 18
    0x00, 0x00, 0x0F, 0xFF,   // line 19
    0x80, 0x00, 0x0F, 0xFF,   // line 20

    0x80, 0x00, 0x07, 0xFF,   // line 21
    0x80, 0x00, 0x07, 0xFF,   // line 22
    0xC0, 0x00, 0x07, 0xFF,   // line 23
    0xC0, 0x00, 0x0F, 0xFF,   // line 24

    0xE0, 0x00, 0x0F, 0xFF,   // line 25
    0xF0, 0x00, 0x1F, 0xFF,   // line 26
    0xF0, 0x00, 0x1F, 0xFF,   // line 27
    0xF8, 0x00, 0x3F, 0xFF,   // line 28

    0xFE, 0x00, 0x7F, 0xFF,   // line 29
    0xFF, 0x00, 0xFF, 0xFF,   // line 30
    0xFF, 0xC3, 0xFF, 0xFF,   // line 31
    0xFF, 0xFF, 0xFF, 0xFF    // line 32
};

// Yin cursor XOR bitmask

BYTE XORmaskCursor[] =
{
    0x00, 0x00, 0x00, 0x00,   // line 1
    0x00, 0x03, 0xC0, 0x00,   // line 2
    0x00, 0x3F, 0x00, 0x00,   // line 3
    0x00, 0xFE, 0x00, 0x00,   // line 4

    0x0E, 0xFC, 0x00, 0x00,   // line 5
    0x07, 0xF8, 0x00, 0x00,   // line 6
    0x07, 0xF8, 0x00, 0x00,   // line 7
    0x0F, 0xF0, 0x00, 0x00,   // line 8

    0x1F, 0xF0, 0x00, 0x00,   // line 9
    0x1F, 0xE0, 0x00, 0x00,   // line 10
    0x3F, 0xE0, 0x00, 0x00,   // line 11
    0x3F, 0xE0, 0x00, 0x00,   // line 12

    0x3F, 0xF0, 0x00, 0x00,   // line 13
    0x7F, 0xF0, 0x00, 0x00,   // line 14
    0x7F, 0xF8, 0x00, 0x00,   // line 15
    0x7F, 0xFC, 0x00, 0x00,   // line 16

    0x7F, 0xFF, 0x00, 0x00,   // line 17
    0x7F, 0xFF, 0x80, 0x00,   // line 18
    0x7F, 0xFF, 0xE0, 0x00,   // line 19
    0x3F, 0xFF, 0xE0, 0x00,   // line 20

    0x3F, 0xC7, 0xF0, 0x00,   // line 21
    0x3F, 0x83, 0xF0, 0x00,   // line 22
    0x1F, 0x83, 0xF0, 0x00,   // line 23
    0x1F, 0x83, 0xE0, 0x00,   // line 24

    0x0F, 0xC7, 0xE0, 0x00,   // line 25
    0x07, 0xFF, 0xC0, 0x00,   // line 26
    0x07, 0xFF, 0xC0, 0x00,   // line 27
    0x01, 0xFF, 0x80, 0x00,   // line 28

    0x00, 0xFF, 0x00, 0x00,   // line 29
    0x00, 0x3C, 0x00, 0x00,   // line 30
    0x00, 0x00, 0x00, 0x00,   // line 31
    0x00, 0x00, 0x00, 0x00    // line 32
};

// Create a custom cursor at run time.

hCurs3 = CreateCursor( hinst,   // app instance
             19,                // horizontal position of hot spot
             2,                 // vertical position of hot spot
             32,                // cursor width
             32,                // cursor height
             ANDmaskCursor,     // AND bitmask
             XORmaskCursor );   // XOR bitmask

To create the cursor, CreateCursor applies the following truth table to the AND and XOR bitmasks.

AND bitmask | XOR bitmask | Display
0 | 0 | Black
0 | 1 | White
1 | 0 | Screen
1 | 1 | Reverse screen

For more information, see Bitmaps.

Before closing, you must use the DestroyCursor function to destroy any cursors you created with CreateCursor. It is not necessary to destroy cursors created by other functions.


Displaying a Cursor

The system automatically displays the class cursor (the cursor associated with the window to which the cursor is pointing). You can assign a class cursor while registering a window class. The following example illustrates this by assigning a cursor handle to the hCursor member of the WNDCLASS structure identified by the wc parameter.

WNDCLASS  wc;

// Fill the window class structure with parameters that
// describe the main window.

wc.style = NULL;                        // class style(s)
wc.lpfnWndProc = (WNDPROC) MainWndProc; // window procedure
wc.cbClsExtra = 0;           // no per-class extra data
wc.cbWndExtra = 0;           // no per-window extra data
wc.hInstance = hinst;        // application that owns the class
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);     // class icon
wc.hCursor = LoadCursor(hinst, MAKEINTRESOURCE(230)); // class cursor
wc.hbrBackground = GetStockObject(WHITE_BRUSH); // class background
wc.lpszMenuName =  "GenericMenu";               // class menu
wc.lpszClassName = "GenericWClass"              // class name

// Register the window class.

return RegisterClass(&wc);

When the window class is registered, the cursor identified by 230 in the application's resource-definition file will be the default cursor for all windows based on the class.

Your application can change the design of the cursor by using the SetCursor function and specifying a different cursor handle. However, when the cursor moves, the system redraws the class cursor at the new location. To prevent the class cursor from being redrawn, you must process the WM_SETCURSOR message. Each time the cursor moves and mouse input is not captured, the system sends this message to the window in which the cursor is moving.

You can specify different cursors for different conditions while processing WM_SETCURSOR. For example, the following example shows how to display the hCurs3 cursor whenever the cursor moves over the icon of a minimized application.

case WM_SETCURSOR:

    // If the window is minimized, draw the hCurs3 cursor.
    // If the window is not minimized, draw the default
    // cursor (class cursor).

    if (IsIconic(hwnd))
    {
        SetCursor(hCurs3);
        break;
    }

When the window is not minimized, the system displays the class cursor.

You can replace a class cursor by using the SetClassLong function. This function changes the default window settings for all windows of a given class. The following example replaces the existing class cursor with the hCurs2 cursor.

// Change the cursor for window class represented by hwnd.

SetClassLong(hwnd,    // window handle
    GCL_HCURSOR,      // change cursor
    (LONG) hCurs2);   // new cursor

For more information, see Window Classes and Mouse Input.


Confining a Cursor

The following example confines the cursor to the application's window and then restores the cursor to its previous window. The example uses the GetClipCursor function to record the area in which the cursor can move and the ClipCursor function to confine and restore the cursor.

RECT rcClip;           // new area for ClipCursor
RECT rcOldClip;        // previous area for ClipCursor

// Record the area in which the cursor can move.

GetClipCursor(&rcOldClip);

// Get the dimensions of the application's window.

GetWindowRect(hwnd, &rcClip);

// Confine the cursor to the application's window.

ClipCursor(&rcClip);

   //
   // Process input from the confined cursor.
   //

// Restore the cursor to its previous area.

ClipCursor(&rcOldClip);

Because there is only one cursor at a time available in the system, an application that confines the cursor must restore the cursor before relinquishing control to another window.


Using Cursor Functions to Create a Mousetrap

The following example uses the SetCursorPos, GetCursorPos, CreateCursor, LoadCursor, and SetCursor functions to create a simple mousetrap. It also uses cursor and timer functions to monitor the cursor's position every 10 seconds. If the cursor position has not changed in the last 10 seconds and the application's main window is minimized, the application changes the cursor and moves it to the mousetrap icon.

An example for a similar mousetrap is included in Icons. It uses the LoadCursor and LoadIcon functions instead of the more device-dependent CreateCursor and CreateIcon functions.

HICON hIcon1;               // icon handles
POINT ptOld;                // previous cursor location
HCURSOR hCurs1;             // cursor handle

// The following cursor bitmasks are defined in a code
// example that appears earlier in this topic.

// Yin cursor AND and XOR bitmasks

BYTE ANDmaskCursor[] = ...
BYTE XORmaskCursor[] = ...

// Yang icon AND bitmask

BYTE ANDmaskIcon[] = {0xFF, 0xFF, 0xFF, 0xFF,  // line 1
                      0xFF, 0xFF, 0xC3, 0xFF,  // line 2
                      0xFF, 0xFF, 0x00, 0xFF,  // line 3
                      0xFF, 0xFE, 0x00, 0x7F,  // line 4

                      0xFF, 0xFC, 0x00, 0x1F,  // line 5
                      0xFF, 0xF8, 0x00, 0x0F,  // line 6
                      0xFF, 0xF8, 0x00, 0x0F,  // line 7
                      0xFF, 0xF0, 0x00, 0x07,  // line 8

                      0xFF, 0xF0, 0x00, 0x03,  // line 9
                      0xFF, 0xE0, 0x00, 0x03,  // line 10
                      0xFF, 0xE0, 0x00, 0x01,  // line 11
                      0xFF, 0xE0, 0x00, 0x01,  // line 12

                      0xFF, 0xF0, 0x00, 0x01,  // line 13
                      0xFF, 0xF0, 0x00, 0x00,  // line 14
                      0xFF, 0xF8, 0x00, 0x00,  // line 15
                      0xFF, 0xFC, 0x00, 0x00,  // line 16

                      0xFF, 0xFF, 0x00, 0x00,  // line 17
                      0xFF, 0xFF, 0x80, 0x00,  // line 18
                      0xFF, 0xFF, 0xE0, 0x00,  // line 19
                      0xFF, 0xFF, 0xE0, 0x01,  // line 20

                      0xFF, 0xFF, 0xF0, 0x01,  // line 21
                      0xFF, 0xFF, 0xF0, 0x01,  // line 22
                      0xFF, 0xFF, 0xF0, 0x03,  // line 23
                      0xFF, 0xFF, 0xE0, 0x03,  // line 24

                      0xFF, 0xFF, 0xE0, 0x07,  // line 25
                      0xFF, 0xFF, 0xC0, 0x0F,  // line 26
                      0xFF, 0xFF, 0xC0, 0x0F,  // line 27
                      0xFF, 0xFF, 0x80, 0x1F,  // line 28

                      0xFF, 0xFF, 0x00, 0x7F,  // line 29
                      0xFF, 0xFC, 0x00, 0xFF,  // line 30
                      0xFF, 0xF8, 0x03, 0xFF,  // line 31
                      0xFF, 0xFC, 0x3F, 0xFF}; // line 32

// Yang icon XOR bitmask

BYTE XORmaskIcon[] = {0x00, 0x00, 0x00, 0x00,  // line 1
                      0x00, 0x00, 0x00, 0x00,  // line 2
                      0x00, 0x00, 0x00, 0x00,  // line 3
                      0x00, 0x00, 0x00, 0x00,  // line 4

                      0x00, 0x00, 0x00, 0x00,  // line 5
                      0x00, 0x00, 0x00, 0x00,  // line 6
                      0x00, 0x00, 0x00, 0x00,  // line 7
                      0x00, 0x00, 0x38, 0x00,  // line 8

                      0x00, 0x00, 0x7C, 0x00,  // line 9
                      0x00, 0x00, 0x7C, 0x00,  // line 10
                      0x00, 0x00, 0x7C, 0x00,  // line 11
                      0x00, 0x00, 0x38, 0x00,  // line 12

                      0x00, 0x00, 0x00, 0x00,  // line 13
                      0x00, 0x00, 0x00, 0x00,  // line 14
                      0x00, 0x00, 0x00, 0x00,  // line 15
                      0x00, 0x00, 0x00, 0x00,  // line 16

                      0x00, 0x00, 0x00, 0x00,  // line 17
                      0x00, 0x00, 0x00, 0x00,  // line 18
                      0x00, 0x00, 0x00, 0x00,  // line 19
                      0x00, 0x00, 0x00, 0x00,  // line 20

                      0x00, 0x00, 0x00, 0x00,  // line 21
                      0x00, 0x00, 0x00, 0x00,  // line 22
                      0x00, 0x00, 0x00, 0x00,  // line 23
                      0x00, 0x00, 0x00, 0x00,  // line 24

                      0x00, 0x00, 0x00, 0x00,  // line 25
                      0x00, 0x00, 0x00, 0x00,  // line 26
                      0x00, 0x00, 0x00, 0x00,  // line 27
                      0x00, 0x00, 0x00, 0x00,  // line 28

                      0x00, 0x00, 0x00, 0x00,  // line 29
                      0x00, 0x00, 0x00, 0x00,  // line 30
                      0x00, 0x00, 0x00, 0x00,  // line 31
                      0x00, 0x00, 0x00, 0x00}; // line 32

hIcon1 = CreateIcon(hinst, // handle to app instance
             32,           // icon width
             32,           // icon height
             1,            // number of XOR planes
             1,            // number of bits per pixel
             ANDmaskIcon,  // AND bitmask
             XORmaskIcon); // XOR bitmask

hCurs1 = CreateCursor(hinst, // handle to app instance
             19,         // horizontal position of hot spot
             2,          // vertical position of hot spot
             32,         // cursor width
             32,         // cursor height
             ANDmaskCursor,            // AND bitmask
             XORmaskCursor);           // XOR bitmask

// Fill in the window class structure.

WNDCLASS  wc;

wc.hIcon = hIcon1;                        // class icon
wc.hCursor = LoadCursor(NULL, IDC_ARROW); // class cursor

//
// Register the window class and perform
// other application initialization.
//

// Set a timer for the mousetrap.

GetCursorPos(&ptOld);

SetTimer(hwnd, IDT_CURSOR, 10000, (TIMERPROC) NULL);

LONG APIENTRY MainWndProc(
    HWND hwnd,          // window handle
    UINT message,       // type of message
    UINT wParam,        // additional information
    LONG lParam)        // additional information
{

    HDC hdc;            // handle to device context
    POINT pt;           // current cursor location
    RECT rc;            // iconized window location

    switch (message)
    {
        //
        // Process other messages.
        //

        case WM_TIMER:
        // If the window is minimized, compare the
        // current cursor position with the one 10
        // seconds before. If the cursor position has
        // not changed, move the cursor to the icon.

            if (IsIconic(hwnd))
            {
                GetCursorPos(&pt);

                if ((pt.x == ptOld.x) && (pt.y == ptOld.y))
                {
                    GetWindowRect(hwnd, &rc);
                    SetCursorPos(rc.left + 20, rc.top + 4);

                    // Note that the additional constants
                    // (20 and 4) are application-specific
                    // values to align the yin-shaped cursor
                    // and the yang-shaped icon.

                }
                else
                {
                    ptOld.x = pt.x;
                    ptOld.y = pt.y;
                }
            }

            return 0;

        case WM_SETCURSOR:
        // If the window is minimized, draw hCurs1.
        // If the window is not minimized, draw the
        // default cursor (class cursor).

            if (IsIconic(hwnd))
            {
                SetCursor(hCurs1);
                break;
            }

        case WM_DESTROY:
        // Destroy timer.

            KillTimer(hwnd, IDT_CURSOR);

            PostQuitMessage(0);
            break;
    }
}


Using the Keyboard to Move the Cursor

Because the system does not require a mouse, an application should be able to simulate mouse actions with the keyboard. The following example shows how to achieve this, by using the GetCursorPos and SetCursorPos functions, and by processing input from the arrow keys.

HCURSOR hCurs1, hCurs2;    // cursor handles

POINT pt;                  // cursor location
RECT rc;                   // client area coordinates
static int repeat = 1;     // repeat key counter

//
// Other declarations and initialization.
//

switch (message)
{
//
// Process other messages.
//

    case WM_KEYDOWN:

        if (wParam != VK_LEFT && wParam != VK_RIGHT &&
        wParam != VK_UP && wParam != VK_DOWN)
        {
            break;
        }

        GetCursorPos(&pt);

        // Convert screen coordinates to client coordinates.

        ScreenToClient(hwnd, &pt);

        switch (wParam)
        {
        // Move the cursor to reflect which
        // arrow keys are pressed.

            case VK_LEFT:               // left arrow
                pt.x -= repeat;
                break;

            case VK_RIGHT:              // right arrow
                pt.x += repeat;
                break;

            case VK_UP:                 // up arrow
                pt.y -= repeat;
                break;

            case VK_DOWN:               // down arrow
                pt.y += repeat;
                break;

            default:
                return NULL;

        }

        repeat++;           // increment repeat count

        // Keep the cursor in the client area.

        GetClientRect(hwnd, &rc);

        if (pt.x >= rc.right)
        {
            pt.x = rc.right - 1;
        }
        else
        {
            if (pt.x < rc.left)
            {
                pt.x = rc.left;
            }
        }

        if (pt.y >= rc.bottom)
            pt.y = rc.bottom - 1;
        else
            if (pt.y < rc.top)
                pt.y = rc.top;

        // Convert client coordinates to screen coordinates.

        ClientToScreen(hwnd, &pt);
        SetCursorPos(pt.x, pt.y);
        break;

    case WM_KEYUP:

        repeat = 1;            // clear repeat count
        break;

}


Cursor Reference

The following elements are associated with cursors.

  • Cursor Functions
  • Cursor Messages


Cursor Functions

The following functions are used with cursors.

ClipCursor
CopyCursor
CreateCursor
DestroyCursor
GetClipCursor
GetCursor
GetCursorPos
LoadCursorFromFile
SetCursor
SetCursorPos
SetSystemCursor
ShowCursor

Obsolete Functions

LoadCursor


ClipCursor

The ClipCursor function confines the cursor to a rectangular area on the screen. If a subsequent cursor position (set by the SetCursorPos function or the mouse) lies outside the rectangle, the system automatically adjusts the position to keep the cursor inside the rectangular area.

BOOL ClipCursor(
  CONST RECT *lpRect   // pointer to structure with rectangle
);

Parameters

lprc
Pointer to the RECT structure that contains the screen coordinates of the upper-left and lower-right corners of the confining rectangle. If this parameter is NULL, the cursor is free to move anywhere on the screen.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The cursor is a shared resource. If an application confines the cursor, it must release the cursor by using ClipCursor before relinquishing control to another application.

The calling process must have WINSTA_WRITEATTRIBUTES access to the window station.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Cursors Overview, Cursor Functions, GetClipCursor, GetCursorPos, RECT, SetCursorPos


CopyCursor

The CopyCursor function copies a cursor.

HCURSOR CopyCursor(
  HCURSOR pcur   // handle to cursor to copy
);

Parameters

pcur
Handle to the cursor to be copied.

Return Values

If the function succeeds, the return value is the handle to the duplicate cursor.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The CopyCursor function enables an application or dynamic-link library (DLL) to obtain the handle to a cursor shape owned by another module. Then if the other module is freed, the application is still able to use the cursor shape.

Before closing, an application must call the DestroyCursor function to free any system resources associated with the cursor.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Cursors Overview, Cursor Functions, CopyIcon, DestroyCursor, GetCursor, SetCursor, ShowCursor


CreateCursor

The CreateCursor function creates a cursor having the specified size, bit patterns, and hot spot.

HCURSOR CreateCursor(
  HINSTANCE hInst,         // handle to application instance
  int xHotSpot,            // horizontal position of hot spot
  int yHotSpot,            // vertical position of hot spot
  int nWidth,              // cursor width
  int nHeight,             // cursor height
  CONST VOID *pvANDPlane,  // pointer to AND bitmask array
  CONST VOID *pvXORPlane   // pointer to XOR bitmask array
);

Parameters

hInst
Handle to the current instance of the application creating the cursor.
xHotSpot
Specifies the horizontal position of the cursor's hot spot.
yHotSpot
Specifies the vertical position of the cursor's hot spot.
nWidth
Specifies the width, in pixels, of the cursor.
nHeight
Specifies the height, in pixels, of the cursor.
pvANDplane
Pointer to an array of bytes that contains the bit values for the AND bitmask of the cursor, as in a device-dependent monochrome bitmap.
pvXORplane
Pointer to an array of bytes that contains the bit values for the XOR bitmask of the cursor, as in a device-dependent monochrome bitmap.

Return Values

If the function succeeds, the return value identifies the cursor.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The nWidth and nHeight parameters must specify a width and height that are supported by the current display driver, because the system cannot create cursors of other sizes. To determine the width and height supported by the display driver, use the GetSystemMetrics function, specifying the SM_CXCURSOR or SM_CYCURSOR value.

Before closing, an application must call the DestroyCursor function to free any system resources associated with the cursor.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Cursors Overview, Cursor Functions, CreateIcon, DestroyCursor, GetModuleHandle, GetSystemMetrics, SetCursor


DestroyCursor

The DestroyCursor function destroys a cursor and frees any memory the cursor occupied. Do not use this function to destroy a shared cursor.

BOOL DestroyCursor(
  HCURSOR hCursor   // handle to cursor to destroy
);

Parameters

hCursor
Handle to the cursor to be destroyed. The cursor must not be in use.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The DestroyCursor function destroys a non-shared cursor. Do not use this function to destroy a shared cursor. A shared cursor is valid as long as the module from which it was loaded remains in memory. The following functions obtain a shared cursor:

  • LoadCursor
  • LoadCursorFromFile
  • LoadImage (if you use the LR_SHARED flag)
  • CopyImage (if you use the LR_COPYRETURNORG flag and the hImage parameter is a shared cursor)

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Cursors Overview, Cursor Functions, CopyCursor, CopyImage, CreateCursor, LoadCursor, LoadCursorFromFile, LoadImage


GetClipCursor

The GetClipCursor function retrieves the screen coordinates of the rectangular area to which the cursor is confined.

BOOL GetClipCursor(
  LPRECT lpRect   // address of structure for rectangle
);

Parameters

lpRect
Pointer to a RECT structure that receives the screen coordinates of the confining rectangle. The structure receives the dimensions of the screen if the cursor is not confined to a rectangle.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The cursor is a shared resource. If an application confines the cursor with the ClipCursor function, it must later release the cursor by using ClipCursor before relinquishing control to another application.

The calling process must have WINSTA_READATTRIBUTES access to the window station.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Cursors Overview, Cursor Functions, ClipCursor, GetCursorPos, RECT


GetCursor

The GetCursor function retrieves the handle to the current cursor.

HCURSOR GetCursor(VOID)

Parameters

This function has no parameters.

Return Values

The return value is the handle to the current cursor. If there is no cursor, the return value is NULL.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Cursors Overview, Cursor Functions, SetCursor


GetCursorPos

The GetCursorPos function retrieves the cursor's position, in screen coordinates.

BOOL GetCursorPos(
  LPPOINT lpPoint   // address of structure for cursor position
);

Parameters

lpPoint
Pointer to a POINT structure that receives the screen coordinates of the cursor.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The cursor position is always given in screen coordinates and is not affected by the mapping mode of the window that contains the cursor.

The calling process must have WINSTA_READATTRIBUTES access to the window station.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Cursors Overview, Cursor Functions, ClipCursor, POINT, SetCursor, SetCursorPos, ShowCursor


LoadCursor

The LoadCursor function loads the specified cursor resource from the executable (.EXE) file associated with an application instance.

This function has been superseded by the LoadImage function

HCURSOR LoadCursor(
  HINSTANCE hInstance,  // handle to application instance
  LPCTSTR lpCursorName  // name string or cursor resource identifier
);

Parameters

hInstance
Handle to an instance of the module whose executable file contains the cursor to be loaded.
lpCursorName
Pointer to a null-terminated string that contains the name of the cursor resource to be loaded. Alternatively, this parameter can consist of the resource identifier in the low-order word and zero in the high-order word. The MAKEINTRESOURCE macro can also be used to create this value.

To use one of the Win32 predefined cursors, the application must set the hInstance parameter to NULL and the lpCursorName parameter to one the following values:
Value | Description
IDC_APPSTARTING | Standard arrow and small hourglass
IDC_ARROW | Standard arrow
IDC_CROSS | Crosshair
IDC_HAND | Windows NT 5.0 and later: Hand
IDC_HELP | Arrow and question mark
IDC_IBEAM | I-beam
IDC_ICON | Obsolete for applications marked version 4.0 or later.
IDC_NO | Slashed circle
IDC_SIZE | Obsolete for applications marked version 4.0 or later. Use IDC_SIZEALL.
IDC_SIZEALL | Four-pointed arrow pointing north, south, east, and west
IDC_SIZENESW | Double-pointed arrow pointing northeast and southwest
IDC_SIZENS | Double-pointed arrow pointing north and south
IDC_SIZENWSE | Double-pointed arrow pointing northwest and southeast
IDC_SIZEWE | Double-pointed arrow pointing west and east
IDC_UPARROW | Vertical arrow
IDC_WAIT | Hourglass

Return Values

If the function succeeds, the return value is the handle to the newly loaded cursor.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The LoadCursor function loads the cursor resource only if it has not been loaded; otherwise, it retrieves the handle to the existing resource. This function returns a valid cursor handle only if the lpCursorName parameter points to a cursor resource. If lpCursorName points to any type of resource other than a cursor (such as an icon), the return value is not NULL, even though it is not a valid cursor handle.

The LoadCursor function searches the cursor resource most appropriate for the cursor for the current display device. The cursor resource can be a color or monochrome bitmap.

Windows CE: Use the cursor component when targeting a platform that does not support mouse cursors. The only cursor this component supports is the wait cursor (IDC_WAIT). Use the LoadCursor function in conjunction with the SetCursor function to set the wait cursor.

SetCursor(LoadCursor(NULL, IDC_WAIT));

Use the mcursor component when targeting a platform that does support mouse cursors. This component supports the LoadCursor function the same way Windows desktop platforms do, except that it only supports monochrome cursors. Windows CE does not support color cursors. An attempt to load a color cursor will have unpredictable results.

See Also

Cursors Overview, Cursor Functions, LoadImage, MAKEINTRESOURCE, SetCursor, SetCursorPos, ShowCursor


LoadCursorFromFile

The LoadCursorFromFile function creates a cursor based on data contained in a file. The file is specified by its name or by a system cursor identifier. The function returns a handle to the newly created cursor. Files containing cursor data may be in either cursor (.CUR) or animated cursor (.ANI) format.

HCURSOR LoadCursorFromFile(
  LPCTSTR lpFileName  // pointer to name of cursor file, or system
                      // cursor identifier
);

Parameters

lpFileName
Indicates the source of the file data to be used to create the cursor. The data in the file must be in either .CUR or .ANI format.

If the high-order word of lpszFileName is nonzero, it is a pointer to a string that is a fully qualified name of a file containing cursor data.

If the high-order word of lpszFileName is zero, the low-order word is a system cursor identifier. The function then searches the [Cursors] entry in the WIN.INI file for the file associated with the name of that system cursor. Here is a list of system cursor names and identifiers:
System Cursor Name | System Cursor Identifier
"AppStarting" | OCR_APPSTARTING
"Arrow" | OCR_NORMAL
"Crosshair" | OCR_CROSS
"Hand" | Windows NT 5.0 and later: OCR_HAND
"Help" | OCR_HELP
"IBeam" | OCR_IBEAM
"Icon" | OCR_ICON
"No" | OCR_NO
"Size" | OCR_SIZE
"SizeAll" | OCR_SIZEALL
"SizeNESW" | OCR_SIZENESW
"SizeNS" | OCR_SIZENS
"SizeNWSE" | OCR_SIZENWSE
"SizeWE" | OCR_SIZEWE
"UpArrow" | OCR_UP
"Wait" | OCR_WAIT

For example, if the WIN.INI file contains the following :

[Cursors]
    Arrow = "arrow.ani"

Then the call

LoadCursorFromFile((LPWSTR)OCR_NORMAL)

causes the LoadCursorFromFile function to obtain cursor data from the file ARROW.ANI. If the WIN.INI file doesn't contain an entry for the specified system cursor, the function fails and returns NULL.

Return Values

If the function is successful, the return value is a handle to the new cursor.

If the function fails, the return value is NULL. To get extended error information, call GetLastError. GetLastError may return the following value:

Value | Meaning
ERROR_FILE_NOT_FOUND | The specified file could not be found.

QuickInfo

Windows NT: Requires version 3.5 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Cursors Overview, Cursor Functions, LoadCursor, SetCursor, SetSystemCursor


SetCursor

The SetCursor function establishes the cursor shape.

HCURSOR SetCursor(
  HCURSOR hCursor   // handle to cursor
);

Parameters

hCursor
Handle to the cursor. The cursor must have been created by the CreateCursor or loaded by the LoadCursor or LoadImage function. If this parameter is NULL, the cursor is removed from the screen.

Windows 95: The width and height of the cursor must be the values returned by the GetSystemMetrics function for SM_CXCURSOR and SM_CYCURSOR. In addition, the cursor bit depth must match the bit depth of the display or the cursor must be monochrome.

Return Values

The return value is the handle to the previous cursor, if there was one.

If there was no previous cursor, the return value is NULL.

Remarks

The cursor is set only if the new cursor is different from the previous cursor; otherwise, the function returns immediately.

The cursor is a shared resource. A window should set the cursor shape only when the cursor is in its client area or when the window is capturing mouse input. In systems without a mouse, the window should restore the previous cursor before the cursor leaves the client area or before it relinquishes control to another window.

If your application must set the cursor while it is in a window, make sure the class cursor for the specified window's class is set to NULL. If the class cursor is not NULL, the system restores the class cursor each time the mouse is moved.

The cursor is not shown on the screen if the internal cursor display count is less than zero. This occurs if the application uses the ShowCursor function to hide the cursor more times than to show the cursor.

Windows CE: Use the cursor component when targeting a platform that does not support mouse cursors. The only cursor this component supports is the wait cursor. Use the following code to set the wait cursor:

SetCursor(LoadCursor(NULL, IDC_WAIT));

Use the mcursor component when targeting a platform that does support mouse cursors. This component does not support color cursors.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Cursors Overview, Cursor Functions, CreateCursor, GetCursor, GetSystemMetrics, LoadCursor, LoadImage, SetCursorPos, ShowCursor


SetCursorPos

The SetCursorPos function moves the cursor to the specified screen coordinates. If the new coordinates are not within the screen rectangle set by the most recent ClipCursor function, the system automatically adjusts the coordinates so that the cursor stays within the rectangle.

BOOL SetCursorPos(
  int X,  // horizontal position
  int Y   // vertical position
);

Parameters

X
Specifies the new x-coordinate, in screen coordinates, of the cursor.
Y
Specifies the new y-coordinate, in screen coordinates, of the cursor.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The cursor is a shared resource. A window should move the cursor only when the cursor is in its client area.

The calling process must have WINSTA_WRITEATTRIBUTES access to the window station.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Cursors Overview, Cursor Functions, ClipCursor, GetCursorPos, SetCaretPos, SetCursor, ShowCursor


SetSystemCursor

The SetSystemCursor function enables an application to customize the system cursors. It replaces the contents of the system cursor specified by id with the contents of the cursor specified by hcur, and then destroys hcur.

BOOL SetSystemCursor (
  HCURSOR hcur,  // cursor to be set as a system cursor
  DWORD id       // identifier of the system cursor to replace
);

Parameters

hcur
Handle to a cursor. The function replaces the contents of the system cursor specified by id with the contents of the cursor handled by hcur.

The system destroys hcur by calling the DestroyCursor function. Therefore, hcur cannot be a cursor loaded using the LoadCursor function. To specify a cursor loaded from a resource, copy the cursor using the CopyCursor function, then pass the copy to SetSystemCursor.

id
Specifies the system cursor to replace with the contents of hcur.

Following is a list of system cursor identifiers:
Value | Description
OCR_APPSTARTING | Standard arrow and small hourglass
OCR_NORMAL | Standard arrow
OCR_CROSS | Crosshair
OCR_HAND | Windows NT 5.0 and later: Hand
OCR_HELP | Arrow and question mark
OCR_IBEAM | I-beam
OCR_NO | Slashed circle
OCR_SIZEALL | Four-pointed arrow pointing north, south, east, and west
OCR_SIZENESW | Double-pointed arrow pointing northeast and southwest
OCR_SIZENS | Double-pointed arrow pointing north and south
OCR_SIZENWSE | Double-pointed arrow pointing northwest and southeast
OCR_SIZEWE | Double-pointed arrow pointing west and east
OCR_UP | Vertical arrow
OCR_WAIT | Hourglass

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

QuickInfo

Windows NT: Requires version 3.5 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Cursors Overview, Cursor Functions, DestroyCursor, LoadCursor, LoadCursorFromFile, SetCursor


ShowCursor

The ShowCursor function displays or hides the cursor.

int ShowCursor(
  BOOL bShow   // cursor visibility flag
);

Parameters

bShow
Specifies whether the internal display counter is to be incremented or decremented. If bShow is TRUE, the display count is incremented by one. If bShow is FALSE, the display count is decremented by one.

Return Values

The return value specifies the new display counter.

Remarks

This function sets an internal display counter that determines whether the cursor should be displayed. The cursor is displayed only if the display count is greater than or equal to 0. If a mouse is installed, the initial display count is 0. If no mouse is installed, the display count is –1.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Cursors Overview, Cursor Functions, ClipCursor, GetCursorPos, SetCursor, SetCursorPos


Cursor Messages

The following message is used with cursors.

WM_SETCURSOR


WM_SETCURSOR

The WM_SETCURSOR message is sent to a window if the mouse causes the cursor to move within a window and mouse input is not captured.

WM_SETCURSOR
hwnd = (HWND) wParam;       // handle to window with cursor
nHittest = LOWORD(lParam);  // hit-test code
wMouseMsg = HIWORD(lParam); // mouse-message identifier

Parameters

hwnd
Value of wParam. Handle to the window that contains the cursor.
nHittest
Value of the low-order word of lParam. Specifies the hit-test code.
wMouseMsg
Value of the high-order word of lParam. Specifies the identifier of the mouse message.

Default Action

The DefWindowProc function passes the WM_SETCURSOR message to a parent window before processing. If the parent window returns TRUE, further processing is halted. Passing the message to a window's parent window gives the parent window control over the cursor's setting in a child window. The DefWindowProc function also uses this message to set the cursor to an arrow if it is not in the client area, or to the registered class cursor if it is in the client area. If the low-order word of the lParam parameter is HTERROR and the high-order word of lParam specifies that one of the mouse buttons is pressed, DefWindowProc calls the MessageBeep function.

Remarks

The high-order word of lParam is zero when the window enters menu mode.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Cursors Overview, Cursor Messages, DefWindowProc, MessageBeep


Icons

An icon is a picture that consists of a bitmap image combined with a mask to create transparent areas in the picture. The term icon can refer to either of the following:

  • A single icon image. This is a resource of type RT_ICON.
  • A group of images, from which the system or an application can choose the most appropriate icon based on size and color depth. This is a resource of type RT_GROUP_ICON.

This overview describes creating, displaying, destroying, and duplicating icons.


About Icons

The system uses icons throughout the user interface to represent objects such as files, folders, shortcuts, applications, and documents. The icon functions provided by the Win32 API enable applications to create, load, display, arrange, and destroy icons.

For information on specifying icons for file types, see IExtractIcon.


Icon Hot Spot

One of the pixels in an icon is designated as the hot spot, which is the point the system tracks and recognizes as the position of the icon. An icon's hot spot is typically the pixel located at the center of the icon. If you use the CreateIconIndirect function to create an icon, you can specify any pixel to be the hot spot.


Icon Types

The operating system provides a set of standard icons that are available for any application to use at any time. The SDK header files contain identifiers for the standard icons — the identifiers begin with the "IDI_" prefix.

Each standard icon has a corresponding default image associated with it. The user can replace the default image associated with any standard cursor at any time.

Custom icons are designed for use in a particular application and can be any design. Following are several custom icons.


Icon Sizes

The system uses four icon sizes: system small, system large, shell small, and shell large.

The system small icon is displayed in the window caption. To change the size of the system small icon, start the Display control panel applet, click the Appearance tab, select Caption Buttons from the Item list, then set the Size field. To retrieve the size of the system small icon, call the GetSystemMetrics function with SM_CXSMICON and SM_CYSMICON.

The system large icon is mainly used by applications, but it is also displayed in the Alt+Tab dialog. The CreateIconFromResource, DrawIcon, ExtractAssociatedIcon, ExtractIcon, ExtractIconEx, and LoadIcon functions all use system large icons. The size of the system large icon is defined by the video driver, therefore it cannot be changed. You can retrieve the size of the system large icon by calling GetSystemMetrics with SM_CXICON and SM_CYICON.

The CreateIcon, CreateIconFromResourceEx, CreateIconIndirect, and SHGetFileInfo functions can be used to work with icons in sizes other than system large.

The shell small icon is used in the Windows Explorer and the common dialogs. Currently, this defaults to the system small size. To retrieve the size of the shell small icon, use the SHGetFileInfo function with SHGFI_SHELLICONSIZE | SHGFI_SMALLICON to retrieve a handle to the system image list, then the ImageList_GetIconSize function to get the icon size.

The shell large icon is used on the desktop. To change the size of the large icon, start the Display control panel applet, click the Appearance tab, select Icon from the Item list, then set the Size field (this size is stored in the registry, under HKEY_CURRENT_USER\Control Panel, Desktop\WindowMetrics\Shell Icon Size). You must also click the Plus! tab and select the Use large icons check box. To retrieve the size of the shell large icon, use the SHGetFileInfo function with SHGFI_SHELLICONSIZE to retrieve a handle to the system image list, then the ImageList_GetIconSize function to get the icon size.

The Start menu uses either shell small icons or shell large icons, depending on whether the Use large icons check box is selected.

Your application should supply groups of icon images in the following sizes:

  • 48x48, 256 color
  • 32x32, 16 color
  • 16x16 pixels, 16 color

When filling in the WNDCLASSEX structure to be used in registering your window class, set the hIcon member to the 32x32 icon and the hIconSm member to the 16x16 icon. For more information about class icons, see Class Icons.


Icon Creation

Standard icons are predefined, so it is not necessary to create them. To use a standard icon, an application can obtain its handle by using the LoadImage function. An icon handle is a unique value of the HICON type that identifies a standard or custom icon.

To create a custom icon for an application, you would typically use a graphics application and include the ICON resource in the application's resource-definition file. At run time, you can call LoadIcon or LoadImage to retrieve a handle to the icon. An icon resource can contain a group images for several different display devices. LoadIcon and LoadImage automatically select the most appropriate icon from the group for the current display device.

An application can also create a custom icon at run time by using the CreateIconIndirect function, which creates an icon based on the contents of an ICONINFO structure. The GetIconInfo function fills the structure with the hot spot coordinates and information about the bitmask bitmap and color bitmap for the icon.

Applications should implement custom icons as resources and should use LoadIcon or LoadImage, rather than create the icon at run time. Using icon resources avoids device dependence, simplifies localization, and enables applications to share icon shapes.

The CreateIconFromResourceEx function enables an application to browse through the system's resources and create icons and cursors based on resource data. CreateIconFromResourceEx creates an icon based on binary resource data from other executable files or dynamic-link libraries (DLLs). An application must precede this function with calls to the LookupIconIdFromDirectoryEx function and several of the resource functions. LookupIconIdFromDirectoryEx returns the identifier of the most appropriate icon data for the current display device. For more information about the resource functions, see Resource Functions.


Icon Display

You can retrieve the image for an icon by using the GetIconInfo function, and can draw it by using the DrawIconEx function. To draw the default image for a icon, specify the DI_COMPAT flag in the call to DrawIconEx. If you do not specify the DI_COMPAT flag, DrawIconEx draws the icon using the image that the user specified.

When the system displays an icon, it must extract the appropriate icon image from the .EXE or .DLL file. The system uses the following steps to select the icon image:

  1. Select the RT_GROUP_ICON resource. If more than one such resource exists, Windows NT uses the first resource listed in the resource script, while Windows 95 chooses the first resource listed in alphabetical order.
  2. Select the appropriate RT_ICON image from the RT_GROUP_ICON resource. If more than one image exists, the system uses the following criteria to choose an image:
    • The image closest in size to the requested size is chosen.
    • If two or more images of that size are present, the one that matches the color depth of the display is chosen.
    • If no images exactly match the color depth of the display, the image with the greatest color depth that does not exceed the color depth of the display is chosen. If all exceed the color depth, the one with the lowest color depth is chosen.

Note The system treats all color depths of 8 or more bpp as equal. Therefore, there is no advantage of including a 16x16 256 color image and a 16x16 16 color image in the same resource — the system will simply choose the first one it encounters. When the display is in 8 bpp mode, the system will choose a 16 color icon over a 256 color icon, and will display all icons using the system default palette.


Icon Destruction

When an application no longer needs an icon it created by using the CreateIconIndirect function, it should destroy the icon. The DestroyIcon function destroys the icon handle and frees any memory used by the icon. Applications should use this function only for icons created with CreateIconIndirect; it is not necessary to destroy other icons.


Icon Duplication

The CopyIcon function copies an icon handle. This enables an application or DLL to get its own handle for an icon owned by another module. Then, if the other module is freed, the application that copied the icon will still be able to use the icon.

The CopyImage function creates a new icon based on the specified source icon. The new icon can be larger or smaller than the source icon.

For information about adding, removing, or replacing icon resources in executable (.EXE) files, see Resources.


Using Icons

This following topics describe how to perform certain tasks related to icons:

  • Creating an icon
  • Displaying an icon
  • Sharing icon resources


Creating an Icon

To use an icon, your application must get a handle to the icon. The following example shows how to create two different icon handles: one for the standard exclamation icon and one for a custom icon included as a resource in the application's resource-definition file.

HICON hIcon1;   // icon handle
HICON hIcon2;   // icon handle

// Create a standard question icon.

hIcon1 = LoadIcon(NULL, IDI_QUESTION);

// Create a custom icon based on a resource.

hIcon2 = LoadIcon(hinst, MAKEINTRESOURCE(460));

// Create a custom icon at run time.

An application should implement custom icons as resources and should use the LoadIcon or LoadImage function, rather than create the icons at run time. This approach avoids device dependence, simplifies localization, and enables applications to share icon bitmaps. However, the following example uses CreateIcon to create a custom icon at run time, based on bitmap bitmasks; it is included to illustrate how the system interprets icon bitmap bitmasks.

HICON hIcon3;      // icon handle

// Yang icon AND bitmask

BYTE ANDmaskIcon[] = {0xFF, 0xFF, 0xFF, 0xFF,   // line 1
                      0xFF, 0xFF, 0xC3, 0xFF,   // line 2
                      0xFF, 0xFF, 0x00, 0xFF,   // line 3
                      0xFF, 0xFE, 0x00, 0x7F,   // line 4

                      0xFF, 0xFC, 0x00, 0x1F,   // line 5
                      0xFF, 0xF8, 0x00, 0x0F,   // line 6
                      0xFF, 0xF8, 0x00, 0x0F,   // line 7
                      0xFF, 0xF0, 0x00, 0x07,   // line 8

                      0xFF, 0xF0, 0x00, 0x03,   // line 9
                      0xFF, 0xE0, 0x00, 0x03,   // line 10
                      0xFF, 0xE0, 0x00, 0x01,   // line 11
                      0xFF, 0xE0, 0x00, 0x01,   // line 12

                      0xFF, 0xF0, 0x00, 0x01,   // line 13
                      0xFF, 0xF0, 0x00, 0x00,   // line 14
                      0xFF, 0xF8, 0x00, 0x00,   // line 15
                      0xFF, 0xFC, 0x00, 0x00,   // line 16

                      0xFF, 0xFF, 0x00, 0x00,   // line 17
                      0xFF, 0xFF, 0x80, 0x00,   // line 18
                      0xFF, 0xFF, 0xE0, 0x00,   // line 19
                      0xFF, 0xFF, 0xE0, 0x01,   // line 20

                      0xFF, 0xFF, 0xF0, 0x01,   // line 21
                      0xFF, 0xFF, 0xF0, 0x01,   // line 22
                      0xFF, 0xFF, 0xF0, 0x03,   // line 23
                      0xFF, 0xFF, 0xE0, 0x03,   // line 24

                      0xFF, 0xFF, 0xE0, 0x07,   // line 25
                      0xFF, 0xFF, 0xC0, 0x0F,   // line 26
                      0xFF, 0xFF, 0xC0, 0x0F,   // line 27
                      0xFF, 0xFF, 0x80, 0x1F,   // line 28

                      0xFF, 0xFF, 0x00, 0x7F,   // line 29
                      0xFF, 0xFC, 0x00, 0xFF,   // line 30
                      0xFF, 0xF8, 0x03, 0xFF,   // line 31
                      0xFF, 0xFC, 0x3F, 0xFF};  // line 32

// Yang icon XOR bitmask

BYTE XORmaskIcon[] = {0x00, 0x00, 0x00, 0x00,   // line 1
                      0x00, 0x00, 0x00, 0x00,   // line 2
                      0x00, 0x00, 0x00, 0x00,   // line 3
                      0x00, 0x00, 0x00, 0x00,   // line 4

                      0x00, 0x00, 0x00, 0x00,   // line 5
                      0x00, 0x00, 0x00, 0x00,   // line 6
                      0x00, 0x00, 0x00, 0x00,   // line 7
                      0x00, 0x00, 0x38, 0x00,   // line 8

                      0x00, 0x00, 0x7C, 0x00,   // line 9
                      0x00, 0x00, 0x7C, 0x00,   // line 10
                      0x00, 0x00, 0x7C, 0x00,   // line 11
                      0x00, 0x00, 0x38, 0x00,   // line 12

                      0x00, 0x00, 0x00, 0x00,   // line 13
                      0x00, 0x00, 0x00, 0x00,   // line 14
                      0x00, 0x00, 0x00, 0x00,   // line 15
                      0x00, 0x00, 0x00, 0x00,   // line 16

                      0x00, 0x00, 0x00, 0x00,   // line 17
                      0x00, 0x00, 0x00, 0x00,   // line 18
                      0x00, 0x00, 0x00, 0x00,   // line 19
                      0x00, 0x00, 0x00, 0x00,   // line 20

                      0x00, 0x00, 0x00, 0x00,   // line 21
                      0x00, 0x00, 0x00, 0x00,   // line 22
                      0x00, 0x00, 0x00, 0x00,   // line 23
                      0x00, 0x00, 0x00, 0x00,   // line 24

                      0x00, 0x00, 0x00, 0x00,   // line 25
                      0x00, 0x00, 0x00, 0x00,   // line 26
                      0x00, 0x00, 0x00, 0x00,   // line 27
                      0x00, 0x00, 0x00, 0x00,   // line 28

                      0x00, 0x00, 0x00, 0x00,   // line 29
                      0x00, 0x00, 0x00, 0x00,   // line 30
                      0x00, 0x00, 0x00, 0x00,   // line 31
                      0x00, 0x00, 0x00, 0x00};  // line 32

hIcon3 = CreateIcon(hinst,    // application instance
             32,              // icon width
             32,              // icon height
             1,               // number of XOR planes
             1,               // number of bits per pixel
             ANDmaskIcon,     // AND bitmask
             XORmaskIcon);    // XOR bitmask

To create the icon, CreateIcon applies the following truth table to the AND and XOR bitmasks.

AND bitmask | XOR bitmask | Display
0 | 0 | Black
0 | 1 | White
1 | 0 | Screen
1 | 1 | Reverse screen

Before closing, your application must use DestroyIcon to destroy any icon it created by using CreateIconIndirect. It is not necessary to destroy icons created by other functions.


Displaying an Icon

Your application can load and create icons to display in the application's client area or child windows. The following example demonstrates how to draw an icon in the client area of the window whose display context (DC) is identified by the hdc parameter.

HICON hIcon1;   // icon handle
HDC hdc;        // handle to display context

DrawIcon(hdc, 10, 20, hIcon1);

The system automatically displays the class icon(s) for a window. Your application can assign class icons while registering a window class. Your application can replace a class icon by using the SetClassLong function. This function changes the default window settings for all windows of a given class. The following example replaces a class icon with the icon whose resource identifier is 480.

HINSTANCE hinst;            // handle to current instance
HWND hwnd;                  // main window handle

// Change the icon for hwnd's window class.

SetClassLong(hwnd,          // window handle
    GCL_HICON,              // changes icon
    (LONG) LoadIcon(hinst, MAKEINTRESOURCE(480))
   );

For more information about window classes, see Window Classes.


Sharing Icon Resources

The following code uses the functions CreateIconFromResourceEx, DrawIcon, and LookupIconIdFromDirectoryEx, and several of the resource functions, to create an icon handle based on icon data from another executable file. Then, it displays the icon in a window.

HICON hIcon1;       // icon handle
HINSTANCE hExe;     // handle to loaded .EXE file
HRSRC hResource;    // handle for FindResource
HRSRC hMem;         // handle for LoadResource
BYTE *lpResource;   // address of resource data
int nID;            // ID of resource that best fits current screen

HDC hdc;        // handle to display context

// Load the file from which to copy the icon.

hExe = LoadLibrary("myapp.exe");

// Find the icon directory whose identifier is 440.

hResource = FindResource(hExe,
    MAKEINTRESOURCE(440),
    RT_GROUP_ICON);

// Load and lock the icon directory.

hMem = LoadResource(hExe, hResource);

lpResource = LockResource(hMem);

// Get the identifier of the icon that is most appropriate
// for the video display.

nID = LookupIconIdFromDirectoryEx((PBYTE) lpResource, TRUE,
    CXICON, CYICON, LR_DEFAULTCOLOR);

// Find the bits for the nID icon.

hResource = FindResource(hExe,
    MAKEINTRESOURCE(nID),
    MAKEINTRESOURCE(RT_ICON));

// Load and lock the icon.

hMem = LoadResource(hExe, hResource);

lpResource = LockResource(hMem);

// Create a handle to the icon.

hIcon1 = CreateIconFromResourceEx((PBYTE) lpResource,
    SizeofResource(hExe, hResource), TRUE, 0x00030000,
    CXICON, CYICON, LR_DEFAULTCOLOR);

// Draw the icon in the client area.

DrawIcon(hdc, 10, 20, hIcon1);


Icon Reference

The following elements are used with icons.

  • Icon Functions
  • Icon Structures
  • Icon Messages


Icon Functions

The following functions are used with icons.

CopyIcon
CreateIcon
CreateIconFromResource
CreateIconFromResourceEx
CreateIconIndirect
DestroyIcon
DrawIcon
DrawIconEx
ExtractAssociatedIcon
ExtractIcon
ExtractIconEx
GetIconInfo
LookupIconIdFromDirectory
LookupIconIdFromDirectoryEx

Obsolete Functions

LoadIcon


CopyIcon

The CopyIcon function copies the specified icon from another module to the current module.

HICON CopyIcon(
  HICON hIcon   // handle to icon to copy
);

Parameters

hIcon
Handle to the icon to be copied.

Return Values

If the function succeeds, the return value is a handle to the duplicate icon.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The CopyIcon function enables an application or dynamic-link library (DLL) to get its own handle to an icon owned by another module. If the other module is freed, the application icon will still be able to use the icon.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Icons Overview, Icon Functions, CopyCursor, DrawIcon, DrawIconEx


CreateIcon

The CreateIcon function creates an icon that has the specified size, colors, and bit patterns.

HICON CreateIcon(
  HINSTANCE hInstance,  // handle to application instance
  int nWidth,           // icon width
  int nHeight,          // icon height
  BYTE cPlanes,         // number of planes in XOR bitmask
  BYTE cBitsPixel,      // number of bits per pixel in XOR bitmask
  CONST BYTE *lpbANDbits,  // pointer to AND bitmask array
  CONST BYTE *lpbXORbits   // pointer to XOR bitmask array
);

Parameters

hInstance
Handle to the instance of the module creating the icon.
nWidth
Specifies the width, in pixels, of the icon.
nHeight
Specifies the height, in pixels, of the icon.
cPlanes
Specifies the number of planes in the XOR bitmask of the icon.
cBitsPixel
Specifies the number of bits per pixel in the XOR bitmask of the icon.
lpbANDbits
Pointer to an array of bytes that contains the bit values for the AND bitmask of the icon. This bitmask describes a monochrome bitmap.
lpbXORbits
Pointer to an array of bytes that contains the bit values for the XOR bitmask of the icon. This bitmask describes a monochrome or device-dependent color bitmap.

Return Values

If the function succeeds, the return value is a handle to an icon.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The nWidth and nHeight parameters must specify a width and height supported by the current display driver, because the system cannot create icons of other sizes. To determine the width and height supported by the display driver, use the GetSystemMetrics function, specifying the SM_CXICON or SM_CYICON value.

CreateIcon applies the following truth table to the AND and XOR bitmasks:

AND bitmask | XOR bitmask | Display
0 | 0 | Black
0 | 1 | White
1 | 0 | Screen
1 | 1 | Reverse screen

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Icons Overview, Icon Functions, GetSystemMetrics


CreateIconFromResource

The CreateIconFromResource function creates an icon or cursor from resource bits describing the icon.

HICON CreateIconFromResource(
  PBYTE presbits,  // pointer to icon or cursor bits
  DWORD dwResSize, // number of bytes in bit buffer
  BOOL fIcon,      // icon or cursor flag
  DWORD dwVer      // format version
);

Parameters

presbits
Pointer to a buffer containing the icon or cursor resource bits. These bits are typically loaded by calls to the LookupIconIdFromDirectory (in Windows 95 you can also call LookupIconIdFromDirectoryEx) and LoadResource functions.
dwResSize
Specifies the size, in bytes, of the set of bits pointed to by the presbits parameter.
fIcon
Specifies whether an icon or a cursor is to be created. If this parameter is TRUE, an icon is to be created. If it is FALSE, a cursor is to be created.
dwVer
Specifies the version number of the icon or cursor format for the resource bits pointed to by the presbits parameter. This parameter can be one of the following values:
Format | dwVer
Windows 2.x | 0x00020000
Windows 3.x | 0x00030000

All Microsoft Win32-based applications use the Windows 3.x format for icons and cursors.

Return Values

If the function succeeds, the return value is a handle to the icon or cursor.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The CreateIconFromResource, CreateIconFromResourceEx, CreateIconIndirect, GetIconInfo, LookupIconIdFromDirectory, and LookupIconIdFromDirectoryEx functions allow shell applications and icon browsers to examine and use resources from throughout the system.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Icons Overview, Icon Functions, CreateIconFromResource, CreateIconFromResourceEx, CreateIconIndirect, GetIconInfo, LoadResource, LookupIconIdFromDirectory, LookupIconIdFromDirectoryEx


CreateIconFromResourceEx

The CreateIconFromResourceEx function creates an icon or cursor from resource bits describing the icon.

HICON CreateIconFromResourceEx(
  PBYTE pbIconBits, // pointer to icon or cursor bits
  DWORD cbIconBits, // number of bytes in bit buffer
  BOOL fIcon,       // icon or cursor flag
  DWORD dwVersion,  // format version
  int cxDesired,    // desired width of icon or cursor
  int cyDesired,    // desired height of icon or cursor
  UINT uFlags       // load resource flags
);

Parameters

pbIconBits
Pointer to a buffer containing the icon or cursor resource bits. These bits are typically loaded by calls to the LookupIconIdFromDirectoryEx and LoadResource functions.
cbIconBits
Specifies the size, in bytes, of the set of bits pointed to by the pbIconBits parameter.
fIcon
Specifies whether an icon or a cursor is to be created. If this parameter is TRUE, an icon is to be created. If it is FALSE, a cursor is to be created.
dwVersion
Specifies the version number of the icon or cursor format for the resource bits pointed to by the pbIconBits parameter. This parameter can be one of the following values:
Format | dwVersion
Windows 2.x | 0x00020000
Windows 3.x | 0x00030000

All Win32-based applications use the Windows 3.x format for icons and cursors.

cxDesired
Specifies the desired width, in pixels, of the icon or cursor. If this parameter is zero, the function uses the SM_CXICON or SM_CXCURSOR system metric value to set the width.
cyDesired
Specifies the desired height, in pixels, of the icon or cursor. If this parameter is zero, the function uses the SM_CYICON or SM_CYCURSOR system metric value to set the height.
uFlags
Specifies a combination of the following values:
Value | Meaning
LR_DEFAULTCOLOR | Uses the default color format.
LR_MONOCHROME | Creates a monochrome icon or cursor.

Return Values

If the function succeeds, the return value is a handle to the icon or cursor.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The CreateIconFromResourceEx, CreateIconFromResource, CreateIconIndirect, GetIconInfo, and LookupIconIdFromDirectoryEx functions allow shell applications and icon browsers to examine and use resources from throughout the system.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Icons Overview, Icon Functions, BITMAPINFOHEADER, CreateIconFromResource, CreateIconIndirect, GetIconInfo, LoadResource, LookupIconIdFromDirectoryEx


CreateIconIndirect

The CreateIconIndirect function creates an icon or cursor from an ICONINFO structure.

HICON CreateIconIndirect(
  PICONINFO piconinfo   // pointer to icon information structure
);

Parameters

piconinfo
Pointer to an ICONINFO structure the function uses to create the icon or cursor.

Return Values

If the function succeeds, the return value is a handle to the icon or cursor that is created.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The system copies the bitmaps in the ICONINFO structure before creating the icon or cursor. Because the system may temporarily select the bitmaps in a device context, the hbmMask and hbmColor members of the ICONINFO structure should not already be selected into a device context. The application must continue to manage the original bitmaps and delete them when they are no longer necessary.

When you are finished using the icon, destroy it using the DestroyIcon function.

Windows CE: The icon component does not support cursors. When using this component, always set the fIcon field of the ICONINFO structure to TRUE.

When using the iconcurs component, you can use the CreateIconIndirect function to create either icons or monochrome cursors. Windows CE does not support color cursors.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Icons Overview, Icon Functions, DestroyIcon, ICONINFO


DestroyIcon

The DestroyIcon function destroys an icon and frees any memory the icon occupied.

BOOL DestroyIcon(
  HICON hIcon   // handle to icon to destroy
);

Parameters

hIcon
Handle to the icon to be destroyed. The icon must not be in use.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

It is only necessary to call DestroyIcon for icons and cursors created with the CreateIconIndirect function. Do not use this function to destroy a shared icon. A shared icon is valid as long as the module from which it was loaded remains in memory. The following functions obtain a shared icon:

  • LoadIcon
  • LoadImage (if you use the LR_SHARED flag)
  • CopyImage (if you use the LR_COPYRETURNORG flag and the hImage parameter is a shared icon)

Windows CE: The DestroyIcon function may be called on the icon handle returned from CreateIconIndirect, ExtractIconEx, LoadImage or LoadIcon. The icon handle is invalid after calling DestroyIcon.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Icons Overview, Icon Functions, CreateIconIndirect


DrawIcon

The DrawIcon function draws an icon in the client area of the window of the specified device context.

BOOL DrawIcon(
  HDC hDC,      // handle to device context
  int X,        // x-coordinate of upper-left corner
  int Y,        // y-coordinate of upper-left corner
  HICON hIcon   // handle to icon to draw
);

Parameters

hDC
Handle to the device context for a window.
X
Specifies the logical x-coordinate of the upper-left corner of the icon.
Y
Specifies the logical y-coordinate of the upper-left corner of the icon.
hIcon
Handle to the icon to be drawn. The icon resource must have been previously loaded by using the LoadIcon or LoadImage functions.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

DrawIcon places the icon's upper-left corner at the location specified by the X and Y parameters. The location is subject to the current mapping mode of the device context.

Windows CE: The DrawIcon function is implemented as a macro, defined as DrawIconEx(hdc, x, y, hicon, 0, 0, 0, NULL, DI_NORMAL).

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Icons Overview, Icon Functions, CreateIcon, DrawIconEx, LoadIcon


DrawIconEx

The DrawIconEx function draws an icon or cursor in the client area of the window of the specified device context, performing the specified raster operations, and stretching or compressing the icon or cursor as specified.

BOOL DrawIconEx(
  HDC hdc,                    // handle to device context
  int xLeft,                  // x-coordinate of upper left corner
  int yTop,                   // y-coordinate of upper left corner
  HICON hIcon,                // handle to icon to draw
  int cxWidth,                // width of the icon
  int cyWidth,                // height of the icon
  UINT istepIfAniCur,         // index of frame in animated cursor
  HBRUSH hbrFlickerFreeDraw,  // handle to background brush
  UINT diFlags                // icon-drawing flags
);

Parameters

hdc
Handle to the device context for a window.
xLeft
Specifies the logical x-coordinate of the upper-left corner of the icon or cursor.
yTop
Specifies the logical y-coordinate of the upper-left corner of the icon or cursor.
hIcon
Handle to the icon or cursor to be drawn. This parameter can identify an animated cursor. The icon or cursor resource must have been previously loaded by using the LoadImage function.
cxWidth
Specifies the logical width of the icon or cursor. If this parameter is zero and the diFlags parameter is DI_DEFAULTSIZE, the function uses the SM_CXICON or SM_CXCURSOR system metric value to set the width. If this parameter is zero and DI_DEFAULTSIZE is not used, the function uses the actual resource width.
cyWidth
Specifies the logical height of the icon or cursor. If this parameter is zero and the diFlags parameter is DI_DEFAULTSIZE, the function uses the SM_CYICON or SM_CYCURSOR system metric value to set the width. If this parameter is zero and DI_DEFAULTSIZE is not used, the function uses the actual resource height.
istepIfAniCur
Specifies the index of the frame to draw, if hIcon identifies an animated cursor. This parameter is ignored if hIcon does not identify an animated cursor.
hbrFlickerFreeDraw
Handle to a brush that the system uses for flicker-free drawing. If hbrFlickerFreeDraw is a valid brush handle, the system creates an offscreen bitmap using the specified brush for the background color, draws the icon or cursor into the bitmap, and then copies the bitmap into the device context identified by hdc. If hbrFlickerFreeDraw is NULL, the system draws the icon or cursor directly into the device context.
diFlags
Specifies the drawing flags. This parameter can be one of the following values:
Value | Meaning
DI_COMPAT | Draws the icon or cursor using the system default image rather than the user-specified image.
DI_DEFAULTSIZE | Draws the icon or cursor using the width and height specified by the system metric values for cursors or icons, if the cxWidth and cyWidth parameters are set to zero. If this flag is not specified and cxWidth and cyWidth are set to zero, the function uses the actual resource size.
DI_IMAGE | Draws the icon or cursor using the image.
DI_MASK | Draws the icon or cursor using the mask.
DI_NORMAL | Combination of DI_IMAGE and DI_MASK.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The DrawIconEx function places the icon's upper-left corner at the location specified by the xLeft and yTop parameters. The location is subject to the current mapping mode of the device context.

Windows CE: The following parameter settings must be used:

  • diFlags must be DI_NORMAL, DI_IMAGE, or DI_MASK. (DI_COMPAT and DI_DEFAULTSIZE are not supported.)
  • cxWidth and cyHeight must be zero or the native dimensions of the icon.
  • hbrFlickerFreeDraw must be NULL.
  • iStepIfAniCur must be zero. Animated icons are not supported.

Windows CE does not support:

  • Stretching and compressing.

    That is, the icon resolution is fixed for a given HICON, and no icon resizing is supported.

  • Mapping modes.
  • Using DrawIconEx to draw cursors.

The hIcon parameter cannot identify an animated cursor.

QuickInfo

Windows NT: Requires version 3.5 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Icons Overview, Icon Functions, CopyImage, DrawIcon, LoadImage


ExtractAssociatedIcon

The ExtractAssociatedIcon function returns a handle to an indexed icon found in a file or an icon found in an associated executable file.

HICON ExtractAssociatedIcon(
  HINSTANCE hInst,    // application instance handle
  LPTSTR lpIconPath,  // path and filename of file for which icon is
                      // wanted
  LPWORD lpiIcon      // pointer to icon index
);

Parameters

hInst
Specifies the instance of the application calling the function.
lpIconPath
Pointer to a string that specifies the full path and filename of the file for which an icon is desired. The function extracts the icon handle from that file, or from an executable file associated with that file.

If the icon handle is obtained from an executable file, the function stores the full path and filename of that executable in the string pointed to by lpIconPath.

lpiIcon
Pointer to a WORD that specifies the index of the icon whose handle is to be obtained.

If the icon handle is obtained from an executable file, the function stores the icon's identifier in the WORD pointed to by lpiIcon.

Return Values

If the function succeeds, the return value is an icon handle. If the icon is extracted from an associated executable file, the function stores the full path and filename of the executable file in the string pointed to by lpIconPath, and stores the icon's identifier in the WORD pointed to by lpiIcon.

If the function fails, the return value is NULL.

Remarks

The ExtractAssociatedIcon function first looks for the indexed icon in the file specified by lpIconPath. If the function cannot obtain the icon handle from that file, and the file has an associated executable file, it looks in that executable file for an icon. Associations with executable files are based on filename extensions, are stored in the per-user part of the registry, and can be defined using File Manager's Associate command.

QuickInfo

Windows NT: Requires version 3.5 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in shellapi.h.
Import Library: Use shell32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Icons Overview, Icon Functions, ExtractIcon


ExtractIcon

The ExtractIcon function retrieves a handle to an icon from the specified executable file, dynamic-link library (DLL), or icon file.

To retrieve an array of handles to large or small icons, use the ExtractIconEx function.

HICON ExtractIcon(
  HINSTANCE hInst,          // instance handle
  LPCTSTR lpszExeFileName,  // filename of file with icon
  UINT nIconIndex           // index of icon to extract
);

Parameters

hInst
Handle to the instance of the application calling the function.
lpszExeFileName
Pointer to a null-terminated string specifying the name of an executable file, DLL, or icon file.
nIconIndex
Specifies the zero-based index of the icon to retrieve. For example, if this value is 0, the function returns a handle to the first icon in the specified file.

If this value is –1, the function returns the total number of icons in the specified file. If the file is an executable file or DLL, the return value is the number of RT_GROUP_ICON resources. If the file is an .ICO file, the return value is 1.

Windows 95, Windows NT 4.0, and later: If this value is a negative number not equal to -1, the function returns a handle to the icon in the specified file whose resource identifier is equal to the absolute value of nIconIndex. For example, use -3 to extract the icon whose resource identifier is 3. To extract the icon whose resource identifier is 1, use the ExtractIconEx function.

Return Values

The return value is a handle to an icon. If the file specified was not an executable file, DLL, or icon file, the return is 1. If no icons were found in the file, the return value is NULL.

Remarks

You must destroy the icon handle returned by ExtractIcon by calling the DestroyIcon function.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in shellapi.h.
Import Library: Use shell32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Icons Overview, Icon Functions, DestroyIcon, ExtractIconEx


ExtractIconEx

The ExtractIconEx function creates an array of handles to large or small icons extracted from the specified executable file, dynamic-link library (DLL), or icon file.

UINT ExtractIconEx(
  LPCTSTR lpszFile,
  int nIconIndex,
  HICON FAR *phiconLarge,
  HICON FAR *phiconSmall,
  UINT nIcons
);

Parameters

lpszFile
Pointer to a null-terminated string specifying the name of an executable file, DLL, or icon file from which icons will be extracted.
nIconIndex
Specifies the zero-based index of the first icon to extract. For example, if this value is zero, the function extracts the first icon in the specified file.

If this value is –1 and phIconLarge and phiconSmall are both NULL, the function returns the total number of icons in the specified file. If the file is an executable file or DLL, the return value is the number of RT_GROUP_ICON resources. If the file is an .ICO file, the return value is 1.

Windows 95, Windows NT 4.0, and later: If this value is a negative number and either phIconLarge or phiconSmall is not NULL, the function begins by extracting the icon whose resource identifier is equal to the absolute value of nIconIndex. For example, use -3 to extract the icon whose resource identifier is 3.

phiconLarge
Pointer to an array of icon handles which receives handles to the large icons extracted from the file. If this parameter is NULL, no large icons are extracted from the file.
phiconSmall
Pointer to an array of icon handles which receives handles to the small icons extracted from the file. If this parameter is NULL, no small icons are extracted from the file.
nIcons
Specifies the number of icons to extract from the file.

Return Values

If the nIconIndex parameter is -1, the phiconLarge parameter is NULL, and the phiconSmall parameter is NULL, then the return value is the number of icons contained in the specified file. Otherwise, the return value is the number of icons successfully extracted from the file.

Remarks

You must destroy all icons extracted by ExtractIconEx by calling the DestroyIcon function.

To retrieve the dimensions of the large and small icons, use the GetSystemMetrics function with the SM_CXICON, SM_CYICON, SM_CXSMICON, and SM_CYSMICON flags.

Windows CE: The nIconIndex parameter must be zero or –N where N is a specified resource identifier. The nIcons parameter must be 1.

QuickInfo

Windows NT: Requires version 3.5 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in shellapi.h.
Import Library: Use shell32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Icons Overview, Icon Functions, DestroyIcon, ExtractIcon


GetIconInfo

The GetIconInfo function retrieves information about the specified icon or cursor.

BOOL GetIconInfo(
  HICON hIcon,          // icon handle
  PICONINFO piconinfo   // address of icon structure
);

Parameters

hIcon
Handle to the icon or cursor. To retrieve information about a standard icon or cursor, specify one of the following values:
Value | Meaning
IDC_APPSTARTING | Standard arrow and small hourglass cursor
IDC_ARROW | Standard arrow cursor
IDC_CROSS | Crosshair cursor
IDC_HAND | Windows NT 5.0 and later: Hand cursor
IDC_HELP | Arrow and question mark cursor
IDC_IBEAM | I-beam cursor
IDC_NO | Slashed circle cursor
IDC_SIZEALL | Four-pointed arrow cursor pointing north, south, east, and west
IDC_SIZENESW | Double-pointed arrow cursor pointing northeast and southwest
IDC_SIZENS | Double-pointed arrow cursor pointing north and south
IDC_SIZENWSE | Double-pointed arrow cursor pointing northwest and southeast
IDC_SIZEWE | Double-pointed arrow cursor pointing west and east
IDC_UPARROW | Vertical arrow cursor
IDC_WAIT | Hourglass cursor
IDI_APPLICATION | Application icon
IDI_ASTERISK | Asterisk icon
IDI_EXCLAMATION | Exclamation point icon
IDI_HAND | Stop sign icon
IDI_QUESTION | Question-mark icon
IDI_WINLOGO | Windows logo icon

piconinfo
Pointer to an ICONINFO structure. The function fills in the structure's members.

Return Values

If the function succeeds, the return value is nonzero and the function fills in the members of the specified ICONINFO structure.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

GetIconInfo creates bitmaps for the hbmMask and hbmColor members of ICONINFO. The calling application must manage these bitmaps and delete them when they are no longer necessary.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Icons Overview, Icon Functions, CreateIcon, CreateIconFromResource, CreateIconIndirect, DestroyIcon, DrawIcon, DrawIconEx, ICONINFO, LoadIcon, LookupIconIdFromDirectory


LoadIcon

The LoadIcon function loads the specified icon resource from the executable (.EXE) file associated with an application instance. This function has been superseded by the LoadImage function

HICON LoadIcon(
  HINSTANCE hInstance, // handle to application instance
  LPCTSTR lpIconName   // icon-name string or icon resource
                       // identifier
);

Parameters

hInstance
Handle to an instance of the module whose executable file contains the icon to be loaded. This parameter must be NULL when a standard icon is being loaded.
lpIconName
Pointer to a null-terminated string that contains the name of the icon resource to be loaded. Alternatively, this parameter can contain the resource identifier in the low-order word and zero in the high-order word. Use the MAKEINTRESOURCE macro to create this value.

To use one of the predefined icons, set the hInstance parameter to NULL and the lpIconName parameter to one of the following values:
Value | Description
IDI_APPLICATION | Default application icon.
IDI_ASTERISK | Same as IDI_INFORMATION.
IDI_ERROR | Hand-shaped icon.
IDI_EXCLAMATION | Same as IDI_WARNING.
IDI_HAND | Same as IDI_ERROR.
IDI_INFORMATION | Asterisk icon.
IDI_QUESTION | Question mark icon.
IDI_WARNING | Exclamation point icon.
IDI_WINLOGO | Windows logo icon.

Return Values

If the function succeeds, the return value is a handle to the newly loaded icon.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

LoadIcon loads the icon resource only if it has not been loaded; otherwise, it retrieves a handle to the existing resource. The function searches the icon resource for the icon most appropriate for the current display. The icon resource can be a color or monochrome bitmap.

LoadIcon can only load an icon whose size conforms to the SM_CXICON and SM_CYICON system metric values. Use the LoadImage function to load icons of other sizes.

Windows CE: Predefined icons (IDI_*) are not supported.

In Windows CE 1.0, the icon must be a two bit per pixel (.ic2) icon or a monochrome icon.

See Also

Icons Overview, Icon Functions, CreateIcon, LoadImage, MAKEINTRESOURCE


LookupIconIdFromDirectory

The LookupIconIdFromDirectory function searches through icon or cursor data for the icon or cursor that best fits the current display device.

int LookupIconIdFromDirectory(
  PBYTE presbits,  // address of resource data
  BOOL fIcon       // look for icon or cursor
);

Parameters

presbits
Pointer to the icon or cursor directory data. Because this function does not validate the resource data, it causes a general protection (GP) fault or returns an undefined value if presbits is not pointing to valid resource data.
fIcon
Specifies whether an icon or a cursor is sought. If this parameter is TRUE, the function is searching for an icon; if the parameter is FALSE, the function is searching for a cursor.

Return Values

If the function succeeds, the return value is an integer resource identifier for the icon or cursor that best fits the current display device.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

A resource file of type RT_GROUP_ICON (RT_GROUP_CURSOR indicates cursors) contains icon (or cursor) data in several device-dependent and device-independent formats. LookupIconIdFromDirectory searches the resource file for the icon (or cursor) that best fits the current display device and returns its integer identifier. The FindResource and FindResourceEx functions use the MAKEINTRESOURCE macro with this identifier to locate the resource in the module.

The icon directory is loaded from a resource file with resource type RT_GROUP_ICON (or RT_GROUP_CURSOR for cursors), and an integer resource name for the specific icon to be loaded. LookupIconIdFromDirectory returns an integer identifier that is the resource name of the icon that best fits the current display device.

The LoadIcon, LoadCursor, and LoadImage functions use this function to search the specified resource data for the icon or cursor that best fits the current display device.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Icons Overview, Icon Functions, CreateIconFromResource, CreateIconIndirect, FindResource, FindResourceEx, GetIconInfo, LoadCursor, LoadIcon, LoadImage, LookupIconIdFromDirectoryEx, MAKEINTRESOURCE


LookupIconIdFromDirectoryEx

The LookupIconIdFromDirectoryEx function searches through icon or cursor data for the icon or cursor that best fits the current display device.

int LookupIconIdFromDirectoryEx(
  PBYTE presbits, // address of resource data
  BOOL fIcon,     // icon or cursor flag
  int cxDesired,  // desired width of icon or cursor
  int cyDesired,  // desired height of icon or cursor
  UINT Flags      // resource flags
);

Parameters

presbits
Pointer to the icon or cursor directory data. Because this function does not validate the resource data, it causes a general protection (GP) fault or returns an undefined value if presbits is not pointing to valid resource data.
fIcon
Specifies whether an icon or a cursor is sought. If this parameter is TRUE, the function is searching for an icon; if the parameter is FALSE, the function is searching for a cursor.
cxDesired
Specifies the desired width, in pixels, of the icon. If this parameter is zero, the function uses the SM_CXICON or SM_CXCURSOR system metric value.
cyDesired
Specifies the desired height, in pixels, of the icon. If this parameter is zero, the function uses the SM_CYICON or SM_CYCURSOR system metric value.
Flags
Specifies a combination of the following values:
Value | Meaning
LR_DEFAULTCOLOR | Uses the default color format.
LR_MONOCHROME | Creates a monochrome icon or cursor.

Return Values

If the function succeeds, the return value is an integer resource identifier for the icon or cursor that best fits the current display device.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

A resource file of type RT_GROUP_ICON (RT_GROUP_CURSOR indicates cursors) contains icon (or cursor) data in several device-dependent and device-independent formats. LookupIconIdFromDirectoryEx searches the resource file for the icon (or cursor) that best fits the current display device and returns its integer identifier. The FindResource and FindResourceEx functions use the MAKEINTRESOURCE macro with this identifier to locate the resource in the module.

The icon directory is loaded from a resource file with resource type RT_GROUP_ICON (or RT_GROUP_CURSOR for cursors), and an integer resource name for the specific icon to be loaded. LookupIconIdFromDirectoryEx returns an integer identifier that is the resource name of the icon that best fits the current display device.

The LoadIcon, LoadImage, and LoadCursor functions use this function to search the specified resource data for the icon or cursor that best fits the current display device.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Icons Overview, Icon Functions, CreateIconFromResourceEx, CreateIconIndirect, FindResource, FindResourceEx, GetIconInfo, LoadCursor, LoadIcon, LoadImage, LookupIconIdFromDirectory, MAKEINTRESOURCE


Icon Structures

The following structures are used with icons.

ICONINFO
ICONMETRICS


ICONINFO

The ICONINFO structure contains information about an icon or a cursor.

typedef struct _ICONINFO { // ii
   BOOL    fIcon;
   DWORD   xHotspot;
   DWORD   yHotspot;
   HBITMAP hbmMask;
   HBITMAP hbmColor;
} ICONINFO;

Members

fIcon
Specifies whether this structure defines an icon or a cursor. A value of TRUE specifies an icon; FALSE specifies a cursor.
xHotspot
Specifies the x-coordinate of a cursor's hot spot. If this structure defines an icon, the hot spot is always in the center of the icon, and this member is ignored.
yHotspot
Specifies the y-coordinate of the cursor's hot spot. If this structure defines an icon, the hot spot is always in the center of the icon, and this member is ignored.
hbmMask
Specifies the icon bitmask bitmap. If this structure defines a black and white icon, this bitmask is formatted so that the upper half is the icon AND bitmask and the lower half is the icon XOR bitmask. Under this condition, the height should be an even multiple of two. If this structure defines a color icon, this mask only defines the AND bitmask of the icon.
hbmColor
Handle to the icon color bitmap. This member can be optional if this structure defines a black and white icon. The AND bitmask of hbmMask is applied with the SRCAND flag to the destination; subsequently, the color bitmap is applied (using XOR) to the destination by using the SRCINVERT flag.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Icons Overview, Icon Structures, CreateIconIndirect, GetIconInfo


ICONMETRICS

The ICONMETRICS structure contains the scalable metrics associated with icons. This structure is used with the SystemParametersInfo function when the SPI_GETICONMETRICS or SPI_SETICONMETRICS action is specified.

typedef struct tagICONMETRICS {
    UINT    cbSize;
    int     iHorzSpacing;
    int     iVertSpacing;
    int     iTitleWrap;
    LOGFONT lfFont;
} ICONMETRICS, FAR *LPICONMETRICS;

Members

cbSize
Specifies the size of the structure, in bytes.
iHorzSpacing and iVertSpacing
Horizontal and vertical space, in pixels, for each arranged icon.
iTitleWrap
Title-wrapping flag. If this member is nonzero, icon titles wrap to a new line. If this member is zero, titles do not wrap.
lfFont
Specifies the font to use for icon titles.

QuickInfo

Windows NT: Requires version 3.5 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Unicode: Defined as Unicode and ANSI structures.

See Also

Icons Overview, Icon Structures, SystemParametersInfo


Icon Messages

The following messages are used with icons.

WM_ERASEBKGND
WM_ICONERASEBKGND
WM_PAINTICON


WM_ERASEBKGND

An application sends the WM_ERASEBKGND message when the window background must be erased (for example, when a window is resized). The message is sent to prepare an invalidated portion of a window for painting.

WM_ERASEBKGND
hdc = (HDC) wParam; // handle to device context

Parameters

hdc
Value of wParam. Handle to the device context.

Return Values

An application should return nonzero if it erases the background; otherwise, it should return zero.

Remarks

The DefWindowProc function erases the background by using the class background brush specified by the hbrBackground member of the WNDCLASS structure. If hbrBackground is NULL, the application should process the WM_ERASEBKGND message and erase the background.

An application should return nonzero in response to WM_ERASEBKGND if it processes the message and erases the background; this indicates that no further erasing is required. If the application returns zero, the window will remain marked for erasing. (Typically, this indicates that the fErase member of the PAINTSTRUCT structure will be TRUE.)

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Icons Overview, Icon Messages, BeginPaint, DefWindowProc, PAINTSTRUCT, WM_ICONERASEBKGND, WNDCLASS


WM_ICONERASEBKGND

The WM_ICONERASEBKGND message is sent to a minimized window when the background of the icon must be filled before painting the icon. A window receives this message only if a class icon is defined for the window; otherwise, WM_ERASEBKGND is sent.

WM_ICONERASEBKGND
hdc = (HDC) wParam; // handle to device context

Parameters

hdc
Value of wParam. Handle to the device context of the icon.

Return Values

An application should return nonzero if it processes this message.

Remarks

The DefWindowProc function fills the icon background with the class background brush of the parent window.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Icons Overview, Icon Messages, DefWindowProc, WM_ERASEBKGND


WM_PAINTICON

The WM_PAINTICON message is sent to a minimized window when the icon is to be painted but only if the application is written for 16-bit Windows. A window receives this message only if a class icon is defined for the window; otherwise, WM_PAINT is sent instead.

WM_PAINTICON

Parameters

This message has no parameters.

Return Values

An application should return zero if it processes this message.

Remarks

The DefWindowProc function draws the class icon. For compatibility with 16-bit Windows, wParam is TRUE. However, this value has no significance.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Icons Overview, Icon Messages, DefWindowProc, WM_ICONERASEBKGND, WM_PAINT


Menus

This overview describes menus and explains how to use them in Win32-based applications.


About Menus

A menu is a list of menu items. Clicking a menu item opens a submenu or causes the application to carry out a command. The following sections discuss various aspects of menus.

  • Menu Bars and Menus
  • Menu Handles
  • Menu Items
  • Keyboard Access to Menus
  • Menu Creation
  • Menu Destruction
  • Messages Used with Menus
  • Menu Modifications


Menu Bars and Menus

A menu is arranged in a hierarchy. At the top level of the hierarchy is the menu bar; menus drop down from the menu bar, and at the lower levels are submenus. A menu bar is sometimes called a top-level menu, and the menus and submenus are also known as pop-up menus.

A menu item can either carry out a command or open a submenu. An item that carries out a command is called a command item or a command.

An item on the menu bar almost always opens a menu. Menu bars rarely contain command items. A menu opened from the menu bar drops down from the menu bar and is sometimes called a drop-down menu. When a drop-down menu is displayed, it is attached to the menu bar. A menu item on the menu bar that opens a drop-down menu is also called a menu name.

The menu names on a menu bar represent the main categories of commands that an application provides. Selecting a menu name from the menu bar typically opens a menu whose menu items correspond to the commands in a given category. For example, a menu bar might contain a File menu name that, when clicked by the user, activates a menu with menu items such as New, Open, and Save.

Only an overlapped or pop-up window can contain a menu bar; a child window cannot contain one. If the window has a title bar, the system positions the menu bar just below it. A menu bar is always visible. A submenu is not visible, however, until the user selects a menu item that activates it. For more information about overlapped and pop-up windows, see General Window Styles.

Each menu must have an owner window. The system sends messages to a menu's owner window when the user selects the menu or chooses an item from the menu. These messages are described in Messages Used with Menus.


Shortcut Menus

The system also provides shortcut menus. A shortcut menu is not attached to the menu bar; it can appear anywhere on the screen. An application typically associates a shortcut menu with a portion of a window, such as the client area, or with a specific object, such as an icon. For this reason, these menus are also called context menus.

A shortcut menu remains hidden until the user activates it, typically by right-clicking a selection, a toolbar, or a taskbar button. The menu is usually displayed at the position of the caret or mouse cursor.


The Window Menu

The window menu (also known as the System menu or Control menu) is a pop-up menu defined and managed almost exclusively by the operating system. The user can open the window menu by clicking the application icon on the title bar or by right-clicking anywhere on the title bar.

The window menu provides a standard set of menu items that the user can choose to change a window's size or position, or close the application. Items on the window menu can be added, deleted, and modified, but most applications just use the standard set of menu items. An overlapped, pop-up, or child window can have a window menu. It is uncommon for an overlapped or pop-up window not to include a window menu.

When the user chooses a command from the window menu, the system sends a WM_SYSCOMMAND message to the menu's owner window. In most applications, the window procedure does not process messages from the window menu. Instead, it simply passes the messages to the DefWindowProc function for system-default processing of the message. If an application adds a command to the window menu, the window procedure must process the command.

An application can use the GetSystemMenu function to create a copy of the default window menu to modify. Any window that does not use the GetSystemMenu function to make its own copy of the window menu receives the standard window menu.


Help Identifier

Associated with each menu bar, menu, submenu, and shortcut menu is a 32-bit help identifier. If the user presses the f1 key while the menu is active, this value is sent to the owner window as part of a WM_HELP message. For more information, see Help.


Menu Handles

The system generates a unique handle for each menu. A menu handle is a value of the HMENU type. An application must specify a menu handle in many of the Win32 menu functions. You receive the handle to a menu bar when you create the menu or load a menu resource. For more information, see Menu Creation.

To retrieve the handle to the menu bar for a menu that has been created or loaded, use the GetMenu function. To retrieve the handle to the submenu associated with a menu item, use the GetSubMenu or GetMenuItemInfo function. To retrieve the handle to a window menu, use the GetSystemMenu function.


Menu Items

The following topics discuss what the system does when the user chooses a menu item, and the ways an application can control an item's appearance and functionality.

  • Command Items and Items that Open Submenus
  • Menu Item Identifier
  • Menu Item Position
  • Default Menu Items
  • Checked and Unchecked Menu Items
  • Enabled, Grayed, and Disabled Menu Items
  • Highlighted Menu Items
  • Owner-Drawn Menu Items
  • Menu Item Separators and Line Breaks


Command Items and Items that Open Submenus

When the user chooses a command item, the system sends a command message to the window that owns the menu. If the command item is on the window menu, the system sends the WM_SYSCOMMAND message. Otherwise, it sends the WM_COMMAND message.

Associated with each menu item that opens a submenu is the handle to the corresponding submenu. When the user points to such an item, the system opens the submenu. No command message is sent to the owner window. However, the system sends a WM_INITMENUPOPUP message to the owner window before displaying the submenu. You can get the handle to the submenu associated with an item by using the GetSubMenu or GetMenuItemInfo function.

A menu bar typically contains menu names, but it can also contain command items. A submenu typically contains command items, but it can also contain items that open nested submenus. By adding such items to submenus, you can nest menus to any depth. To provide a visual cue for the user, the system automatically displays a small arrow to the right of the text of a menu item that opens a submenu.


Menu-item Identifier

Associated with each menu item is a unique, application-defined integer, called a menu-item identifier. When the user chooses a command item from a menu, the system sends the item's identifier to the owner window as part of a WM_COMMAND message. The window procedure examines the identifier to determine the source of the message, and processes the message accordingly. In addition, you can specify a menu item using its identifier when you call menu functions; for example, to enable or disable a menu item.

A menu-item identifier must be a value from 0 to 65,535, even though it is a 32-bit integer. This is because the WM_COMMAND message passes a menu-item identifier as the low-order word of its wParam parameter.

Menu items that open submenus have identifiers just as command items do. However, the system does not send a command message when such an item is selected from a menu. Instead, the system opens the submenu associated with the menu item.

To retrieve the identifier of the menu item at a specified position, use the GetMenuItemID or GetMenuItemInfo function.


Menu-Item Position

In addition to having a unique identifier, each menu item in a menu bar or menu has a unique position value. The leftmost item in a menu bar, or the top item in a menu, has position zero. The position value is incremented for subsequent menu items. The system assigns a position value to all items in a menu, including separators. The following illustration shows the position values of items in a menu bar and in a menu.

When calling a menu function that modifies or retrieves information about a specific menu item, you can specify the item using either its identifier or its position. For more information, see Menu Modifications.


Default Menu Items

A submenu can contain one default menu item. When the user opens a submenu by double-clicking, the system sends a command message to the menu's owner window and closes the menu as if the default command item had been chosen. If there is no default command item, the submenu remains open. To retrieve and set the default item for a submenu, use the GetMenuDefaultItem and SetMenuDefaultItem functions.


Checked and Unchecked Menu Items

A menu item can be either checked or unchecked. The system displays a bitmap next to checked menu items to indicate their checked state. The system does not display a bitmap next to unchecked items, unless an application-defined "unchecked" bitmap is specified. Only menu items in a menu can be checked; items in a menu bar cannot be checked.

Applications typically check or uncheck a menu item to indicate whether an option is in effect. For example, suppose an application has a toolbar that the user can show or hide by using a Toolbar command on a menu. When the toolbar is hidden, the Toolbar menu item is unchecked. When the user chooses the command, the application checks the menu item and shows the toolbar.

A check-mark attribute controls whether a menu item is checked. You can set a menu item's check-mark attribute by using the CheckMenuItem function. You can use the GetMenuState function to determine whether a menu item is currently checked or unchecked.

Instead of CheckMenuItem and GetMenuState, you can use the GetMenuItemInfo and SetMenuItemInfo functions to retrieve and set the check state of a menu item.

Sometimes, a group of menu items corresponds to a set of mutually exclusive options. In this case, you can indicate the selected option by using a checked radio menu item (analogous to a radio button control). Checked radio items are displayed with a bullet bitmap instead of a check-mark bitmap. To check a menu item and make it a radio item, use the CheckMenuRadioItem function.

By default, the system displays a check-mark or bullet bitmap next to checked menu items and no bitmap next to unchecked menu items. However, you can use the SetMenuItemBitmaps function to associate application-defined checked and unchecked bitmaps with a menu item. The system then uses the specified bitmaps to indicate the menu item's checked or unchecked state.

Application-defined bitmaps associated with a menu item must be the same size as the default check-mark bitmap, the dimensions of which may vary depending on screen resolution. To retrieve the correct dimensions, use the GetSystemMetrics function. You can create multiple bitmap resources for different screen resolutions; create one bitmap resource and scale it, if necessary; or create a bitmap at run time and draw an image in it. The bitmaps may be either monochrome or color. However, because menu items are inverted when highlighted, the appearance of certain inverted color bitmaps may be undesirable. For more information, see Bitmaps.


Enabled, Grayed, and Disabled Menu Items

A menu item can be enabled, grayed, or disabled. By default, a menu item is enabled. When the user chooses an enabled menu item, the system sends a command message to the owner window or displays the corresponding submenu, depending on what kind of menu item it is.

When menu items are not available to the user, they should be grayed or disabled. Grayed and disabled menu items cannot be chosen. A disabled item looks just like an enabled item. When the user clicks on a disabled item, the item is not selected, and nothing happens. Disabled items can be useful in, for example, a tutorial that presents a menu that looks active but isn't.

An application grays an unavailable menu item to provide a visual cue to the user that a command is not available. You can use a grayed item when an action is not appropriate (for example, you can gray the Print command in the File menu when the system does not have a printer installed).

The EnableMenuItem function enables, grays, or disables a menu item. To determine whether a menu item is enabled, grayed, or disabled, use the GetMenuItemInfo function.

Instead of GetMenuItemInfo, you can also use the GetMenuState function to determine whether a menu item is enabled, grayed, or disabled.


Highlighted Menu Items

The system automatically highlights menu items on menus as the user selects them. However, highlighting can be explicitly added or removed from a menu name on the menu bar by using the HiliteMenuItem function. This function has no effect on menu items on menus. When HiliteMenuItem is used to highlight a menu name, though, the name only appears to be selected. If the user presses the enter key, the highlighted item is not chosen. This feature might be useful in, for example, a training application that demonstrates the use of menus.


Owner-Drawn Menu Items

An application can completely control the appearance of a menu item by using an owner-drawn item. Owner-drawn items require an application to take total responsibility for drawing selected (highlighted), checked, and unchecked states. For example, if an application provided a font menu, it could draw each menu item by using the corresponding font; the item for Roman would be drawn with roman, the item for Italic would be drawn in italic, and so on.

For more information, see Creating Owner-Drawn Menu Items.


Menu Item Separators and Line Breaks

The system provides a special type of menu item, called a separator, that appears as a horizontal line. You can use a separator to divide a menu into groups of related items. A separator cannot be used in a menu bar, and the user cannot select a separator.

When a menu bar contains more menu names than will fit on one line, the system wraps the menu bar by automatically breaking it into two or more lines. You can cause a line break to occur at a specific item on a menu bar by assigning the MFT_MENUBREAK type flag to the item. The system places that item and all subsequent items on a new line.

When a menu contains more items than will fit in one column, the menu will be truncated. You can cause a column break to occur at a specific item in a menu by assigning the MFT_MENUBREAK type flag to the item or using the MENUBREAK option in the MENUITEM statement. The system places that item and all subsequent items in a new column. The MFT_MENUBARBREAK type flag has the same effect, except that a vertical line appears between the new column and the old.

If you use the AppendMenu, InsertMenu, or ModifyMenu functions to assign line breaks, you should assign the type flags MF_MENUBREAK or MF_MENUBARBREAK.


Keyboard Access to Menus

The system provides a standard keyboard interface for menus. You can enhance this interface by providing mnemonic access keys and shortcut (accelerator) keys for your menu items. The following topics describe the standard keyboard interface, access keys, and shortcut keys.

  • Standard Keyboard Interface
  • Menu Access Keys
  • Menu Shortcut Keys


Standard Keyboard Interface

The system is designed to work with or without a mouse or other pointing device. Because the system provides a standard keyboard interface, the user can use the keyboard to select menu items. This keyboard interface does not need special code. An application receives a command message whether the user selects a menu item through the keyboard or by using a mouse. The standard keyboard interface processes the following keystrokes.

Keystroke | Action
Alphabetic character | Selects the first menu item with the specified character as its access key. If the selected item invokes a menu, the menu is displayed and the first item is highlighted. Otherwise, the menu item is chosen.
alt | Toggles in and out of menu bar mode.
alt+spacebar | Displays the window menu.
enter | Activates a menu and selects the first menu item if an item has a menu associated with it. Otherwise, this keystroke chooses the item as if the user released the mouse button while the item was selected.
esc | Exits menu mode.
left arrow | Cycles to the previous top-level menu item. Top-level menu items include menu names and the window menu. If the selected item is in a menu, the previous column in the menu is selected or the previous top-level menu item is selected.
right arrow | Works like the left arrow key, except in the opposite direction. In menus, this keystroke moves forward one column; when the currently selected item is in the far-right column, the next menu is selected.
up or down arrows | Activates a menu when pressed in a menu name. When pressed in a menu, the up arrow keystroke selects the previous item; the down arrow keystroke selects the next item.


Menu Access Keys

The standard keyboard interface for menus can be enhanced by adding access keys (mnemonics) to menu items. An access key is an underlined letter in the text of a menu item. When a menu is active, the user can select a menu item by pressing the key that corresponds to the item's underlined letter. The user makes the menu bar active by pressing the alt key to highlight the first item on the menu bar. A menu is active when it is displayed.

To create an access key for a menu item, precede any character in the item's text string with an ampersand. For example, the text string "&Move" causes the system to underline the letter "M".


Menu Shortcut Keys

In addition to having an access key, a menu item can have a shortcut key associated with it. A shortcut key is different from an access key, because the menu does not have to be active for the shortcut key to work. Also, an access key is always associated with a menu item, while an shortcut key is usually (but does not have to be) associated with a menu item.

Text that identifies the shortcut key is added to the menu-item text string. The shortcut text appears to the right of the menu item name, after a backslash and tab character (\t). For example, "&Close\tAlt+F4" represents a Close command with the alt+f4 key combination as its shortcut key and with the letter "C" as its access key. For more information, see Keyboard Accelerators.


Menu Creation

You can create a menu using either a menu template or menu creation functions. Menu templates are typically defined as resources. Menu-template resources can be loaded explicitly or assigned as the default menu for a window class. You can also create menu-template resources dynamically in memory. The following topics describe menu creation in detail.

  • Menu Template Resources
  • Menu Template in Memory
  • Menu Creation Functions
  • Menu Display
  • Window Class Menus


Menu Template Resources

Most applications create menus using menu-template resources. A menu template defines a menu, including the items in the menu bar and all menus. For information about creating a menu-template resource, see the documentation included with your development tools.

After you create a menu-template resource and add it to your application's executable (.EXE) file, you can use the LoadMenu function to load the resource into memory. This function returns the handle to the menu, which you can then assign to a window by using the SetMenu function.

Implementing menus as resources makes an application easier to localize for use in multiple countries. Only the resource-definition file needs to be localized for each language, not the application's source code.


Menu Template in Memory

A menu can be created from a menu template that is built in memory at run time. For example, an application that allows a user to customize its menu might create a menu template in memory based on the user's preferences. The application could then save the template in a file or in the registry for future use. To create a menu from a template in memory, use the LoadMenuIndirect function. For descriptions of menu-template formats, see Using a Menu-Template Resource.

A standard menu template consists of a MENUITEMTEMPLATEHEADER structure followed by one or more MENUITEMTEMPLATE structures.

An extended menu template consists of a MENUEX_TEMPLATE_HEADER structure followed by one or more MENUEX_TEMPLATE_ITEM structures.


Menu Creation Functions

Using menu creation functions, you can create menus at run time or add menu items to existing menus. You can use the CreateMenu function to create an empty menu bar and the CreatePopupMenu function to create an empty menu. To add items to a menu, use the InsertMenuItem function. The older AppendMenu and InsertMenu functions are still supported, but InsertMenuItem should be used for new applications.


Menu Display

After a menu has been loaded or created, it must be assigned to a window before the system can display it. You can assign a menu by defining a class menu. For more information, see Window Class Menus. You can also assign a menu to a window by specifying the handle to the menu as the hMenu parameter of the CreateWindow or CreateWindowEx function, or by calling the SetMenu function.

To display a shortcut menu use the TrackPopupMenuEx function. Shortcut menus, also called floating pop-up menus or context menus, are typically displayed when the WM_CONTEXTMENU message is processed.

The older TrackPopupMenu function is still supported, but new applications should use the TrackPopupMenuEx function.


Window Class Menus

You can specify a default menu, called a class menu, when you register a window class. To do so, you assign the name of the menu-template resource to the lpszMenuName member of the WNDCLASS structure used to register the class.

By default, every window is assigned the class menu for its window class so you do not need to explicitly load the menu and assign it to each window. You can override the class menu by specifying a different menu handle in a call to the CreateWindowEx function. You can also change a window's menu after it is created by using the SetMenu function. For more information, see Window Classes.


Menu Destruction

If a menu is assigned to a window and that window is destroyed, the system automatically destroys the menu and its submenus, freeing the menu's handle and the memory occupied by the menu. The system does not automatically destroy a menu that is not assigned to a window. An application must destroy the unassigned menu by calling the DestroyMenu function. Otherwise, the menu continues to exist in memory even after the application closes.


Messages Used with Menus

The system reports menu-related activity by sending messages to the window procedure of the window that owns the menu. The system sends a series of messages when the user selects items on the menu bar or clicks the right mouse button to display a shortcut menu.

When the user activates an item on the menu bar, the owner window first receives a WM_SYSCOMMAND message. This message includes a flag that indicates whether the user activated the menu by using the keyboard (SC_KEYMENU) or the mouse (SC_MOUSEMENU). For more information, see Keyboard Access to Menus.

Next, before displaying any menus, the system sends the WM_INITMENU message to the window procedure so that an application can modify the menus before the user sees them. The system sends the WM_INITMENU message only once per menu activation.

When the user points to a menu item that opens a submenu, the system sends the owner window the WM_INITMENUPOPUP message before displaying the submenu. This message gives the application an opportunity to modify the submenu before it is displayed.

Each time the user moves the highlighting from one item to another, the system sends a WM_MENUSELECT message to the window procedure of the menu's owner window. This message identifies the currently selected menu item. Many applications provide an information area at the bottom of their main windows and use this message to display additional information about the selected menu item.

When the user chooses a command item from a menu, the system sends a WM_COMMAND message to the window procedure. The low-order word of the WM_COMMAND message's wParam parameter contains the identifier of the chosen item. The window procedure should examine the identifier and process the message accordingly.

Not all menus are accessible through a window's menu bar. Many applications display shortcut menus when the user clicks the right mouse button at a specific location. Such applications should process the WM_CONTEXTMENU message and display a shortcut menu, if appropriate. If an application does not display a shortcut menu, it should pass the WM_CONTEXTMENU message to the DefWindowProc function for default processing.


Menu Modifications

Several functions enable you to change a menu after it has been loaded or created. These changes may include adding or removing menu items and modifying existing menu items.

To add a menu item, use the InsertMenuItem function. You can use the SetMenuItemInfo function to change the attributes of an existing menu item. The lpmii parameter points to a MENUITEMINFO structure, which contains the new attributes and specifies which attributes to change. A menu item's attributes include its type, state, identifier, submenu, bitmaps, item data, and text.

The older AppendMenu and InsertMenu functions can also be used to add menu items, but new applications should use InsertMenuItem. The AppendMenu function appends a menu item to the end of a menu or submenu; the InsertMenu function inserts a menu item at a specified position in a menu or submenu. Both functions permit the attributes of the menu item to be specified, including whether the menu item is enabled, disabled, grayed, checked, or unchecked.

To change the appearance or attributes of an existing menu item, use the ModifyMenu function. For example, the text string or bitmap of a menu item can be enabled, disabled, grayed, checked, or unchecked. The ModifyMenu function replaces the specified menu item with a new item.

To retrieve information about a menu item, use the GetMenuItemInfo function. The lpmii parameter points to a MENUITEMINFO structure, which specifies the attributes to retrieve and receives their current values.

To delete a menu item from a menu, use the DeleteMenu or RemoveMenu function. If the item being deleted is one that opens a submenu, DeleteMenu deletes the associated submenu, discarding the menu handle and freeing the memory used by the submenu. The RemoveMenu function deletes a menu item, but if the item opens a submenu, the function does not destroy the submenu or its handle, allowing the submenu to be reused.

To redraw the menu bar after a menu bar has been modified, use the DrawMenuBar function. Otherwise, the modifications will not appear until the system redraws the owner window.


Using Menus

  • Using a menu-template resource
  • Creating a shortcut menu
  • Using menu-item bitmaps
  • Creating owner-drawn menu items
  • Using custom check-mark bitmaps


Using a Menu-Template Resource

You typically include a menu in an application by creating a menu-template resource and then loading the menu at run time. This section describes the format of a menu template, and explains how to load a menu-template resource and use it in your application. For information about creating a menu-template resource, see the documentation included with your development tools.


Extended Menu-Template Format

The extended menu-template format supports the menu functionality implemented starting with Windows 95 and Windows NT version 4.0. Like menu-template resources used previously, extended menu-template resources have the RT_MENU resource type. The system distinguishes the two resource formats by the version number, which is the first member of the resource header.

An extended menu template consists of a MENUEX_TEMPLATE_HEADER structure followed by one more MENUEX_TEMPLATE_ITEM item definition structures.


Old Menu-Template Format

An old menu template (for systems earlier than Windows 95 and Windows NT 4.0) defines a menu, but does not support the new menu functionality. An old menu-template resource has the RT_MENU resource type.

An old menu template consists of a MENUITEMTEMPLATEHEADER structure followed by one or more MENUITEMTEMPLATE structures.


Loading a Menu-Template Resource

To load a menu-template resource, use the LoadMenu function, specifying the handle to the module that contains the resource and the menu template's identifier. The LoadMenu function returns a menu handle that you can use to assign the menu to a window. This window becomes the menu's owner window, receiving all the messages generated by the menu.

To create a menu from a menu template that is already in memory, use the LoadMenuIndirect function. This is useful if your application generates menu templates dynamically.

To assign a menu to a window, use the SetMenu function or specify the menu's handle in the hMenu parameter of the CreateWindowEx function when creating a window. Another way you can assign a menu to a window is to specify a menu template when you register a window class; the template identifies the specified menu as the class menu for that window class.

To have the system automatically assign a specific menu to a window, specify the menu's template when you register the window's class. The template identifies the specified menu as the class menu for that window class. Then, when you create a window of the given class, the system automatically assigns the specified menu to the window.

To create a class menu, include the identifier of the menu-template resource as the lpszMenuName member of a WNDCLASS structure and then pass the address of the structure to the RegisterClass function.


Creating a Class Menu

The following example shows how to create a class menu for an application, create a window that uses the class menu, and process menu commands in the window procedure.

Following is the relevant portion of the application's header file:

// Menu-template resource identifier

#define IDM_MYMENURESOURCE   3

Following are the relevant portions of the application itself:

HINSTANCE hinst;

int APIENTRY WinMain(HINSTANCE hinstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    MSG msg;        // message
    WNDCLASS wc;    // windowclass data
    HWND hwnd;      // handle to the main window

    // Create the window class for the main window. Specify
    // the identifier of the menu-template resource as the
    // lpszMenuName member of the WNDCLASS structure to create
    // the class menu.

    wc.style = 0;
    wc.lpfnWndProc = (WNDPROC) MainWndProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = hinstance;
    wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = GetStockObject(WHITE_BRUSH);
    wc.lpszMenuName =  MAKEINTRESOURCE(IDM_MYMENURESOURCE);
    wc.lpszClassName = "MainWClass";

    if (!RegisterClass(&wc))
        return FALSE;

    hinst = hinstance;

    // Create the main window. Set the hmenu parameter to NULL so
    // that the system uses the class menu for the window.

    hwnd = CreateWindow("MainWClass", "Sample Application",
        WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
        CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hinstance,
        NULL);

    if (hwnd == NULL)
        return FALSE;

    // Make the window visible and send a WM_PAINT message to the
    // window procedure.

    ShowWindow(hwnd, nCmdShow);
    UpdateWindow(hwnd);

    // Start the main message loop.

    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return msg.wParam;
        UNREFERENCED_PARAMETER(hPrevInstance);
}

LRESULT APIENTRY MainWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{

    switch (uMsg)
    {
        // Process other window messages.

        case WM_COMMAND:

            // Test for the identifier of a command item.

            switch(LOWORD(wParam))
            {
                case IDM_FI_OPEN:
                    DoFileOpen();   // application-defined
                    break;

                case IDM_FI_CLOSE:
                    DoFileClose();  // application-defined
                    break;
                // Process other menu commands.

                default:
                    break;

            }
            return 0;

        // Process other window messages.

        default:
            return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }
    return NULL;
}


Creating a Shortcut Menu

To use a shortcut menu in an application, pass its handle to the TrackPopupMenuEx function. An application typically calls TrackPopupMenuEx in a window procedure in response to a user-generated message, such as WM_LBUTTONDOWN or WM_KEYDOWN.

In addition to the pop-up menu handle, TrackPopupMenuEx requires that you specify the handle to the owner window, the position of the shortcut menu (in screen coordinates), and the mouse button that the user can use to choose an item.

The older TrackPopupMenu function is still supported, but new applications should use the TrackPopupMenuEx function. The TrackPopupMenuEx function requires the same parameters as TrackPopupMenu, but also lets you specify a portion of the screen that the menu should not obscure. An application typically calls these functions in a window procedure when processing the WM_CONTEXTMENU message.

You can specify the position of a shortcut menu by providing x- and y-coordinates along with the TPM_CENTERALIGN, TPM_LEFTALIGN, or TPM_RIGHTALIGN flag. The flag specifies the position of the shortcut menu relative to the x- and y-coordinates.

You should permit the user to choose an item from a shortcut menu by using the same mouse button used to display the menu. To do this, specify either TPM_LEFTBUTTON or TPM_RIGHTBUTTON flag to indicate which mouse button the user can use to choose a menu item.


Processing the WM_CONTEXTMENU Message

The WM_CONTEXTMENU message is generated when an application's window procedure passes the WM_RBUTTONUP or WM_NCRBUTTONUP message to the DefWindowProc function. The application can process this message to display a shortcut menu appropriate to a specific portion of its screen. If the application does not display a shortcut menu, it should pass the message to DefWindowProc for default handling.

Following is an example of WM_CONTEXTMENU message processing as it might appear in an application's window procedure. The low-order and high-order ints of the lParam parameter specify the screen coordinates of the mouse when the right mouse button is released (note that these coordinates can take negative values on systems with multiple monitors). The application-defined OnContextMenu function returns TRUE if it displays a context menu, or FALSE if it does not.

case WM_CONTEXTMENU:
    if (!OnContextMenu(hwnd, GET_X_LPARAM(lParam),
              GET_Y_LPARAM(lParam)))
        return DefWindowProc(hwnd, uMsg, wParam, lParam);
    break;

The following application-defined OnContextMenu function displays a shortcut menu if the specified mouse position is within the window's client area. A more sophisticated function might display one of several different menus, depending on which portion of the client area is specified. To actually display the shortcut menu, this example calls an application-defined function called DisplayContextMenu. For a description of this function, see Displaying a Shortcut Menu.

BOOL WINAPI OnContextMenu(HWND hwnd, int x, int y)
{
    RECT rc;                    // client area of window
    POINT pt = { x, y };        // location of mouse click

    // Get the bounding rectangle of the client area.

    GetClientRect(hwnd, &rc);

    // Convert the mouse position to client coordinates.

    ScreenToClient(hwnd, &pt);

    // If the position is in the client area, display a
    // shortcut menu.

    if (PtInRect(&rc, pt))
    {
        ClientToScreen(hwnd, &pt);
        DisplayContextMenu(hwnd, pt);
        return TRUE;
    }

    // Return FALSE if no menu is displayed.

    return FALSE;
}


Creating a Shortcut Font-Attributes Menu

The example in this section contains portions of code from an application that creates and displays a shortcut menu that enables the user to set fonts and font attributes. The application displays the menu in the client area of its main window whenever the user clicks the left mouse button.

Here is the menu template for the shortcut menu that is provided in the application's resource-definition file.

PopupMenu MENU
BEGIN
  POPUP "Dummy Popup"
    BEGIN
      POPUP "Fonts"
        BEGIN
          MENUITEM "Courier",     IDM_FONT_COURIER
          MENUITEM "Times Roman", IDM_FONT_TMSRMN
          MENUITEM "Swiss",       IDM_FONT_SWISS
          MENUITEM "Helvetica",   IDM_FONT_HELV
          MENUITEM "Old English", IDM_FONT_OLDENG
        END
      POPUP "Sizes"
        BEGIN
          MENUITEM "7",  IDM_SIZE_7
          MENUITEM "8",  IDM_SIZE_8
          MENUITEM "9",  IDM_SIZE_9
          MENUITEM "10", IDM_SIZE_10
          MENUITEM "11", IDM_SIZE_11
          MENUITEM "12", IDM_SIZE_12
          MENUITEM "14", IDM_SIZE_14
        END
      POPUP "Styles"
        BEGIN
          MENUITEM "Bold",        IDM_STYLE_BOLD
          MENUITEM "Italic",      IDM_STYLE_ITALIC
          MENUITEM "Strike Out",  IDM_STYLE_SO
          MENUITEM "Superscript", IDM_STYLE_SUPER
          MENUITEM "Subscript",   IDM_STYLE_SUB
        END
    END

END

The following example gives the window procedure and supporting functions used to create and display the shortcut menu.

LRESULT APIENTRY MenuWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    RECT rc;    // client area
    POINT pt;   // location of mouse click

    switch (uMsg)
    {
        case WM_LBUTTONDOWN:

            // Get the bounding rectangle of the client area.

            GetClientRect(hwnd, (LPRECT) &rc);

            // Get the client coordinates for the mouse click.

            pt.x = GET_X_LPARAM(lParam);
            pt.y = GET_Y_LPARAM(lParam);

            // If the mouse click took place inside the client
            // area, execute the application-defined function
            // that displays the shortcut menu.

            if (PtInRect((LPRECT) &rc, pt))
                HandlePopupMenu(hwnd, pt);
            break;
        // Process other window messages.

        default:
            return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }
    return NULL;
}

VOID APIENTRY HandlePopupMenu(HWND hwnd, POINT pt)
{
    HMENU hmenu;            // menu template
    HMENU hmenuTrackPopup;  // shortcut menu

    //  Load the menu template containing the shortcut menu from the
    // application's resources.

    hmenu = LoadMenu(hinst, "PopupMenu");
    if (hmenu == NULL)
        return;

    // Get the first shortcut menu in the menu template. This is the
    // menu that TrackPopupMenu displays.

    hmenuTrackPopup = GetSubMenu(hmenu, 0);

    // TrackPopup uses screen coordinates, so convert the
    // coordinates of the mouse click to screen coordinates.

    ClientToScreen(hwnd, (LPPOINT) &pt);

    // Draw and track the shortcut menu.

    TrackPopupMenu(hmenuTrackPopup, TPM_LEFTALIGN | TPM_LEFTBUTTON,
        pt.x, pt.y, 0, hwnd, NULL);

    // Destroy the menu.

    DestroyMenu(hmenu);
}


Displaying a Shortcut Menu

The function shown in the following example displays a shortcut menu.

The application includes a menu resource identified by the string "ShortcutExample." The menu bar simply contains a menu name. The application uses the TrackPopupMenu function to display the menu associated with this menu item. (The menu bar itself is not displayed because TrackPopupMenu requires the handle to a menu, submenu, or shortcut menu.)

VOID APIENTRY DisplayContextMenu(HWND hwnd, POINT pt)
{
    HMENU hmenu;            // top-level menu
    HMENU hmenuTrackPopup;  // shortcut menu

    // Load the menu resource.

    if ((hmenu = LoadMenu(hinst, "ShortcutExample")) == NULL)
        return;

    // TrackPopupMenu cannot display the menu bar so get
    // the handle to the first shortcut menu.

    hmenuTrackPopup = GetSubMenu(hmenu, 0);

    // Display the shortcut menu. Track the right mouse
    // button.

    TrackPopupMenu(hmenuTrackPopup,
            TPM_LEFTALIGN | TPM_RIGHTBUTTON,
            pt.x, pt.y, 0, hwnd, NULL);

    // Destroy the menu.

    DestroyMenu(hmenu);
}


Using Menu-Item Bitmaps

The system can use a bitmap instead of a text string to display a menu item. To use a bitmap, you must set the MFT_BITMAP flag for the menu item and specify the handle to the bitmap that the system should display for the menu item. This section describes how to set the MFT_BITMAP flag and retrieve the handle to a bitmap.

Applications written for 16-bit versions of Windows can set the MF_BITMAP flag with the old menu functions.


Setting the Bitmap Type Flag

The MFT_BITMAP or MF_BITMAP flag tells the system to use a bitmap rather than a text string to display a menu item. A menu item's MFT_BITMAP or MF_BITMAP flag must be set at run time; you cannot set it in the resource-definition file.

For new applications, you can use the SetMenuItemInfo or InsertMenuItem function to set the MFT_BITMAP type flag. To change a menu item from a text item to a bitmap item, use SetMenuItemInfo. To add a new bitmap item to a menu, use the InsertMenuItem function.

Applications written for earlier versions of the system can continue to use the ModifyMenu, InsertMenu, or AppendMenu functions to set the MF_BITMAP flag. To change a menu item from a text string item to a bitmap item, use ModifyMenu. To add a new bitmap item to a menu, use the MF_BITMAP flag with the InsertMenu or AppendMenu function.


Creating the Bitmap

When you set the MFT_BITMAP or MF_BITMAP type flag for a menu item, you must also specify the handle to the bitmap that the system should display for the menu item. You can provide the bitmap as a bitmap resource or create the bitmap at run time. If you use a bitmap resource, you can use the LoadBitmap function to load the bitmap and obtain its handle.

To create the bitmap at run time, use graphics device interface (GDI) functions. GDI provides several ways to create a bitmap at run time, but developers typically use the following method:

  1. Use the CreateCompatibleDC function to create a device context compatible with the device context used by the application's main window.
  2. Use the CreateCompatibleBitmap function to create a bitmap compatible with the application's main window or use the CreateBitmap function to create a monochrome bitmap.
  3. Use the SelectObject function to select the bitmap into the compatible device context.
  4. Use GDI drawing functions, such as Ellipse and LineTo, to draw an image into the bitmap.

For more information, see Bitmaps.


Adding Lines and Graphs to a Menu

The following code sample shows how to create a menu that contains menu-item bitmaps. It creates two menus. The first is a Chart menu that contains three menu-item bitmaps: a pie chart, a line chart, and a bar chart. The example demonstrates how to load these bitmaps from the application's resource file, and then use the CreatePopupMenu and AppendMenu functions to create the menu and menu items.

The second menu is a Lines menu. It contains bitmaps showing the line styles provided by the predefined pen in the system. The line-style bitmaps are created at run time by using GDI functions.

Here are the definitions of the bitmap resources in the application's resource-definition file.

PIE BITMAP pie.bmp
LINE BITMAP line.bmp
BAR BITMAP bar.bmp

Here are the relevant portions of the application's header file.

// Menu-item identifiers

#define IDM_SOLID       PS_SOLID
#define IDM_DASH        PS_DASH
#define IDM_DASHDOT     PS_DASHDOT
#define IDM_DASHDOTDOT  PS_DASHDOTDOT

#define IDM_PIE  1
#define IDM_LINE 2
#define IDM_BAR  3

// Line-type flags

#define SOLID       0
#define DOT         1
#define DASH        2
#define DASHDOT     3
#define DASHDOTDOT  4

// Count of pens

#define CPENS 5

// Chart-type flags

#define PIE  1
#define LINE 2
#define BAR  3

// Function prototypes

LRESULT APIENTRY MainWndProc(HWND, UINT, WPARAM, LPARAM);
VOID MakeChartMenu(HWND);
VOID MakeLineMenu(HWND, HPEN, HBITMAP);

The following example shows how menus and menu-item bitmaps are created in an application.

LRESULT APIENTRY MainWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{

    static HPEN hpen[CPENS];
    static HBITMAP hbmp[CPENS];
    int i;

    switch (uMsg)
    {
        case WM_CREATE:

            // Create the Chart and Line menus.

            MakeChartMenu(hwnd);
            MakeLineMenu(hwnd, hpen, hbmp);
            return 0;

        // Process other window messages.

        case WM_DESTROY:

            for (i = 0; i < CPENS; i++)
            {
                DeleteObject(hbmp[i]);
                DeleteObject(hpen[i]);
            }

            PostQuitMessage(0);
            break;

        default:
            return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }
    return NULL;
}

VOID MakeChartMenu(HWND hwnd)
{
    HBITMAP hbmpPie;    // handle to pie chart bitmap
    HBITMAP hbmpLine;   // handle to line chart bitmap
    HBITMAP hbmpBar;    // handle to bar chart bitmap
    HMENU hmenuMain;    // handle to main menu
    HMENU hmenuChart;   // handle to Chart menu

    // Load the pie, line, and bar chart bitmaps from the
    // resource-definition file.

    hbmpPie = LoadBitmap(hinst, MAKEINTRESOURCE(PIE));
    hbmpLine = LoadBitmap(hinst, MAKEINTRESOURCE(LINE));
    hbmpBar = LoadBitmap(hinst, MAKEINTRESOURCE(BAR));

    // Create the Chart menu and add it to the menu bar.
    // Append the Pie, Line, and Bar menu items to the Chart
    // menu.

    hmenuMain = GetMenu(hwnd);
    hmenuChart = CreatePopupMenu();
    AppendMenu(hmenuMain, MF_STRING | MF_POPUP, (UINT) hmenuChart,
        "Chart");
    AppendMenu(hmenuChart, MF_BITMAP, IDM_PIE, (LPCTSTR) hbmpPie);
    AppendMenu(hmenuChart, MF_BITMAP, IDM_LINE,
        (LPCTSTR) hbmpLine);
    AppendMenu(hmenuChart, MF_BITMAP, IDM_BAR, (LPCTSTR) hbmpBar);

    return;
}

VOID MakeLineMenu(HWND hwnd, HPEN phpen, HBITMAP phbmp)
{
    HMENU hmenuLines;       // handle to Lines menu
    HMENU hmenu;            // handle to main menu
    COLORREF crMenuClr;     // menu-item background color
    HBRUSH hbrBackground;   // handle to background brush
    HBRUSH hbrOld;          // handle to previous brush
    WORD wLineX;            // width of line bitmaps
    WORD wLineY;            // height of line bitmaps
    HDC hdcMain;            // handle to main window's DC
    HDC hdcLines;           // handle to compatible DC
    HBITMAP hbmpOld;        // handle to previous bitmap
    int i;                  // loop counter

    // Create the Lines menu. Add it to the menu bar.

    hmenu = GetMenu(hwnd);
    hmenuLines = CreatePopupMenu();
    AppendMenu(hmenu, MF_STRING | MF_POPUP,
        (UINT) hmenuLines, "&Lines");

    // Create a brush for the menu-item background color.

    crMenuClr = GetSysColor(COLOR_MENU);
    hbrBackground = CreateSolidBrush(crMenuClr);

    // Create a compatible device context for the line bitmaps,
    // and then select the background brush into it.

    hdcMain = GetDC(hwnd);
    hdcLines = CreateCompatibleDC(hdcMain);
    hbrOld = SelectObject(hdcLines, hbrBackground);

    // Get the dimensions of the check-mark bitmap. The width of
    // the line bitmaps will be five times the width of the
    // check-mark bitmap.

    wLineX = GetSystemMetrics(SM_CXMENUCHECK) * (WORD) 5;
    wLineY = GetSystemMetrics(SM_CYMENUCHECK);

    // Create the bitmaps and select them, one at a time, into the
    // compatible device context. Initialize each bitmap by
    // filling it with the menu-item background color.

    for (i = 0; i < CPENS; i++)
    {
        phbmp[i] = CreateCompatibleBitmap(hdcMain, wLineX, wLineY);
        if (i == 0)
            hbmpOld = SelectObject(hdcLines, phbmp[i]);
        else
            SelectObject(hdcLines, phbmp[i]);
        ExtFloodFill(hdcLines, 0, 0, crMenuClr, FLOODFILLBORDER);
    }

    // Create the pens.

    phpen[0] = CreatePen(PS_SOLID, 1, RGB(0, 0, 0));
    phpen[1] = CreatePen(PS_DOT, 1, RGB(0, 0, 0));
    phpen[2] = CreatePen(PS_DASH, 1, RGB(0, 0, 0));
    phpen[3] = CreatePen(PS_DASHDOT, 1, RGB(0, 0, 0));
    phpen[4] = CreatePen(PS_DASHDOTDOT, 1, RGB(0, 0, 0));

    // Select a pen and a bitmap into the compatible device
    // context, draw a line into the bitmap, and then append
    // the bitmap as an item in the Lines menu.

    for (i = 0; i < CPENS; i++)
    {
        SelectObject(hdcLines, phbmp[i]);
        SelectObject(hdcLines, phpen[i]);
        MoveToEx(hdcLines, 0, wLineY / 2, NULL);
        LineTo(hdcLines, wLineX, wLineY / 2);
        AppendMenu(hmenuLines, MF_BITMAP, i + 1,
            (LPCTSTR) phbmp[i]);
    }

    // Release the main window's device context and destroy the
    // compatible device context. Also, destroy the background
    // brush.

    ReleaseDC(hwnd, hdcMain);
    SelectObject(hdcLines, hbrOld);
    DeleteObject(hbrBackground);
    SelectObject(hdcLines, hbmpOld);
    DeleteDC(hdcLines);

    return;
}


Example of Menu-item Bitmaps

The example in this topic creates two menus, each containing several bitmap menu items. For each menu, the application adds a corresponding menu name to the main window's menu bar.

The first menu contains menu items showing each of three chart types: pie, line, and bar. The bitmaps for these menu items are defined as resources and are loaded by using the LoadBitmap function. Associated with this menu is a "Chart" menu name on the menu bar.

The second menu contains menu items showing each of the five line styles used with the CreatePen function: PS_SOLID, PS_DASH, PS_DOT, PS_DASHDOT, and PS_DASHDOTDOT. The application creates the bitmaps for these menu items at run time using GDI drawing functions. Associated with this menu is a "Lines" menu name on the menu bar.

Defined in the application's window procedure are two static arrays of bitmap handles. One array contains the handles of the three bitmaps used for the Chart menu. The other contains the handles of the five bitmaps used for the Lines menu. When processing the WM_CREATE message, the window procedure loads the chart bitmaps, creates the line bitmaps, and then adds the corresponding menu items. When processing the WM_DESTROY message, the window procedure deletes all of the bitmaps.

Following are the relevant portions of the application's header file.

// Menu-item identifiers

#define IDM_PIE         1
#define IDM_LINE        2
#define IDM_BAR         3

#define IDM_SOLID       4
#define IDM_DASH        5
#define IDM_DASHDOT     6
#define IDM_DASHDOTDOT  7

// Number of items on the Chart and Lines menus

#define C_LINES         5
#define C_CHARTS        3

// Bitmap resource identifiers

#define IDB_PIE         1
#define IDB_LINE        2
#define IDB_BAR         3

// Dimensions of the line bitmaps

#define CX_LINEBMP      40
#define CY_LINEBMP      10

Following are the relevant portions of the window procedure. The window procedure performs most of its initialization by calling the application-defined LoadChartBitmaps, CreateLineBitmaps, and AddBitmapMenu functions, described later in this topic.

LRESULT CALLBACK MainWindowProc(
        HWND hwnd,
        UINT uMsg,
        WPARAM wParam,
        LPARAM lParam
        )
{
    static HBITMAP aHbmLines[C_LINES];
    static HBITMAP aHbmChart[C_CHARTS];
    int i;

    switch (uMsg)
    {
        case WM_CREATE:

             // Call application-defined functions to load the
             // bitmaps for the Chart menu and create those for
             // the Lines menu.

            LoadChartBitmaps(aHbmChart);
            CreateLineBitmaps(aHbmLines);

             // Call an application-defined function to create
             // menus containing the bitmap menu items. The function
             // also adds a menu name to the window's menu bar.

            AddBitmapMenu(
                    hwnd,      // menu bar's owner window
                    "&Chart",  // text of menu name on menu bar
                    IDM_PIE,   // ID of first item on menu
                    aHbmChart, // array of bitmap handles
                    C_CHARTS   // number of items on menu
                    );
            AddBitmapMenu(hwnd, "&Lines", IDM_SOLID,
                    aHbmLines, C_LINES);
            break;

        case WM_DESTROY:
            for (i = 0; i < C_LINES; i++)
                DeleteObject(aHbmLines[i]);
            for (i = 0; i < C_CHARTS; i++)
                DeleteObject(aHbmChart[i]);
            PostQuitMessage(0);
            break;

        // Process additional messages here.

        default:
            return (DefWindowProc(hwnd, uMsg, wParam, lParam));
    }
    return 0;
}

The application-defined LoadChartBitmaps function loads the bitmap resources for the chart menu by calling the LoadBitmap function, as follows.

VOID WINAPI LoadChartBitmaps(HBITMAP *paHbm)
{
    paHbm[0] = LoadBitmap(g_hinst, MAKEINTRESOURCE(IDB_PIE));
    paHbm[1] = LoadBitmap(g_hinst, MAKEINTRESOURCE(IDB_LINE));
    paHbm[2] = LoadBitmap(g_hinst, MAKEINTRESOURCE(IDB_BAR));
}

The application-defined CreateLineBitmaps function creates the bitmaps for the Lines menu by using GDI drawing functions. The function creates a memory device context (DC) with the same properties as the desktop window's DC. For each line style, the function creates a bitmap, selects it into the memory DC, and draws in it.

VOID WINAPI CreateLineBitmaps(HBITMAP *paHbm)
{
    HWND hwndDesktop = GetDesktopWindow();
    HDC hdcDesktop = GetDC(hwndDesktop);
    HDC hdcMem = CreateCompatibleDC(hdcDesktop);
    COLORREF clrMenu = GetSysColor(COLOR_MENU);
    HBRUSH hbrOld;
    HPEN hpenOld;
    HBITMAP hbmOld;
    int fnDrawMode;
    int i;

     // Create a brush using the menu background color,
     // and select it into the memory DC.

    hbrOld = SelectObject(hdcMem, CreateSolidBrush(clrMenu));

     // Create the bitmaps. Select each one into the memory
     // DC that was created and draw in it.

    for (i = 0; i < C_LINES; i++)
    {
        // Create the bitmap and select it into the DC.

        paHbm[i] = CreateCompatibleBitmap(hdcDesktop,
                CX_LINEBMP, CY_LINEBMP);
        hbmOld = SelectObject(hdcMem, paHbm[i]);

        // Fill the background using the brush.

        PatBlt(hdcMem, 0, 0, CX_LINEBMP, CY_LINEBMP, PATCOPY);

        // Create the pen and select it into the DC.

        hpenOld = SelectObject(hdcMem,
                CreatePen(PS_SOLID + i, 1, RGB(0, 0, 0)));

         // Draw the line. To preserve the background color where
         // the pen is white, use the R2_MASKPEN drawing mode.

        fnDrawMode = SetROP2(hdcMem, R2_MASKPEN);
        MoveToEx(hdcMem, 0, CY_LINEBMP / 2, NULL);
        LineTo(hdcMem, CX_LINEBMP, CY_LINEBMP / 2);
        SetROP2(hdcMem, fnDrawMode);

        // Delete the pen, and select the old pen and bitmap.

        DeleteObject(SelectObject(hdcMem, hpenOld));
        SelectObject(hdcMem, hbmOld);
    }

    // Delete the brush and select the original brush.

    DeleteObject(SelectObject(hdcMem, hbrOld));

    // Delete the memory DC and release the desktop DC.

    DeleteDC(hdcMem);
    ReleaseDC(hwndDesktop, hdcDesktop);
}

The application-defined AddBitmapMenu function creates a menu and adds the specified number of bitmap menu items to it. Then it adds a corresponding menu name to the specified window's menu bar.

VOID WINAPI AddBitmapMenu(
        HWND hwnd,          // window that owned the menu bar
        LPSTR lpszText,     // text of menu name on menu bar
        UINT uID,           // ID of first bitmap menu item
        HBITMAP *paHbm,     // bitmaps for the menu items
        int cItems)         // number bitmap menu items
{
    HMENU hmenuBar = GetMenu(hwnd);
    HMENU hmenuPopup = CreatePopupMenu();
    MENUITEMINFO mii;
    int i;

    // Add the bitmap menu items to the menu.

    for (i = 0; i < cItems; i++)
    {
        mii.fMask = MIIM_ID | MIIM_TYPE | MIIM_DATA;
        mii.fType = MFT_BITMAP;
        mii.wID = uID + i;
        mii.dwTypeData = (LPSTR) (paHbm[i]);
        InsertMenuItem(hmenuPopup, i, TRUE, &mii);
    }

    // Add a menu name to the menu bar.

    mii.fMask = MIIM_TYPE | MIIM_DATA | MIIM_SUBMENU;
    mii.fType = MFT_STRING;
    mii.hSubMenu = hmenuPopup;
    mii.dwTypeData = lpszText;
    InsertMenuItem(hmenuBar,
        GetMenuItemCount(hmenuBar), TRUE, &mii);
}


Creating Owner-Drawn Menu Items

If you need complete control over the appearance of a menu item, you can use an owner-drawn menu item in your application. This section describes the steps involved in creating and using an owner-drawn menu item.


Setting the Owner-Drawn Flag

You cannot define an owner-drawn menu item in your application's resource-definition file. Instead, you must create a new menu item or modify an existing one by using the MFT_OWNERDRAW menu flag.

You can use the InsertMenuItem or SetMenuItemInfo function to specify an owner-drawn menu item. Use InsertMenuItem to insert a new menu item at the specified position in a menu bar or menu. Use SetMenuItemInfo to change the contents of a menu.

When calling these two functions, you must specify the address of a MENUITEMINFO structure, giving the properties of the new menu item or the properties you want to change for an existing menu item. To make an item an owner-drawn item, specify the MIIM_TYPE value for the fMask member and the MFT_OWNERDRAW value for the fType member.

By setting the appropriate members of the MENUITEMINFO structure, you can associate an application-defined value, which is called item data, with each menu item. To do so, specify the MIIM_DATA value for the fMask member and the application-defined value for the dwItemData member.

You can use item data with any type of menu item, but it is particularly useful for owner-drawn items. For example, suppose a structure contains information used to draw a menu item. An application might use the item data for a menu item to store a pointer to the structure. The item data is sent to the menu's owner window with the WM_MEASUREITEM and WM_DRAWITEM messages. To retrieve the item data for a menu at any time, use the GetMenuItemInfo function.

Applications written for earlier versions of the system can continue to call AppendMenu, InsertMenu, or ModifyMenu to assign the MF_OWNERDRAW flag to an owner-drawn menu item.

When you call any of these three functions, you can pass a 32-bit value as the lpNewItem parameter. This value can represent any information that is meaningful to your application, and that will be available to your application when the item is to be displayed. For example, the value could contain a pointer to a structure; the structure, in turn, might contain a text string and the handle to a logical font that your application will use to draw the string.


Owner-Drawn Menus and the WM_MEASUREITEM Message

Before the system displays an owner-drawn menu item for the first time, it sends the WM_MEASUREITEM message to the window procedure of the window that owns the item's menu. This message contains a pointer to a MEASUREITEMSTRUCT structure that identifies the item and contains the item data that an application may have assigned to it. The window procedure must fill the itemWidth and itemHeight members of the structure before returning from processing the message. The system uses the information in these members when creating the bounding rectangle in which an application draws the menu item. It also uses the information to detect when the user chooses the item.


Owner-Drawn Menus and the WM_DRAWITEM Message

Whenever the item must be drawn (for example, when it is first displayed or when the user selects it), the system sends the WM_DRAWITEM message to the window procedure of the menu's owner window. This message contains a pointer to a DRAWITEMSTRUCT structure, which contains information about the item, including the item data that an application may have assigned to it. In addition, DRAWITEMSTRUCT contains flags that indicate the state of the item (such as whether it is grayed or checked) as well as a bounding rectangle and a device context that the application uses to draw the item.

An application must do the following while processing the WM_DRAWITEM message:

  1. Determine the type of drawing that is necessary. To do so, check the itemAction member of the DRAWITEMSTRUCT structure.
  2. Draw the menu item appropriately, using the bounding rectangle and device context obtained from the DRAWITEMSTRUCT structure. The application must draw only within the bounding rectangle. For performance reasons, the system does not clip portions of the image that are drawn outside the rectangle.
  3. Restore all GDI objects selected for the menu item's device context.

If the user selects the menu item, the system sets the itemAction member of the DRAWITEMSTRUCT structure to the ODA_SELECT value and sets the ODS_SELECTED value in the itemState member. This is an application's cue to redraw the menu item to indicate that it is selected.


Owner-Drawn Menus and the WM_MENUCHAR Message

Menus other than owner-drawn menus can specify a menu mnemonic by inserting an underscore next to a character in the menu string. This allows the user to select the menu by typing alt and the menu mnemonic character. In owner-drawn menus, however, you cannot specify a menu mnemonic in this manner. Instead, your application must process the WM_MENUCHAR message to provide owner-drawn menus with menu mnemonics.

The WM_MENUCHAR message is sent when the user types a menu mnemonic that does not match any of the predefined mnemonics of the current menu. The value contained in wParam specifies the ASCII character that corresponds to the key the user pressed with the alt key. The low-order word of lParam specifies the type of the selected menu and can be on of the following values:

  • MF_POPUP if the current menu is a submenu.
  • MF_SYSMENU if the menu is the system menu.

The high-order word of lParam contains the menu handle to the current menu. The window with the owner-drawn menus can process WM_MENUCHAR as follows:

case WM_MENUCHAR:
      nIndex = Determine index of menu item to be selected from
               character that was typed and handle to the current
               menu.
      return MAKELRESULT(nIndex, 2);

The two in the high-order word of the return value informs the system that the low-order word of the return value contains the zero-based index of the menu item to be selected.

The following constants (defined starting with Windows 95 and Windows NT version 4.0) correspond to the possible return values from the WM_MENUCHAR message:

Constant | Value | Meaning
MNC_IGNORE | 0 | The system should discard the character the user pressed and create a short beep on the system speaker.
MNC_CLOSE | 1 | The system should close the active menu.
MNC_EXECUTE | 2 | The system should choose the item specified in the low-order word of the return value. The owner window receives a WM_COMMAND message.
MNC_SELECT | 3 | The system should select the item specified in the low-order word of the return value.


Setting Fonts for Menu-Item Text Strings

This topic contains an example from an application that uses owner-drawn menu items in a menu. The menu contains items that set the attributes of the current font, and the items are displayed using the appropriate font attribute.

Here is how the menu is defined in the resource-definition file. Note that the strings for the Regular, Bold, Italic, and Underline menu items are assigned at run time, so their strings are empty in the resource-definition file.

MainMenu MENU
BEGIN
    POPUP   "&Character"
    BEGIN
        MENUITEM    "",    IDM_REGULAR
        MENUITEM SEPARATOR
        MENUITEM    "",    IDM_BOLD
        MENUITEM    "",    IDM_ITALIC
        MENUITEM    "",    IDM_ULINE
    END
END

The application's window procedure processes the messages involved in using owner-drawn menu items. The application uses the WM_CREATE message to do the following:

  • Set the MF_OWNERDRAW flag for the menu items.
  • Set the text strings for the menu items.
  • Obtain handles of the fonts used to draw the items.
  • Obtain the text and background color values for selected menu items.

The text strings and font handles are stored in an array of application-defined MYITEM structures. The application-defined GetAFont function creates a font that corresponds to the given font attribute and returns the handle to the font. The handles are destroyed during the processing of the WM_DESTROY message.

During the processing of the WM_MEASUREITEM message, the example gets the width and height of a menu-item string and copies these values into the MEASUREITEMSTRUCT structure. The system uses the width and height values to calculate the size of the menu.

During the processing of the WM_DRAWITEM message, the menu item's string is drawn with room left next to the string for the check-mark bitmap. If the user selects the item, the selected text and background colors are used to draw the item.

LRESULT APIENTRY MainWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{

    typedef struct _MYITEM
    {
        HFONT hfont;
        LPSTR psz;
    } MYITEM;             // structure for item font and string

    MYITEM *pmyitem;      // pointer to item's font and string
    static MYITEM myitem[CITEMS];   // array of MYITEMS
    static HMENU hmenu;             // handle to main menu
    static COLORREF crSelText;  // text color of selected item
    static COLORREF crSelBkgnd; // background color of selected item
    COLORREF crText;            // text color of unselected item
    COLORREF crBkgnd;           // background color unselected item
    LPMEASUREITEMSTRUCT lpmis;  // pointer to item of data
    LPDRAWITEMSTRUCT lpdis;     // pointer to item drawing data
    HDC hdc;                    // handle to screen DC
    SIZE size;                  // menu-item text extents
    WORD wCheckX;               // check-mark width
    int nTextX;                 // width of menu item
    int nTextY;                 // height of menu item
    int i;                      // loop counter
    HFONT hfontOld;             // handle to old font
    BOOL fSelected = FALSE;     // menu-item selection flag

    switch (uMsg)
    {
        case WM_CREATE:

            // Modify the Regular, Bold, Italic, and Underline
            // menu items to make them owner-drawn items. Associate
            // a MYITEM structure with each item to contain the
            // string and font handle for each item.

            hmenu = GetMenu(hwnd);
            ModifyMenu(hmenu, IDM_REGULAR, MF_BYCOMMAND |
                MF_CHECKED | MF_OWNERDRAW, IDM_REGULAR,
                (LPTSTR) &myitem[REGULAR]);
            ModifyMenu(hmenu, IDM_BOLD, MF_BYCOMMAND |
                MF_OWNERDRAW, IDM_BOLD, (LPTSTR) &myitem[BOLD]);
            ModifyMenu(hmenu, IDM_ITALIC, MF_BYCOMMAND |
                MF_OWNERDRAW, IDM_ITALIC,
                (LPTSTR) &myitem[ITALIC]);
            ModifyMenu(hmenu, IDM_ULINE, MF_BYCOMMAND |
                MF_OWNERDRAW, IDM_ULINE, (LPTSTR) &myitem[ULINE]);

            // Retrieve each item's font handle and copy it into
            // the hfont member of each item's MYITEM structure.
            // Also, copy each item's string into the structures.

            myitem[REGULAR].hfont = GetAFont(REGULAR);
            myitem[REGULAR].psz = "Regular";
            myitem[BOLD].hfont = GetAFont(BOLD);
            myitem[BOLD].psz = "Bold";
            myitem[ITALIC].hfont = GetAFont(ITALIC);
            myitem[ITALIC].psz = "Italic";
            myitem[ULINE].hfont = GetAFont(ULINE);
            myitem[ULINE].psz = "Underline";

            // Retrieve the text and background colors of the
            // selected menu text.

            crSelText = GetSysColor(COLOR_HIGHLIGHTTEXT);
            crSelBkgnd = GetSysColor(COLOR_HIGHLIGHT);

            return 0;

        case WM_MEASUREITEM:

            // Retrieve a device context for the main window.

            hdc = GetDC(hwnd);

            // Retrieve pointers to the menu item's
            // MEASUREITEMSTRUCT structure and MYITEM structure.

            lpmis = (LPMEASUREITEMSTRUCT) lParam;
            pmyitem = (MYITEM *) lpmis->itemData;

            // Select the font associated with the item into
            // the main window's device context.

            hfontOld = SelectObject(hdc, pmyitem->hfont);

            // Retrieve the width and height of the item's string,
            // and then copy the width and height into the
            // MEASUREITEMSTRUCT structure's itemWidth and
            // itemHeight members.

            GetTextExtentPoint32(hdc, pmyitem->psz,
                lstrlen(pmyitem->psz), &size);
            lpmis->itemWidth = size.cx;
            lpmis->itemHeight = size.cy;

            // Select the old font back into the device context,
            // and then release the device context.

            SelectObject(hdc, hfontOld);
            ReleaseDC(hwnd, hdc);

            return TRUE;

            break;

        case WM_DRAWITEM:

            // Get pointers to the menu item's DRAWITEMSTRUCT
            // structure and MYITEM structure.

            lpdis = (LPDRAWITEMSTRUCT) lParam;
            pmyitem = (MYITEM *) lpdis->itemData;

            // If the user has selected the item, use the selected
            // text and background colors to display the item.

            if (lpdis->itemState & ODS_SELECTED)
            {
                crText = SetTextColor(lpdis->hDC, crSelText);
                crBkgnd = SetBkColor(lpdis->hDC, crSelBkgnd);
                fSelected = TRUE;
            }

            // Remember to leave space in the menu item for the
            // check-mark bitmap. Retrieve the width of the bitmap
            // and add it to the width of the menu item.

            wCheckX = GetSystemMetrics(SM_CXMENUCHECK);
            nTextX = wCheckX + lpdis->rcItem.left;
            nTextY = lpdis->rcItem.top;

            // Select the font associated with the item into the
            // item's device context, and then draw the string.

            hfontOld = SelectObject(lpdis->hDC, pmyitem->hfont);
            ExtTextOut(lpdis->hDC, nTextX, nTextY, ETO_OPAQUE,
                &lpdis->rcItem, pmyitem->psz,
                lstrlen(pmyitem->psz), NULL);

            // Select the previous font back into the device
            // context.

            SelectObject(lpdis->hDC, hfontOld);

            // Return the text and background colors to their
            // normal state (not selected).

            if (fSelected)
            {
                SetTextColor(lpdis->hDC, crText);
                SetBkColor(lpdis->hDC, crBkgnd);
            }

            return TRUE;

        // Process other messages.

        case WM_DESTROY:

            // Destroy the menu items' font handles.

            for (i = 0; i < CITEMS; i++)
                DeleteObject(myitem[i].hfont);

            PostQuitMessage(0);
            break;

        default:
            return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }
    return NULL;
}

HFONT GetAFont(int fnFont)
{
    static LOGFONT lf;  // structure for font information

    // Get a handle to the ANSI fixed-pitch font, and copy
    // information about the font to a LOGFONT structure.

    GetObject(GetStockObject(ANSI_FIXED_FONT), sizeof(LOGFONT),
        &lf);

    // Set the font attributes, as appropriate.

    if (fnFont == BOLD)
        lf.lfWeight = FW_BOLD;
    else
        lf.lfWeight = FW_NORMAL;

    lf.lfItalic = (fnFont == ITALIC);
    lf.lfItalic = (fnFont == ULINE);

    // Create the font, and then return its handle.

    return CreateFont(lf.lfHeight, lf.lfWidth,
        lf.lfEscapement, lf.lfOrientation, lf.lfWeight,
        lf.lfItalic, lf.lfUnderline, lf.lfStrikeOut, lf.lfCharSet,
        lf.lfOutPrecision, lf.lfClipPrecision, lf.lfQuality,
        lf.lfPitchAndFamily, lf.lfFaceName);
}


Example of Owner-Drawn Menu Items

The example in this topic uses owner-drawn menu items in a menu. The menu items select specific font attributes, and the application displays each menu item using a font that has the corresponding attribute. For example, the Italic menu item is displayed in an italic font. The Character menu name on the menu bar opens the menu.

The menu bar and drop-down menu are defined initially by an extended menu-template resource. Because a menu template cannot specify owner-drawn items, the menu initially contains four text menu items with the following strings: "Regular," "Bold," "Italic," and "Underline." The application's window procedure changes these to owner-drawn items when it processes the WM_CREATE message. When it receives the WM_CREATE message, the window procedure calls the application-defined OnCreate function, which performs the following steps for each menu item:

  1. Allocates an application-defined MYITEM structure.
  2. Gets the text of the menu item and saves it in the application-defined MYITEM structure.
  3. Creates the font used to display the menu item and saves its handle in the application-defined MYITEM structure.
  4. Changes the menu item type to MFT_OWNERDRAW and saves a pointer to the application-defined MYITEM structure as item data.

Because a pointer to each application-defined MYITEM structure is saved as item data, it is passed to the window procedure in conjunction with the WM_MEASUREITEM and WM_DRAWITEM messages for the corresponding menu item. The pointer is contained in the itemData member of both the MEASUREITEMSTRUCT and DRAWITEMSTRUCT structures.

A WM_MEASUREITEM message is sent for each owner-drawn menu item the first time it is displayed. The application processes this message by selecting the font for the menu item into a device context and then determining the space required to display the menu item text in that font. The font and menu item text are both specified by the menu item's MYITEM structure (the structure defined by the application). The application determines the size of the text by using the GetTextExtentPoint32 function.

The window procedure processes the WM_DRAWITEM message by displaying the menu item text in the appropriate font. The font and menu item text are both specified by the menu item's MYITEM structure. The application selects text and background colors appropriate to the menu item's state.

The window procedure processes the WM_DESTROY message to destroy fonts and free memory. The application deletes the font and frees the application-defined MYITEM structure for each menu item.

Following are the relevant portions of the application's header file.

// Menu-item identifiers for the Character menu

#define IDM_CHARACTER 10
#define IDM_REGULAR   11
#define IDM_BOLD      12
#define IDM_ITALIC    13
#define IDM_UNDERLINE 14

// Structure associated with menu items

typedef struct tagMYITEM
{
    HFONT hfont;
    int   cchItemText;
    char  szItemText[1];
} MYITEM;

#define CCH_MAXITEMTEXT 256

Following are the relevant portions of the application's window procedure and its associated functions.

LRESULT CALLBACK MainWindowProc(
        HWND hwnd,
        UINT uMsg,
        WPARAM wParam,
        LPARAM lParam
        )
{
    switch (uMsg)
    {
        case WM_CREATE:
            if (!OnCreate(hwnd))
                return -1;
            break;

        case WM_DESTROY:
            OnDestroy(hwnd);
            PostQuitMessage(0);
            break;

        case WM_MEASUREITEM:
            OnMeasureItem(hwnd, (LPMEASUREITEMSTRUCT) lParam);
            return TRUE;

        case WM_DRAWITEM:
            OnDrawItem(hwnd, (LPDRAWITEMSTRUCT) lParam);
            return TRUE;

        // Additional message processing goes here.

        default:
            return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }
    return 0;
}

BOOL WINAPI OnCreate(HWND hwnd)
{
    HMENU hmenuBar = GetMenu(hwnd);
    HMENU hmenuPopup;
    MENUITEMINFO mii;
    UINT uID;
    MYITEM *pMyItem;

    // Get the handle to the pop-up menu.

    mii.fMask = MIIM_SUBMENU;     // information to get
    GetMenuItemInfo(hmenuBar, IDM_CHARACTER, FALSE, &mii);
    hmenuPopup = mii.hSubMenu;

    // Modify each menu item. Assume that the IDs IDM_REGULAR
    // through IDM_UNDERLINE are consecutive numbers.

    for (uID = IDM_REGULAR; uID <= IDM_UNDERLINE; uID++)
    {
         // Allocate an item structure, leaving space for a
         // string of up to CCH_MAXITEMTEXT characters.

        pMyItem = (MYITEM *) LocalAlloc(LMEM_FIXED,
                sizeof(MYITEM) + CCH_MAXITEMTEXT);

        // Save the item text in the item structure.

        mii.fMask = MIIM_TYPE;
        mii.dwTypeData = pMyItem->szItemText;
        mii.cch = CCH_MAXITEMTEXT;
        GetMenuItemInfo(hmenuPopup, uID, FALSE, &mii);
        pMyItem->cchItemText = mii.cch;

        // Reallocate the structure to the minimum required size.

        pMyItem = (MYITEM *) LocalReAlloc(pMyItem,
                sizeof(MYITEM) + mii.cch, LMEM_MOVEABLE);

        // Create the font used to draw the item.

        pMyItem->hfont = CreateMenuItemFont(uID);

        // Change the item to an owner-drawn item, and save
        // the address of the item structure as item data.

        mii.fMask = MIIM_TYPE | MIIM_DATA;
        mii.fType = MFT_OWNERDRAW;
        mii.dwItemData = (DWORD) pMyItem;
        SetMenuItemInfo(hmenuPopup, uID, FALSE, &mii);
    }
    return TRUE;
}

HFONT CreateMenuItemFont(UINT uID)
{
    LOGFONT lf;

    ZeroMemory(&lf, sizeof(lf));
    lf.lfHeight = 20;
    lstrcpy(lf.lfFaceName, "Times New Roman");

    switch (uID)
    {
        case IDM_BOLD:
            lf.lfWeight = FW_HEAVY;
            break;

        case IDM_ITALIC:
            lf.lfItalic = TRUE;
            break;

        case IDM_UNDERLINE:
            lf.lfUnderline = TRUE;
            break;
    }
    return CreateFontIndirect(&lf);
}

VOID WINAPI OnDestroy(HWND hwnd)
{
    HMENU hmenuBar = GetMenu(hwnd);
    HMENU hmenuPopup;
    MENUITEMINFO mii;
    UINT uID;
    MYITEM *pMyItem;

    // Get the handle to the menu.

    mii.fMask = MIIM_SUBMENU;     // information to get
    GetMenuItemInfo(hmenuBar, IDM_CHARACTER, FALSE, &mii);
    hmenuPopup = mii.hSubMenu;

    // Free resources associated with each menu item.

    for (uID = IDM_REGULAR; uID <= IDM_UNDERLINE; uID++)
    {
        // Get the item data.

        mii.fMask = MIIM_DATA;
        GetMenuItemInfo(hmenuPopup, uID, FALSE, &mii);
        pMyItem = (MYITEM *) mii.dwItemData;

        // Destroy the font and free the item structure.

        DeleteObject(pMyItem->hfont);
        LocalFree(pMyItem);
    }
}

VOID WINAPI OnMeasureItem(HWND hwnd, LPMEASUREITEMSTRUCT lpmis)
{
    MYITEM *pMyItem = (MYITEM *) lpmis->itemData;
    HDC hdc = GetDC(hwnd);
    HFONT hfntOld = SelectObject(hdc, pMyItem->hfont);
    SIZE size;

    GetTextExtentPoint32(hdc, pMyItem->szItemText,
            pMyItem->cchItemText, &size);

    lpmis->itemWidth = size.cx;
    lpmis->itemHeight = size.cy;

    SelectObject(hdc, hfntOld);
    ReleaseDC(hwnd, hdc);
}

VOID WINAPI OnDrawItem(HWND hwnd, LPDRAWITEMSTRUCT lpdis)
{
    MYITEM *pMyItem = (MYITEM *) lpdis->itemData;
    COLORREF clrPrevText, clrPrevBkgnd;
    HFONT hfntPrev;
    int x, y;

    // Set the appropriate foreground and background colors.

    if (lpdis->itemState & ODS_SELECTED)
    {
        clrPrevText = SetTextColor(lpdis->hDC,
                GetSysColor(COLOR_HIGHLIGHTTEXT));
        clrPrevBkgnd = SetBkColor(lpdis->hDC,
                GetSysColor(COLOR_HIGHLIGHT));
    }
    else
    {
        clrPrevText = SetTextColor(lpdis->hDC,
                GetSysColor(COLOR_MENUTEXT));
        clrPrevBkgnd = SetBkColor(lpdis->hDC,
                GetSysColor(COLOR_MENU));
    }

    // Determine where to draw and leave space for a check-mark.

    x = lpdis->rcItem.left;
    y = lpdis->rcItem.top;
    x += GetSystemMetrics(SM_CXMENUCHECK);

    // Select the font and draw the text.

    hfntPrev = SelectObject(lpdis->hDC, pMyItem->hfont);
    ExtTextOut(lpdis->hDC, x, y, ETO_OPAQUE,
            &lpdis->rcItem, pMyItem->szItemText,
            pMyItem->cchItemText, NULL);

    // Restore the original font and colors.

    SelectObject(lpdis->hDC, hfntPrev);
    SetTextColor(lpdis->hDC, clrPrevText);
    SetBkColor(lpdis->hDC, clrPrevBkgnd);
}


Using Custom Check-mark Bitmaps

The system provides a default check-mark bitmap for displaying next to a menu item that is checked. You can customize an individual menu item by providing a pair of bitmaps to replace the default check-mark bitmap. The system displays one bitmap when the item is checked and the other when it is unchecked. This section describes the steps involved in creating and using custom check-mark bitmaps.


Creating Custom Check-mark Bitmaps

A custom check-mark bitmap must be the same size as the default check-mark bitmap. You can retrieve the default check-mark size of the bitmap by calling the GetSystemMetrics function. The low-order word of this function's return value specifies the width; the high-order word specifies the height.

You can use bitmap resources to provide check-mark bitmaps. However, because the required bitmap size varies depending on the display type, you may need to resize the bitmap at run time by using the StretchBlt function. Depending on the bitmap, the distortion caused by sizing could produce unacceptable results.

Instead of using a bitmap resource, you can create a bitmap at run time by using GDI functions.

To create a bitmap at run time
  1. Use the CreateCompatibleDC function to create a device context compatible with the one used by the application's main window. The function's hdc parameter can specify either NULL or the return value from the GetDC function. CreateCompatibleDC returns the handle to the compatible device context.
  2. Use the CreateCompatibleBitmap function to create a bitmap compatible with the application's main window. This function's nWidth and nHeight parameters set the size of the bitmap; they should specify the width and height information returned by the GetSystemMetrics function. You can also use the CreateBitmap function to create a monochrome bitmap.
  3. Use the SelectObject function to select the bitmap into the compatible device context.
  4. Use GDI drawing functions, such as Ellipse and LineTo, to draw an image into the bitmap, or use functions such as BitBlt and StretchBlt to copy an image into the bitmap.

For more information, see Bitmaps.


Associating Bitmaps with a Menu Item

You associate a pair of check-mark bitmaps with a menu item by passing the handles of the bitmaps to the SetMenuItemBitmaps function. The hBitmapUnchecked parameter identifies the unchecked bitmap, and the hBitmapChecked parameter identifies the checked bitmap. If you want to remove one or both check marks from a menu item, you can set the hBitmapUnchecked or hBitmapChecked parameter, or both, to NULL.


Setting the Check-mark Attribute

The CheckMenuItem function sets a menu item's check-mark attribute to either checked or unchecked. You can specify the MF_CHECKED value to set the check-mark attribute to checked and the MF_UNCHECKED value to set it to unchecked.

You can also set the check state of a menu item by using the SetMenuItemInfo function.

Sometimes a group of menu items represents a set of mutually exclusive options. By using the CheckMenuRadioItem function, you can check one menu item while simultaneously removing the check mark from all other menu items in the group.


Simulating Check Boxes in a Menu

This topic contains an example that shows how to simulate check boxes in a menu. The example contains a Character menu whose items allow the user to set the bold, italic, and underline attributes of the current font. When a font attribute is in effect, a check mark is displayed in the check box next to the corresponding menu item; otherwise, an empty check box is displayed next to the item.

The example replaces the default check-mark bitmap with two bitmaps: a bitmap with a checked box and the bitmap with an empty box. The checked check box bitmap is displayed next to the Bold, Italic, or Underline menu item when the item's check-mark attribute is set to MF_CHECKED. The unchecked or empty check box bitmap is displayed when the check-mark attribute is set to MF_UNCHECKED.

The system provides a predefined bitmap that contains the images used for check boxes and radio buttons. The example isolates the checked and empty check boxes, copies them to two separate bitmaps, and then uses them as the checked and unchecked bitmaps for items in the Character menu.

To retrieve the handle to the system-defined check box bitmap, the example calls the LoadBitmap function, specifying NULL as the hInstance parameter and OBM_CHECKBOXES as the lpBitmapName parameter. Because the images in the bitmap are all the same size, the example can isolate them by dividing the bitmap's width and height by the number of images in its rows and columns.

The following portion of a resource-definition file shows how the menu items in the Character menu are defined. Note that no font attributes are in effect initially, so the check-mark attribute for the Regular item is set to checked and, by default, the check-mark attribute of the remaining items is set to unchecked.

#include "men3.h"

MainMenu MENU
BEGIN
    POPUP   "&Character"
    BEGIN
        MENUITEM    "&Regular",     IDM_REGULAR, CHECKED
        MENUITEM SEPARATOR
        MENUITEM    "&Bold",        IDM_BOLD
        MENUITEM    "&Italic",      IDM_ITALIC
        MENUITEM    "&Underline",   IDM_ULINE
    END
END

Here are the relevant contents of the application's header file.

// Menu-item identifiers

#define IDM_REGULAR 0x1
#define IDM_BOLD    0x2
#define IDM_ITALIC  0x4
#define IDM_ULINE   0x8

// Check-mark flags

#define CHECK   1
#define UNCHECK 2

// Font-attribute mask

#define ATTRIBMASK 0xe

// Function prototypes

LRESULT APIENTRY MainWndProc(HWND, UINT, WPARAM, LPARAM);
HBITMAP GetMyCheckBitmaps(UINT);
BYTE CheckOrUncheckMenuItem(BYTE, HMENU);

The following example shows the portions of the window procedure that create the check-mark bitmaps; set the check-mark attribute of the Bold, Italic, and Underline menu items; and destroy check-mark bitmaps.

LRESULT APIENTRY MainWndProc(HWND hwndMain, UINT uMsg, WPARAM wParam, LPARAM lParam)
{

    static HBITMAP hbmpCheck;   // handle to checked bitmap
    static HBITMAP hbmpUncheck; // handle to unchecked bitmap
    static HMENU hmenu;         // handle to main menu
    BYTE fbFontAttrib;          // font-attribute flags

    switch (uMsg)
    {
        case WM_CREATE:

            // Call the application-defined GetMyCheckBitmaps
            // function to get the predefined checked and
            // unchecked check box bitmaps.

            hbmpCheck = GetMyCheckBitmaps(CHECK);
            hbmpUncheck = GetMyCheckBitmaps(UNCHECK);

            // Set the checked and unchecked bitmaps for the menu
            // items.

            hmenu = GetMenu(hwndMain);
            SetMenuItemBitmaps(hmenu, IDM_BOLD, MF_BYCOMMAND,
                hbmpUncheck, hbmpCheck);
            SetMenuItemBitmaps(hmenu, IDM_ITALIC, MF_BYCOMMAND,
                hbmpUncheck, hbmpCheck);
            SetMenuItemBitmaps(hmenu, IDM_ULINE, MF_BYCOMMAND,
                hbmpUncheck, hbmpCheck);

            return 0;

        case WM_COMMAND:
            switch (LOWORD(wParam))
            {
                // Process the menu commands.

                case IDM_REGULAR:
                case IDM_BOLD:
                case IDM_ITALIC:
                case IDM_ULINE:

                    // CheckOrUncheckMenuItem is an application-
                    // defined function that sets the menu item
                    // check marks and returns the user-selected
                    // font attributes.

                    fbFontAttrib = CheckOrUncheckMenuItem(
                        (BYTE) LOWORD(wParam), hmenu);

                    // Set the font attributes.

                    return 0;

                // Process other command messages.

                default:
                    break;
            }

            break;

        // Process other window messages.

        case WM_DESTROY:

            // Destroy the checked and unchecked bitmaps.

            DeleteObject(hbmpCheck);
            DeleteObject(hbmpUncheck);

            PostQuitMessage(0);
            break;

        default:
            return DefWindowProc(hwndMain, uMsg, wParam, lParam);
    }
    return NULL;
}

HBITMAP GetMyCheckBitmaps(UINT fuCheck)
{
    COLORREF crBackground;  // background color
    HBRUSH hbrBackground;   // background brush
    HBRUSH hbrTargetOld;    // original background brush
    HDC hdcSource;          // source device context
    HDC hdcTarget;          // target device context
    HBITMAP hbmpCheckboxes; // handle to check-box bitmap
    BITMAP bmCheckbox;      // structure for bitmap data
    HBITMAP hbmpSourceOld;  // handle to original source bitmap
    HBITMAP hbmpTargetOld;  // handle to original target bitmap
    HBITMAP hbmpCheck;      // handle to check-mark bitmap
    RECT rc;                // rectangle for check-box bitmap
    WORD wBitmapX;          // width of check-mark bitmap
    WORD wBitmapY;          // height of check-mark bitmap

    // Get the menu background color and create a solid brush
    // with that color.

    crBackground = GetSysColor(COLOR_MENU);
    hbrBackground = CreateSolidBrush(crBackground);

    // Create memory device contexts for the source and
    // destination bitmaps.

    hdcSource = CreateCompatibleDC((HDC) NULL);
    hdcTarget = CreateCompatibleDC(hdcSource);

    // Get the size of the the system default check-mark bitmap and
    // create a compatible bitmap of the same size.

    wBitmapX = GetSystemMetrics(SM_CXMENUCHECK);
    wBitmapY = GetSystemMetrics(SM_CYMENUCHECK);

    hbmpCheck = CreateCompatibleBitmap(hdcSource, wBitmapX,
        wBitmapY);

    // Select the background brush and bitmap into the target DC.

    hbrTargetOld = SelectObject(hdcTarget, hbrBackground);
    hbmpTargetOld = SelectObject(hdcTarget, hbmpCheck);

    // Use the selected brush to initialize the background color
    // of the bitmap in the target device context.

    PatBlt(hdcTarget, 0, 0, wBitmapX, wBitmapY, PATCOPY);

    // Load the predefined check box bitmaps and select it
    // into the source DC.

    hbmpCheckboxes = LoadBitmap((HINSTANCE) NULL,
        (LPTSTR) OBM_CHECKBOXES);

    hbmpSourceOld = SelectObject(hdcSource, hbmpCheckboxes);

    // Fill a BITMAP structure with information about the
    // check box bitmaps, and then find the upper-left corner of
    // the unchecked check box or the checked check box.

    GetObject(hbmpCheckboxes, sizeof(BITMAP), &bmCheckbox);

    if (fuCheck == UNCHECK)
    {
        rc.left = 0;
        rc.right = (bmCheckbox.bmWidth / 4);
    }
    else
    {
        rc.left = (bmCheckbox.bmWidth / 4);
        rc.right = (bmCheckbox.bmWidth / 4) * 2;
    }

    rc.top = 0;
    rc.bottom = (bmCheckbox.bmHeight / 3);

    // Copy the appropriate bitmap into the target DC. If the
    // check-box bitmap is larger than the default check-mark
    // bitmap, use StretchBlt to make it fit; otherwise, just
    // copy it.

    if (((rc.right - rc.left) > (int) wBitmapX) ||
            ((rc.bottom - rc.top) > (int) wBitmapY))
    {
        StretchBlt(hdcTarget, 0, 0, wBitmapX, wBitmapY,
            hdcSource, rc.left, rc.top, rc.right - rc.left,
            rc.bottom - rc.top, SRCCOPY);
    }

    else
    {
        BitBlt(hdcTarget, 0, 0, rc.right - rc.left,
            rc.bottom - rc.top,
            hdcSource, rc.left, rc.top, SRCCOPY);
    }

    // Select the old source and destination bitmaps into the
    // source and destination DCs, and then delete the DCs and
    // the background brush.

    SelectObject(hdcSource, hbmpSourceOld);
    SelectObject(hdcTarget, hbrTargetOld);
    hbmpCheck = SelectObject(hdcTarget, hbmpTargetOld);

    DeleteObject(hbrBackground);
    DeleteObject(hdcSource);
    DeleteObject(hdcTarget);

    // Return the handle to the new check-mark bitmap.

    return hbmpCheck;
}

BYTE CheckOrUncheckMenuItem(BYTE bMenuItemID, HMENU hmenu)
{
    DWORD fdwMenu;
    static BYTE fbAttributes;

    switch (bMenuItemID)
    {
        case IDM_REGULAR:

            // Whenever the Regular menu item is selected, add a
            // check mark to it and then remove check marks from
            // any font-attribute menu items.

            CheckMenuItem(hmenu, IDM_REGULAR, MF_BYCOMMAND |
                MF_CHECKED);

            if (fbAttributes & ATTRIBMASK)
            {
                CheckMenuItem(hmenu, IDM_BOLD, MF_BYCOMMAND |
                    MF_UNCHECKED);
                CheckMenuItem(hmenu, IDM_ITALIC, MF_BYCOMMAND |
                    MF_UNCHECKED);
                CheckMenuItem(hmenu, IDM_ULINE, MF_BYCOMMAND |
                    MF_UNCHECKED);
            }
            fbAttributes = IDM_REGULAR;
            return fbAttributes;

        case IDM_BOLD:
        case IDM_ITALIC:
        case IDM_ULINE:

            // Toggle the check mark for the selected menu item and
            // set the font attribute flags appropriately.

            fdwMenu = GetMenuState(hmenu, (UINT) bMenuItemID,
                MF_BYCOMMAND);
            if (!(fdwMenu & MF_CHECKED))
            {
                CheckMenuItem(hmenu, (UINT) bMenuItemID,
                    MF_BYCOMMAND | MF_CHECKED);
                fbAttributes |= bMenuItemID;
            }
            else
            {
                CheckMenuItem(hmenu, (UINT) bMenuItemID,
                    MF_BYCOMMAND | MF_UNCHECKED);
                fbAttributes ^= bMenuItemID;
            }

            // If any font attributes are currently selected,
            // remove the check mark from the Regular menu item;
            // if no attributes are selected, add a check mark
            // to the Regular menu item.

            if (fbAttributes & ATTRIBMASK)
            {
                CheckMenuItem(hmenu, IDM_REGULAR,
                    MF_BYCOMMAND | MF_UNCHECKED);
                fbAttributes &= (BYTE) ~IDM_REGULAR;
            }
            else
            {
                CheckMenuItem(hmenu, IDM_REGULAR,
                    MF_BYCOMMAND | MF_CHECKED);
                fbAttributes = IDM_REGULAR;
            }

            return fbAttributes;
    }
}


Example of Using Custom Check-mark Bitmaps

The example in this topic assigns custom check-mark bitmaps to menu items in two menus. The menu items in the first menu specify character attributes: bold, italic, and underline. Each menu item can be either checked or unchecked. For these menu items, the example uses check-mark bitmaps that resemble the checked and unchecked states of a check box control.

The menu items in the second menu specify paragraph alignment settings: left, centered, and right. Only one of these menu items is checked at any given time. For these menu items, the example uses check-mark bitmaps that resemble the checked and unchecked states of a radio button control.

The window procedure processes the WM_CREATE message by calling the application-defined OnCreate function. OnCreate creates the four check-mark bitmaps and then assigns them to their appropriate menu items by using the SetMenuItemBitmaps function.

To create each bitmap, OnCreate calls the application-defined CreateMenuBitmaps function, specifying a pointer to a bitmap-specific drawing function. CreateMenuBitmaps creates a monochrome bitmap of the required size, selects it into a memory device context, and erases the background. Then it calls the specified drawing function to fill in the foreground.

The four application-defined drawing functions are DrawCheck, DrawUncheck, DrawRadioCheck, and DrawRadioUncheck. They draw a rectangle with an X, an empty rectangle, an ellipse containing a smaller filled ellipse, and an empty ellipse, respectively.

The window procedure processes the WM_DESTROY message by deleting the check-mark bitmaps. It retrieves each bitmap handle by using the GetMenuItemInfo function and then passes the handle to the DeleteObject function.

When the user chooses a menu item, a WM_COMMAND message is sent to the owner window. For menu items on the Character menu, the window procedure calls the application-defined CheckCharacterItem function. For items on the Paragraph menu, the window procedure calls the application-defined CheckParagraphItem function.

Each item on the Character menu can be checked and unchecked independently. Therefore, CheckCharacterItem simply switches the specified menu item's check state. First, the function calls the GetMenuItemInfo function to get the current menu item state. Then it switches the MFS_CHECKED state flag and sets the new state by calling the SetMenuItemInfo function.

Unlike character attributes, only one paragraph alignment can be selected at a time. Therefore, CheckParagraphItem checks the specified menu item and removes the check mark from all other items on the menu. To do so, it calls the CheckMenuRadioItem function.

Following are the relevant portions of the application's header file.

// Menu-item identifiers for the Character menu

#define IDM_CHARACTER 10
#define IDM_BOLD      11
#define IDM_ITALIC    12
#define IDM_UNDERLINE 13

// Menu-item identifiers for the Paragraph menu

#define IDM_PARAGRAPH 20
#define IDM_LEFT      21
#define IDM_CENTER    22
#define IDM_RIGHT     23

// Function-pointer type for drawing functions

typedef VOID (WINAPI * DRAWFUNC)(HDC hdc, SIZE size);

Following are the relevant portions of the application's window procedure and related functions.

LRESULT CALLBACK MainWindowProc(
        HWND hwnd,
        UINT uMsg,
        WPARAM wParam,
        LPARAM lParam
        )
{
    switch (uMsg)
    {
        case WM_CREATE:
            if (!OnCreate(hwnd))
                return -1;
            break;

        case WM_DESTROY:
            OnDestroy(hwnd);
            PostQuitMessage(0);
            break;

        case WM_COMMAND:
            switch (LOWORD(wParam))
            {
                case IDM_BOLD:
                case IDM_ITALIC:
                case IDM_UNDERLINE:
                    CheckCharacterItem(hwnd, LOWORD(wParam));
                    break;

                case IDM_LEFT:
                case IDM_CENTER:
                case IDM_RIGHT:
                    CheckParagraphItem(hwnd, LOWORD(wParam));
                    break;

                // Process other commands here.

            }
            break;

        // Process other messages here.

        default:
            return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }
    return 0;
}

VOID WINAPI CheckCharacterItem(HWND hwnd, UINT uID)
{
    HMENU hmenuBar = GetMenu(hwnd);
    HMENU hmenuPopup;
    MENUITEMINFO mii;

    // Get the handle to the Character menu.

    mii.fMask = MIIM_SUBMENU;  // information to get
    GetMenuItemInfo(hmenuBar, IDM_CHARACTER, FALSE, &mii);
    hmenuPopup = mii.hSubMenu;

    // Get the state of the specified menu item.

    mii.fMask = MIIM_STATE;    // information to get
    GetMenuItemInfo(hmenuPopup, uID, FALSE, &mii);

    // Toggle the checked state.

    mii.fState ^= MFS_CHECKED;
    SetMenuItemInfo(hmenuPopup, uID, FALSE, &mii);
}

VOID WINAPI CheckParagraphItem(HWND hwnd, UINT uID)
{
    HMENU hmenuBar = GetMenu(hwnd);
    HMENU hmenuPopup;
    MENUITEMINFO mii;

    // Get the handle to the Paragraph menu.

    mii.fMask = MIIM_SUBMENU;  // information to get
    GetMenuItemInfo(hmenuBar, IDM_PARAGRAPH, FALSE, &mii);
    hmenuPopup = mii.hSubMenu;

    // Check the specified item and uncheck all the others.

    CheckMenuRadioItem(
            hmenuPopup,         // handle to menu
            IDM_LEFT,           // first item in range
            IDM_RIGHT,          // last item in range
            uID,                // item to check
            MF_BYCOMMAND        // IDs, not positions
            );
}

BOOL WINAPI OnCreate(HWND hwnd)
{
    HMENU hmenuBar = GetMenu(hwnd);
    HMENU hmenuPopup;
    MENUITEMINFO mii;
    UINT uID;
    HBITMAP hbmChecked;
    HBITMAP hbmUnchecked;

    // Get the handle to the Character menu.

    mii.fMask = MIIM_SUBMENU;     // information to get
    GetMenuItemInfo(hmenuBar, IDM_CHARACTER, FALSE, &mii);
    hmenuPopup = mii.hSubMenu;

    // Create the checked and unchecked bitmaps.

    hbmChecked = CreateMenuBitmap(DrawCheck);
    hbmUnchecked = CreateMenuBitmap(DrawUncheck);

    // Set the checkmark bitmaps for each menu item.

    for (uID = IDM_BOLD; uID <= IDM_UNDERLINE; uID++)
    {
        SetMenuItemBitmaps(hmenuPopup, uID, MF_BYCOMMAND,
                hbmUnchecked, hbmChecked);
    }

    // Get the handle to the Paragraph pop-up menu.

    mii.fMask = MIIM_SUBMENU;     // information to get
    GetMenuItemInfo(hmenuBar, IDM_PARAGRAPH, FALSE, &mii);
    hmenuPopup = mii.hSubMenu;

    // Create the checked and unchecked bitmaps.

    hbmChecked = CreateMenuBitmap(DrawRadioCheck);
    hbmUnchecked = CreateMenuBitmap(DrawRadioUncheck);

    // Set the checkmark bitmaps for each menu item.

    for (uID = IDM_LEFT; uID <= IDM_RIGHT; uID++)
    {
        SetMenuItemBitmaps(hmenuPopup, uID, MF_BYCOMMAND,
                hbmUnchecked, hbmChecked);
    }

    // Initially check the IDM_LEFT paragraph item.

    CheckMenuRadioItem(hmenuPopup, IDM_LEFT, IDM_RIGHT,
            IDM_LEFT, MF_BYCOMMAND);
    return TRUE;
}

HBITMAP WINAPI CreateMenuBitmap(DRAWFUNC lpfnDraw)
{
    // Create a DC compatible with the desktop window's DC.

    HWND hwndDesktop = GetDesktopWindow();
    HDC hdcDesktop = GetDC(hwndDesktop);
    HDC hdcMem = CreateCompatibleDC(hdcDesktop);

    // Determine the required bitmap size.

    SIZE size = { GetSystemMetrics(SM_CXMENUCHECK),
                  GetSystemMetrics(SM_CYMENUCHECK) };

    // Create a monochrome bitmap and select it.

    HBITMAP hbm = CreateBitmap(size.cx, size.cy, 1, 1, NULL);
    HBITMAP hbmOld = SelectObject(hdcMem, hbm);

    // Erase the background and call the drawing function.

    PatBlt(hdcMem, 0, 0, size.cx, size.cy, WHITENESS);
    (*lpfnDraw)(hdcMem, size);

    // Clean up.

    SelectObject(hdcMem, hbmOld);
    DeleteDC(hdcMem);
    ReleaseDC(hwndDesktop, hdcDesktop);
    return hbm;
}

VOID WINAPI DrawCheck(HDC hdc, SIZE size)
{
    HBRUSH hbrOld;
    hbrOld = SelectObject(hdc, GetStockObject(NULL_BRUSH));
    Rectangle(hdc, 0, 0, size.cx, size.cy);
    MoveToEx(hdc, 0, 0, NULL);
    LineTo(hdc, size.cx, size.cy);
    MoveToEx(hdc, 0, size.cy - 1, NULL);
    LineTo(hdc, size.cx - 1, 0);
    SelectObject(hdc, hbrOld);
}

VOID WINAPI DrawUncheck(HDC hdc, SIZE size)
{
    HBRUSH hbrOld;
    hbrOld = SelectObject(hdc, GetStockObject(NULL_BRUSH));
    Rectangle(hdc, 0, 0, size.cx, size.cy);
    SelectObject(hdc, hbrOld);
}

VOID WINAPI DrawRadioCheck(HDC hdc, SIZE size)
{
    HBRUSH hbrOld;
    hbrOld = SelectObject(hdc, GetStockObject(NULL_BRUSH));
    Ellipse(hdc, 0, 0, size.cx, size.cy);
    SelectObject(hdc, GetStockObject(BLACK_BRUSH));
    Ellipse(hdc, 2, 2, size.cx - 2, size.cy - 2);
    SelectObject(hdc, hbrOld);
}

VOID WINAPI DrawRadioUncheck(HDC hdc, SIZE size)
{
    HBRUSH hbrOld;
    hbrOld = SelectObject(hdc, GetStockObject(NULL_BRUSH));
    Ellipse(hdc, 0, 0, size.cx, size.cy);
    SelectObject(hdc, hbrOld);
}

VOID WINAPI OnDestroy(HWND hwnd)
{
    HMENU hmenuBar = GetMenu(hwnd);
    HMENU hmenuPopup;
    MENUITEMINFO mii;

    // Get the handle to the Character menu.

    mii.fMask = MIIM_SUBMENU;     // information to get
    GetMenuItemInfo(hmenuBar, IDM_CHARACTER, FALSE, &mii);
    hmenuPopup = mii.hSubMenu;

    // Get the check-mark bitmaps and delete them.

    mii.fMask = MIIM_CHECKMARKS;
    GetMenuItemInfo(hmenuPopup, IDM_BOLD, FALSE, &mii);
    DeleteObject(mii.hbmpChecked);
    DeleteObject(mii.hbmpUnchecked);

    // Get the handle to the Paragraph menu.

    mii.fMask = MIIM_SUBMENU;     // information to get
    GetMenuItemInfo(hmenuBar, IDM_PARAGRAPH, FALSE, &mii);
    hmenuPopup = mii.hSubMenu;

    // Get the check-mark bitmaps and delete them.

    mii.fMask = MIIM_CHECKMARKS;
    GetMenuItemInfo(hmenuPopup, IDM_LEFT, FALSE, &mii);
    DeleteObject(mii.hbmpChecked);
    DeleteObject(mii.hbmpUnchecked);
}


Menu Reference

For convenience, this topic provides a list of menu programming elements grouped by functional area.

For alphabetic listings, see the following topics:

  • Menu Functions
  • Menu Structures
  • Menu Messages

Menu Handles

GetMenu
GetSubMenu
GetSystemMenu
IsMenu

Menu-Item Information

GetMenuItemCount
GetMenuItemID
GetMenuItemInfo
GetMenuState
SetMenuItemInfo
MENUITEMINFO

Default Menu Items

GetMenuDefaultItem
SetMenuDefaultItem

Menu-Item States

CheckMenuItem
CheckMenuRadioItem
EnableMenuItem
HiliteMenuItem
SetMenuItemBitmaps

Menu Templates

LoadMenu
LoadMenuIndirect
MENUITEMTEMPLATE
MENUITEMTEMPLATEHEADER
MENUEX_TEMPLATE_HEADER
MENUEX_TEMPLATE_ITEM

Menu Creation and Modification

AppendMenu
CreateMenu
CreatePopupMenu
DeleteMenu
DestroyMenu
DrawMenuBar
InsertMenu
InsertMenuItem
ModifyMenu
RemoveMenu
SetMenuItemInfo

Menu Display

SetMenu
TrackPopupMenu
TrackPopupMenuEx
WM_CONTEXTMENU

Menu Messages

WM_COMMAND
WM_CONTEXTMENU
WM_DRAWITEM
WM_ENTERMENULOOP
WM_EXITMENULOOP
WM_INITMENU
WM_INITMENUPOPUP
WM_MEASUREITEM
WM_MENUCHAR
WM_MENUSELECT
WM_SYSCOMMAND


Menu Functions

The following functions are used with menus.

CheckMenuRadioItem
CreateMenu
CreatePopupMenu
DeleteMenu
DestroyMenu
DrawMenuBar
EnableMenuItem
GetMenu
GetMenuDefaultItem
GetMenuItemCount
GetMenuItemID
GetMenuItemInfo
GetMenuItemRect
GetSubMenu
GetSystemMenu
HiliteMenuItem
InsertMenuItem
IsMenu
LoadMenu
LoadMenuIndirect
MenuItemFromPoint
RemoveMenu
SetMenu
SetMenuDefaultItem
SetMenuItemBitmaps
SetMenuItemInfo
TrackPopupMenu
TrackPopupMenuEx

Obsolete Functions

AppendMenu
CheckMenuItem
GetMenuCheckMarkDimensions
GetMenuState
GetMenuString
InsertMenu
ModifyMenu


AppendMenu

The AppendMenu function appends a new item to the end of the specified menu bar, drop-down menu, submenu, or shortcut menu. You can use this function to specify the content, appearance, and behavior of the menu item.

The AppendMenu function has been superseded by the InsertMenuItem function. You can still use AppendMenu, however, if you do not need any of the extended features of InsertMenuItem.

BOOL AppendMenu(
  HMENU hMenu,      // handle to menu to be changed
  UINT uFlags,      // menu-item flags
  UINT uIDNewItem,  // menu-item identifier or handle to drop-down menu or submenu
  LPCTSTR lpNewItem // menu-item content
);

Parameters

hMenu
Handle to the menu bar, drop-down menu, submenu, or shortcut menu to be changed.
uFlags
Specifies flags to control the appearance and behavior of the new menu item. This parameter can be a combination of the values listed in the following Remarks section.
uIDNewItem
Specifies either the identifier of the new menu item or, if the uFlags parameter is set to MF_POPUP, the handle to the drop-down menu or submenu.
lpNewItem
Specifies the content of the new menu item. The interpretation of lpNewItem depends on whether the uFlags parameter includes the MF_BITMAP, MF_OWNERDRAW, or MF_STRING flag, as follows:
Value | Description
MF_BITMAP | Contains a bitmap handle.
MF_OWNERDRAW | Contains a 32-bit value supplied by the application that can be used to maintain additional data related to the menu item. The value is in the itemData member of the structure pointed to by the lparam parameter of the WM_MEASURE or WM_DRAWITEM message sent when the menu is created or its appearance is updated.
MF_STRING | Contains a pointer to a null-terminated string.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The application must call the DrawMenuBar function whenever a menu changes, whether or not the menu is in a displayed window.

To get keyboard accelerators to work with bitmap or owner-drawn menu items, the owner of the menu must process the WM_MENUCHAR message. For more information, see Owner-Drawn Menus and the WM_MENUCHAR Message.

The following flags can be set in the uFlags parameter:

Value | Description
MF_BITMAP | Uses a bitmap as the menu item. The lpNewItem parameter contains the handle to the bitmap.
MF_CHECKED | Places a check mark next to the menu item. If the application provides check-mark bitmaps (see SetMenuItemBitmaps, this flag displays the check mark bitmap next to the menu item.
MF_DISABLED | Disables the menu item so it cannot be selected, but the flag does not gray it.
MF_ENABLED | Enables the menu item so it can be selected, and restores it from its grayed state.
MF_GRAYED | Disables the menu item and grays it so it cannot be selected.
MF_MENUBARBREAK | Functions the same as the MF_MENUBREAK flag for a menu bar. For a drop-down menu, submenu, or shortcut menu, the new column is separated from the old column by a vertical line.
MF_MENUBREAK | Places the item on a new line (for a menu bar) or in a new column (for a drop-down menu, submenu, or shortcut menu) without separating columns.
MF_OWNERDRAW | Specifies that the item is an owner-drawn item. Before the menu is displayed for the first time, the window that owns the menu receives a WM_MEASUREITEM message to retrieve the width and height of the menu item. The WM_DRAWITEM message is then sent to the window procedure of the owner window whenever the appearance of the menu item must be updated.
MF_POPUP | Specifies that the menu item opens a drop-down menu or submenu. The uIDNewItem parameter specifies the handle to the drop-down menu or submenu. This flag is used to add a menu name to a menu bar, or a menu item that opens a submenu to a drop-down menu, submenu, or shortcut menu.
MF_SEPARATOR | Draws a horizontal dividing line. This flag is used only in a drop-down menu, submenu, or shortcut menu. The line cannot be grayed, disabled, or highlighted. The lpNewItem and uIDNewItem parameters are ignored.
MF_STRING | Specifies that the menu item is a text string; the lpNewItem parameter points to the string.
MF_UNCHECKED | Does not place a check mark next to the item (default). If the application supplies check-mark bitmaps (see SetMenuItemBitmaps), this flag displays the unchecked bitmap next to the menu item.

The following groups of flags cannot be used together:

  • MF_DISABLED, MF_ENABLED, and MF_GRAYED
  • MF_BITMAP, MF_STRING, and MF_OWNERDRAW
  • MF_MENUBARBREAK and MF_MENUBREAK
  • MF_CHECKED and MF_UNCHECKED

Windows CE: The following flags are not supported for the fuFlags parameter:

MF_BITMAP

MF_DISABLED

MFS_GRAYED

MF_GRAYED can be used in place of MF_DISABLED and MFS_GRAYED.

Windows CE 1.0 does not support cascading menus. If you are using Windows CE 1.0, you cannot insert an MF_POPUP menu into another pop-up menu.

In Windows CE 1.0, the following flags are not supported:

MF_POPUP

MF_MENUBREAK

MF_MENUBARBREAK

In Windows CE versions 2.0 and later, these flags are supported. Cascading menus are also supported.

See Also

Menus Overview, Menu Functions, CreateMenu, DeleteMenu, DestroyMenu, DrawMenuBar, InsertMenu, InsertMenuItem, ModifyMenu, RemoveMenu, SetMenuItemBitmaps


CheckMenuItem

The CheckMenuItem function sets the state of the specified menu item's check mark attribute to either checked or unchecked.

The CheckMenuItem function has been superseded by the SetMenuItemInfo function. You can still use CheckMenuItem, however, if you do not need any of the extended features of SetMenuItemInfo.

DWORD CheckMenuItem(
  HMENU hmenu,        // handle to menu
  UINT uIDCheckItem,  // menu item to check or uncheck
  UINT uCheck         // menu item flags
);

Parameters

hmenu
Handle to the menu of interest.
uIDCheckItem
Specifies the menu item whose check-mark attribute is to be set, as determined by the uCheck parameter.
uCheck
Specifies flags that control the interpretation of the uIDCheckItem parameter and the state of the menu item's check-mark attribute. This parameter can be a combination of either MF_BYCOMMAND, or MF_BYPOSITION and MF_CHECKED or MF_UNCHECKED.
Value | Meaning
MF_BYCOMMAND | Indicates that the uIDCheckItem parameter gives the identifier of the menu item. The MF_BYCOMMAND flag is the default, if neither the MF_BYCOMMAND nor MF_BYPOSITION flag is specified.
MF_BYPOSITION | Indicates that the uIDCheckItem parameter gives the zero-based relative position of the menu item.
MF_CHECKED | Sets the check-mark attribute to the checked state.
MF_UNCHECKED | Sets the check-mark attribute to the unchecked state.

Return Values

The return value specifies the previous state of the menu item (either MF_CHECKED or MF_UNCHECKED). If the menu item does not exist, the return value is 0xFFFFFFFF.

Remarks

An item in a menu bar cannot have a check mark.

The uIDCheckItem parameter identifies a item that opens a submenu or a command item. For a item that opens a submenu, the uIDCheckItem parameter must specify the position of the item. For a command item, the uIDCheckItem parameter can specify either the item's position or its identifier.

See Also

Menus Overview, Menu Functions, EnableMenuItem, GetMenuItemID, SetMenuItemBitmaps, SetMenuItemInfo


CheckMenuRadioItem

The CheckMenuRadioItem function checks a specified menu item and makes it a radio item. At the same time, the function unchecks all other menu items in the associated group and clears the radio-item type flag for those items.

BOOL CheckMenuRadioItem(
  HMENU hmenu,
  UINT idFirst,
  UINT idLast,
  UINT idCheck,
  UINT uFlags
);

Parameters

hmenu
Handle to the menu that contains the group of menu items.
idFirst
Identifier or position of the first menu item in the group.
idLast
Identifier or position of the last menu item in the group.
idCheck
Identifier or position of the menu item to check.
uFlags
Value specifying the meaning of idFirst, idLast, and idCheck. If this parameter is MF_BYCOMMAND, the other parameters specify menu item identifiers. If it is MF_BYPOSITION, the other parameters specify the menu item positions.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, use the GetLastError function.

Remarks

The CheckMenuRadioItem function sets the MFT_RADIOCHECK type flag and the MFS_CHECKED state for the item specified by idCheck and, at the same time, clears both flags for all other items in the group. The checked item is displayed using a bullet bitmap instead of a check-mark bitmap.

For more information about menu item type and state flags, see the MENUITEMINFO structure.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Menus Overview, Menu Functions, MENUITEMINFO


CreateMenu

The CreateMenu function creates a menu. The menu is initially empty, but it can be filled with menu items by using the InsertMenuItem, AppendMenu, and InsertMenu functions.

HMENU CreateMenu(VOID)

Parameters

This function has no parameters.

Return Values

If the function succeeds, the return value is the handle to the newly created menu.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

Resources associated with a menu that is assigned to a window are freed automatically. If the menu is not assigned to a window, an application must free system resources associated with the menu before closing. An application frees menu resources by calling the DestroyMenu function.

Windows 95: The system can support a maximum of 16,364 menu handles.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Menus Overview, Menu Functions, AppendMenu, CreatePopupMenu, DestroyMenu, InsertMenu, SetMenu, InsertMenuItem


CreatePopupMenu

The CreatePopupMenu function creates a drop-down menu, submenu, or shortcut menu. The menu is initially empty. You can insert or append menu items by using the InsertMenuItem function. You can also use the InsertMenu function to insert menu items and the AppendMenu function to append menu items.

HMENU CreatePopupMenu(VOID)

Parameters

This function has no parameters.

Return Values

If the function succeeds, the return value is the handle to the newly created menu.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The application can add the new menu to an existing menu, or it can display a shortcut menu by calling the TrackPopupMenuEx or TrackPopupMenu functions.

Resources associated with a menu that is assigned to a window are freed automatically. If the menu is not assigned to a window, an application must free system resources associated with the menu before closing. An application frees menu resources by calling the DestroyMenu function.

Windows 95: The system can support a maximum of 16,364 menu handles.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Menus Overview, Menu Functions, AppendMenu, CreateMenu, DestroyMenu, InsertMenu, SetMenu, TrackPopupMenu, TrackPopupMenuEx, InsertMenuItem


DeleteMenu

The DeleteMenu function deletes an item from the specified menu. If the menu item opens a menu or submenu, this function destroys the handle to the menu or submenu and frees the memory used by the menu or submenu.

BOOL DeleteMenu(
  HMENU hMenu,     // handle to menu
  UINT uPosition,  // menu item identifier or position
  UINT uFlags      // menu item flag
);

Parameters

hMenu
Handle to the menu to be changed.
uPosition
Specifies the menu item to be deleted, as determined by the uFlags parameter.
uFlags
Specifies how the uPosition parameter is interpreted. This parameter must be one of the following values:
Value | Meaning
MF_BYCOMMAND | Indicates that uPosition gives the identifier of the menu item. The MF_BYCOMMAND flag is the default flag if neither the MF_BYCOMMAND nor MF_BYPOSITION flag is specified.
MF_BYPOSITION | Indicates that uPosition gives the zero-based relative position of the menu item.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The application must call the DrawMenuBar function whenever a menu changes, whether or not the menu is in a displayed window.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Menus Overview, Menu Functions, DrawMenuBar, RemoveMenu


DestroyMenu

The DestroyMenu function destroys the specified menu and frees any memory that the menu occupies.

BOOL DestroyMenu(
  HMENU hMenu  // handle to menu to destroy
);

Parameters

hMenu
Handle to the menu to be destroyed.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Before closing, an application must use the DestroyMenu function to destroy a menu not assigned to a window. A menu that is assigned to a window is automatically destroyed when the application closes.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Menus Overview, Menu Functions, CreateMenu, DeleteMenu, RemoveMenu


DrawMenuBar

The DrawMenuBar function redraws the menu bar of the specified window. If the menu bar changes after the system has created the window, this function must be called to draw the changed menu bar.

BOOL DrawMenuBar(
  HWND hWnd  // handle to window with menu bar to redraw
);

Parameters

hWnd
Handle to the window whose menu bar needs redrawing.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Menus Overview, Menu Functions, DeleteMenu, InsertMenuItem, RemoveMenu, SetMenuItemInfo


EnableMenuItem

The EnableMenuItem function enables, disables, or grays the specified menu item.

BOOL EnableMenuItem(
  HMENU hMenu,         // handle to menu
  UINT uIDEnableItem,  // menu item to enable, disable, or gray
  UINT uEnable         // menu item flags
);

Parameters

hMenu
Handle to the menu.
uIDEnableItem
Specifies the menu item to be enabled, disabled, or grayed, as determined by the uEnable parameter. This parameter specifies an item in a menu bar, menu, or submenu.
uEnable
Specifies flags that control the interpretation of the uIDEnableItem parameter and indicate whether the menu item is enabled, disabled, or grayed. This parameter must be a combination of either MF_BYCOMMAND or MF_BYPOSITION and MF_ENABLED, MF_DISABLED, or MF_GRAYED.
Value | Meaning
MF_BYCOMMAND | Indicates that uIDEnableItem gives the identifier of the menu item. If neither the MF_BYCOMMAND nor MF_BYPOSITION flag is specified, the MF_BYCOMMAND flag is the default flag.
MF_BYPOSITION | Indicates that uIDEnableItem gives the zero-based relative position of the menu item.
MF_DISABLED | Indicates that the menu item is disabled, but not grayed, so it cannot be selected.
MF_ENABLED | Indicates that the menu item is enabled and restored from a grayed state so that it can be selected.
MF_GRAYED | Indicates that the menu item is disabled and grayed so that it cannot be selected.

Return Values

The return value specifies the previous state of the menu item (it is either MF_DISABLED, MF_ENABLED, or MF_GRAYED). If the menu item does not exist, the return value is 0xFFFFFFFF.

Remarks

An application must use the MF_BYPOSITION flag to specify the correct menu handle. If the menu handle to the menu bar is specified, the top-level menu item (an item in the menu bar) is affected. To set the state of an item in a drop-down menu or submenu by position, an application must specify the handle to the drop-down menu or submenu.

When an application specifies the MF_BYCOMMAND flag, the system checks all items that open submenus in the menu identified by the specified menu handle. Therefore, unless duplicate menu items are present, specifying the menu handle to the menu bar is sufficient.

The InsertMenu, InsertMenuItem, LoadMenuIndirect, ModifyMenu, and SetMenuItemInfo functions can also set the state (enabled, disabled, or grayed) of a menu item.

Windows CE: Windows CE does not support the MF_DISABLED flag for the uEnable parameter. Menu items cannot be disabled without being grayed. To disable a menu item use the MF_GRAYED flag.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Menus Overview, Menu Functions, GetMenuItemID, InsertMenu, InsertMenuItem, LoadMenuIndirect, ModifyMenu, SetMenuItemInfo, WM_SYSCOMMAND


GetMenu

The GetMenu function retrieves the handle to the menu assigned to the given window.

HMENU GetMenu(
  HWND hWnd  // handle to window
);

Parameters

hWnd
Handle to the window whose menu handle is retrieved.

Return Values

The return value is the handle to the menu. If the given window has no menu, the return value is NULL. If the window is a child window, the return value is undefined.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Menus Overview, Menu Functions, GetSubMenu, SetMenu


GetMenuCheckMarkDimensions

Note This function is obsolete. Use the GetSystemMetrics function with the CXMENUCHECK and CYMENUCHECK values to retrieve the bitmap dimensions.

The GetMenuCheckMarkDimensions function returns the dimensions of the default check mark bitmap. The system displays this bitmap next to checked menu items. Before calling the SetMenuItemBitmaps function to replace the default check mark bitmap for a menu item, an application must determine the correct bitmap size by calling GetMenuCheckMarkDimensions.

LONG GetMenuCheckMarkDimensions(VOID)

Parameters

This function has no parameters.

Return Values

The return value specifies the height and width, in pixels, of the default check mark bitmap. The high-order word contains the height; the low-order word contains the width.

See Also

Menus Overview, Menu Functions, SetMenuItemBitmaps


GetMenuDefaultItem

The GetMenuDefaultItem function determines the default menu item on the specified menu.

UINT GetMenuDefaultItem(
  HMENU hMenu,
  UINT fByPos,
  UINT gmdiFlags
);

Parameters

hMenu
Handle to the menu for which to retrieve the default menu item.
fByPos
Value specifying whether to retrieve the menu item's identifier or its position. If this parameter is FALSE, the identifier is returned. Otherwise, the position is returned.
gmdiFlags
Value specifying how the function searches for menu items. This parameter can be zero or more of the following values:
Value Meaning
GMDI_GOINTOPOPUPS Specifies that if the default item is one that opens a submenu, the function is to search recursively in the corresponding submenu. If the submenu has no default item, the return value identifies the item that opens the submenu.

By default, the function returns the first default item on the specified menu, regardless of whether it is an item that opens a submenu.
GMDI_USEDISABLED Specifies that the function is to return a default item, even if it is disabled.

By default, the function skips disabled or grayed items.

Return Values

If the function succeeds, the return value is the identifier or position of the menu item.

If the function fails, the return value is – 1. To get extended error information, call GetLastError.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Menus Overview, Menu Functions, SetMenuDefaultItem


GetMenuItemCount

The GetMenuItemCount function determines the number of items in the specified menu.

int GetMenuItemCount(
  HMENU hMenu  // handle to menu
);

Parameters

hMenu
Handle to the handle to the menu to be examined.

Return Values

If the function succeeds, the return value specifies the number of items in the menu.

If the function fails, the return value is –1. To get extended error information, call GetLastError.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Menus Overview, Menu Functions, GetMenuItemID


GetMenuItemID

The GetMenuItemID function retrieves the menu item identifier of a menu item located at the specified position in a menu.

UINT GetMenuItemID(
  HMENU hMenu,  // handle to menu
  int nPos      // position of menu item
);

Parameters

hMenu
Handle to the menu that contains the item whose identifier is to be retrieved.
nPos
Specifies the zero-based relative position of the menu item whose identifier is to be retrieved.

Return Values

The return value specifies the identifier of the given menu item. If the menu item identifier is NULL or if the specified item opens a submenu, the return value is 0xFFFFFFFF.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Menus Overview, Menu Functions, GetMenuItemCount


GetMenuItemInfo

The GetMenuItemInfo function retrieves information about a menu item.

BOOL GetMenuItemInfo(
  HMENU hMenu,
  UINT uItem,
  BOOL fByPosition,
  LPMENUITEMINFO lpmii
);

Parameters

hMenu
Handle to the menu that contains the menu item.
uItem
Identifier or position of the menu item to get information about. The meaning of this parameter depends on the value of fByPosition.
fByPosition
Value specifying the meaning of uItem. If this parameter is FALSE, uItem is a menu item identifier. Otherwise, it is a menu item position.
lpmii
Pointer to a MENUITEMINFO structure that specifies the information to retrieve and receives information about the menu item.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, use the GetLastError function.

Remarks

Windows CE: The MIM_CHECKMARKS flag value is not supported for the fMask member of the MENUITEMINFO structure pointed to by the pmii parameter of this function.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Menus Overview, Menu Functions, SetMenuItemInfo, MENUITEMINFO


GetMenuItemRect

The GetMenuItemRect function retrieves the bounding rectangle for the specified menu item.

BOOL GetMenuItemRect(
  HWND hWnd,
  HMENU hMenu,
  UINT uItem,
  LPRECT lprcItem
);

Parameters

hWnd
Handle to the window containing the menu.

Windows NT 5.0 and Windows 98: If this value is NULL and the hMenu parameter represents a popup menu, the function will find the menu window.

hMenu
Handle to a menu.
uItem
Zero-based position of the menu item.
lprcItem
Pointer to a RECT structure that receives the bounding rectangle of the specified menu item expressed in screen coordinates.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, use the GetLastError function.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Menus Overview, Menu Functions, RECT


GetMenuState

The GetMenuState function retrieves the menu flags associated with the specified menu item. If the menu item opens a submenu, this function also returns the number of items in the submenu.

The GetMenuState function has been superseded by the GetMenuItemInfo function. You can still use GetMenuState, however, if you do not need any of the extended features of GetMenuItemInfo.

UINT GetMenuState(
  HMENU hMenu, // handle to menu
  UINT uId,    // menu item to query
  UINT uFlags  // menu flags
);

Parameters

hMenu
Handle to the menu that contains the menu item whose flags are to be retrieved.
uId
Specifies the menu item for which the menu flags are to be retrieved, as determined by the uFlags parameter.
uFlags
Specifies how the uId parameter is interpreted. This parameter can be one of the following values:
Value | Description
MF_BYCOMMAND | Indicates that the uId parameter gives the identifier of the menu item. The MF_BYCOMMAND flag is the default if neither the MF_BYCOMMAND nor MF_BYPOSITION flag is specified.
MF_BYPOSITION | Indicates that the uId parameter gives the zero-based relative position of the menu item.

Return Values

If the specified item does not exist, the return value is 0xFFFFFFFF.

If the menu item opens a submenu, the low-order byte of the return value contains the menu flags associated with the item, and the high-order byte contains the number of items in the submenu opened by the item.

Otherwise, the return value is a mask (Boolean OR) of the menu flags. Following are the menu flags associated with the menu item.

Value | Description
MF_CHECKED | Places a check mark next to the item (for drop-down menus, submenus, and shortcut menus only).
MF_DISABLED | Disables the item.
MF_GRAYED | Disables and grays the item.
MF_HILITE | Highlights the item.
MF_MENUBARBREAK | Functions the same as the MF_MENUBREAK flag, except for drop-down menus, submenus, and shortcut menus, where the new column is separated from the old column by a vertical line.
MF_MENUBREAK | Places the item on a new line (for menu bars) or in a new column (for drop-down menus, submenus, and shortcut menus) without separating columns.
MF_SEPARATOR | Creates a horizontal dividing line (for drop-down menus, submenus, and shortcut menus only).

See Also

Menus Overview, Menu Functions, GetMenu, GetMenuItemCount, GetMenuItemID, GetMenuItemInfo


GetMenuString

The GetMenuString function copies the text string of the specified menu item into the specified buffer.

The GetMenuString function function has been superseded. Use the GetMenuItemInfo function to retrieve the menu item text.

int GetMenuString(
  HMENU hMenu,      // handle to the menu
  UINT uIDItem,     // menu item identifier
  LPTSTR lpString,  // pointer to the buffer for the string
  int nMaxCount,    // maximum length of the string
  UINT uFlag        // menu flags
);

Parameters

hMenu
Handle to the menu.
uIDItem
Specifies the menu item to be changed, as determined by the uFlag parameter.
lpString
Pointer to the buffer that is to receive the null-terminated string.

If lpString is NULL, the function returns the length of the menu string.

nMaxCount
Specifies the maximum length, in characters, of the string to be copied. If the string is longer than the maximum specified in the nMaxCount parameter, the extra characters are truncated.

If nMaxCount is 0, the function returns the length of the menu string.

uFlag
Specifies how the uIDItem parameter is interpreted. This parameter must be one of the following values:
Value | Meaning
MF_BYCOMMAND | Indicates that uIDItem gives the identifier of the menu item. If neither the MF_BYCOMMAND nor MF_BYPOSITION flag is specified, the MF_BYCOMMAND flag is the default flag.
MF_BYPOSITION | Indicates that uIDItem gives the zero-based relative position of the menu item.

Return Values

If the function succeeds, the return value specifies the number of characters copied to the buffer, not including the terminating null character.

If the function fails, the return value is zero.

Remarks

The nMaxCount parameter must be one larger than the number of characters in the text string to accommodate the terminating null character.

If nMaxCount is 0, the function returns the length of the menu string.

See Also

Menus Overview, Menu Functions, GetMenuItemID


GetSubMenu

The GetSubMenu function retrieves the handle to the drop-down menu or submenu activated by the specified menu item.

HMENU GetSubMenu(
  HMENU hMenu,  // handle to menu
  int nPos      // menu item position
);

Parameters

hMenu
Handle to the menu.
nPos
Specifies the zero-based relative position in the given menu of an item that activates a drop-down menu or submenu.

Return Values

If the function succeeds, the return value is the handle to the drop-down menu or submenu activated by the menu item. If the menu item does not activate a drop-down menu or submenu, the return value is NULL.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Menus Overview, Menu Functions, CreatePopupMenu, GetMenu


GetSystemMenu

The GetSystemMenu function allows the application to access the window menu (also known as the system menu or the control menu) for copying and modifying.

HMENU GetSystemMenu(
  HWND hWnd,    // handle to window to own window menu
  BOOL bRevert  // reset flag
);

Parameters

hWnd
Handle to the window that will own a copy of the window menu.
bRevert
Specifies the action to be taken. If this parameter is FALSE, GetSystemMenu returns the handle to the copy of the window menu currently in use. The copy is initially identical to the window menu, but it can be modified.

If this parameter is TRUE, GetSystemMenu resets the window menu back to the default state. The previous window menu, if any, is destroyed.

Return Values

If the bRevert parameter is FALSE, the return value is the handle to a copy of the window menu. If the bRevert parameter is TRUE, the return value is NULL.

Remarks

Any window that does not use the GetSystemMenu function to make its own copy of the window menu receives the standard window menu.

The window menu initially contains items with various identifier values, such as SC_CLOSE, SC_MOVE, and SC_SIZE.

Menu items on the window menu send WM_SYSCOMMAND messages.

All predefined window menu items have identifier numbers greater than 0xF000. If an application adds commands to the window menu, it should use identifier numbers less than 0xF000.

The system automatically grays items on the standard window menu, depending on the situation. The application can perform its own checking or graying by responding to the WM_INITMENU message that is sent before any menu is displayed.

Windows CE: Windows CE does not support a system menu, but GetSystemMenu is implemented as a macro to maintain compatibility with existing code. You can use the menu handle returned by this macro to disable the close box the same way you would in a Windows desktop platform. There is no other use for the return value in Windows CE. The brevert parameter is ignored. Use the following code to disable the Close button:

EnableMenuItem (GetSystemMenu(hwnd, FALSE), SC_CLOSE,MF_BYCOMMAND | MF_GRAYED);

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Menus Overview, Menu Functions, GetMenu, WM_INITMENU, WM_SYSCOMMAND


HiliteMenuItem

The HiliteMenuItem function highlights or removes the highlighting from an item in a menu bar.

BOOL HiliteMenuItem(
  HWND hwnd,         // handle to the window with the menu
  HMENU hmenu,       // handle to the menu
  UINT uItemHilite,  // menu item to highlight or unhighlight
  UINT uHilite       // highlight flags
);

Parameters

hwnd
Handle to the window that contains the menu.
hmenu
Handle to the menu bar that contains the item to be highlighted.
uItemHilite
Specifies the menu item to be highlighted. This parameter is either the identifier of the menu item or the offset of the menu item in the menu bar, depending on the value of the uHilite parameter.
uHilite
Specifies flags that control the interpretation of the uItemHilite parameter and indicates whether the menu item is highlighted. This parameter must be a combination of either MF_BYCOMMAND or MF_BYPOSITION and MF_HILITE or MF_UNHILITE.
Value | Meaning
MF_BYCOMMAND | Indicates that uItemHilite gives the identifier of the menu item.
MF_BYPOSITION | Indicates that uItemHilite gives the zero-based relative position of the menu item.
MF_HILITE | Highlights the menu item. If this flag is not specified, the highlighting is removed from the item.
MF_UNHILITE | Removes highlighting from the menu item.

Return Values

If the menu item is set to the specified highlight state, the return value is nonzero.

If the menu item is not set to the specified highlight state, the return value is zero.

Remarks

The MF_HILITE and MF_UNHILITE flags can be used only with the HiliteMenuItem function; they cannot be used with the ModifyMenu function.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Menus Overview, Menu Functions, ModifyMenu


InsertMenu

The InsertMenu function inserts a new menu item into a menu, moving other items down the menu.

The InsertMenu function has been superseded by the InsertMenuItem function. You can still use InsertMenu, however, if you do not need any of the extended features of InsertMenuItem.

BOOL InsertMenu(
  HMENU hMenu,      // handle to menu
  UINT uPosition,   // menu item that new menu item precedes
  UINT uFlags,      // menu item flags
  UINT uIDNewItem,  // menu item identifier or handle to drop-down
                    // menu or submenu
  LPCTSTR lpNewItem // menu item content
);

Parameters

hMenu
Handle to the menu to be changed.
uPosition
Specifies the menu item before which the new menu item is to be inserted, as determined by the uFlags parameter.
uFlags
Specifies flags that control the interpretation of the uPosition parameter and the content, appearance, and behavior of the new menu item. This parameter must be a combination of one of the following required values and at least one of the values listed in the following Remarks section.
Value | Description
MF_BYCOMMAND | Indicates that the uPosition parameter gives the identifier of the menu item. The MF_BYCOMMAND flag is the default if neither the MF_BYCOMMAND nor MF_BYPOSITION flag is specified.
MF_BYPOSITION | Indicates that the uPosition parameter gives the zero-based relative position of the new menu item. If uPosition is 0xFFFFFFFF, the new menu item is appended to the end of the menu.

uIDNewItem
Specifies either the identifier of the new menu item or, if the uFlags parameter has the MF_POPUP flag set, the handle to the drop-down menu or submenu.
lpNewItem
Specifies the content of the new menu item. The interpretation of lpNewItem depends on whether the uFlags parameter includes the MF_BITMAP, MF_OWNERDRAW, or MF_STRING flag, as follows:
Value | Description
MF_BITMAP | Contains a bitmap handle.
MF_OWNERDRAW | Contains a 32-bit value supplied by the application that can be used to maintain additional data related to the menu item. The value is in the itemData member of the structure pointed to by the lparam parameter of the WM_MEASUREITEM or WM_DRAWITEM message sent when the menu item is created or its appearance is updated.
MF_STRING | Contains a pointer to a null-terminated string (the default).

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The application must call the DrawMenuBar function whenever a menu changes, whether or not the menu is in a displayed window.

The following list describes the flags that can be set in the uFlags parameter:

Value | Description
MF_BITMAP | Uses a bitmap as the menu item. The lpNewItem parameter contains the handle to the bitmap.
MF_CHECKED | Places a check mark next to the menu item. If the application provides check mark bitmaps (see SetMenuItemBitmaps), this flag displays the check mark bitmap next to the menu item.
MF_DISABLED | Disables the menu item so that it cannot be selected, but does not gray it.
MF_ENABLED | Enables the menu item so that it can be selected and restores it from its grayed state.
MF_GRAYED | Disables the menu item and grays it so it cannot be selected.
MF_MENUBARBREAK | Functions the same as the MF_MENUBREAK flag for a menu bar. For a drop-down menu, submenu, or shortcut menu, the new column is separated from the old column by a vertical line.
MF_MENUBREAK | Places the item on a new line (for menu bars) or in a new column (for a drop-down menu, submenu, or shortcut menu) without separating columns.
MF_OWNERDRAW | Specifies that the item is an owner-drawn item. Before the menu is displayed for the first time, the window that owns the menu receives a WM_MEASUREITEM message to retrieve the width and height of the menu item. The WM_DRAWITEM message is then sent to the window procedure of the owner window whenever the appearance of the menu item must be updated.
MF_POPUP | Specifies that the menu item opens a drop-down menu or submenu. The uIDNewItem parameter specifies the handle to the drop-down menu or submenu. This flag is used to add a menu name to a menu bar or a menu item that opens a submenu to a drop-down menu, submenu, or shortcut menu.
MF_SEPARATOR | Draws a horizontal dividing line. This flag is used only in a drop-down menu, submenu, or shortcut menu. The line cannot be grayed, disabled, or highlighted. The lpNewItem and uIDNewItem parameters are ignored.
MF_STRING | Specifies that the menu item is a text string; the lpNewItem parameter points to the string.
MF_UNCHECKED | Does not place a check mark next to the menu item (default). If the application supplies check mark bitmaps (see the SetMenuItemBitmaps function), this flag displays the unchecked bitmap next to the menu item.

The following groups of flags cannot be used together:

  • MF_BYCOMMAND and MF_BYPOSITION
  • MF_DISABLED, MF_ENABLED, and MF_GRAYED
  • MF_BITMAP, MF_STRING, MF_OWNERDRAW, and MF_SEPARATOR
  • MF_MENUBARBREAK and MF_MENUBREAK
  • MF_CHECKED and MF_UNCHECKED

Windows CE: Windows CE does not support the MF_BITMAP flag or the MF_DISABLED flag in the uFlags parameter. Menu items cannot be disabled without being grayed. To disable a menu item use the MF_GRAYED flag.

Windows CE version 1.0 does not support cascading menus. If you are using Windows CE 1.0, you cannot insert an MF_POPUP menu into another pop-up menu. If using Windows CE 2.0 or later, you can.

See Also

Menus Overview, Menu Functions, AppendMenu, DeleteMenu, DrawMenuBar, InsertMenuItem, ModifyMenu, RemoveMenu, SetMenuItemBitmaps, WM_DRAWITEM, WM_MEASUREITEM


InsertMenuItem

The InsertMenuItem function inserts a new menu item at the specified position in a menu.

BOOL WINAPI InsertMenuItem(
  HMENU hMenu,
  UINT uItem,
  BOOL fByPosition,
  LPMENUITEMINFO lpmii
);

Parameters

hMenu
Handle to the menu in which the new menu item is inserted.
uItem
Identifier or position of the menu item before which to insert the new item. The meaning of this parameter depends on the value of fByPosition.
fByPosition
Value specifying the meaning of uItem. If this parameter is FALSE, uItem is a menu item identifier. Otherwise, it is a menu item position.
lpmii
Pointer to a MENUITEMINFO structure that contains information about the new menu item.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, use the GetLastError function.

Remarks

In order for keyboard accelerators to work with bitmap or owner-drawn menu items, the owner of the menu must process the WM_MENUCHAR message. See Owner-Drawn Menus and the WM_MENUCHAR Message for more information.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Menus Overview, Menu Functions, MENUITEMINFO


IsMenu

The IsMenu function determines whether a handle is a menu handle.

BOOL IsMenu(
  HMENU hMenu  // handle to test
);

Parameters

hMenu
The handle to be tested.

Return Values

If hMenu is a menu handle, the return value is nonzero.

If hMenu is not a menu handle, the return value is zero.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Menus Overview, Menu Functions


LoadMenu

The LoadMenu function loads the specified menu resource from the executable (.EXE) file associated with an application instance.

HMENU LoadMenu(
  HINSTANCE hInstance,  // handle to application instance
  LPCTSTR lpMenuName    // menu name string or menu-resource
                        // identifier
);

Parameters

hInstance
Handle to the instance of the module containing the menu resource to be loaded.
lpMenuName
Pointer to a null-terminated string that contains the name of the menu resource. Alternatively, this parameter can consist of the resource identifier in the low-order word and zero in the high-order word. To create this value, use the MAKEINTRESOURCE macro.

Return Values

If the function succeeds, the return value is the handle to the menu resource.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The DestroyMenu function is used, before an application closes, to destroy the menu and free memory that the loaded menu occupied.

Windows CE: Windows CE version 1.0 does not support cascading menus.

Windows CE versions 2.0 and later support cascading menus.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Menus Overview, Menu Functions, LoadMenuIndirect, MAKEINTRESOURCE


LoadMenuIndirect

The LoadMenuIndirect function loads the specified menu template in memory.

HMENU LoadMenuIndirect(
  CONST MENUTEMPLATE *lpMenuTemplate  // address of menu template
);

Parameters

lpMenuTemplate
Pointer to a menu template or an extended menu template.

A menu template consists of a MENUITEMTEMPLATEHEADER structure followed by one or more contiguous MENUITEMTEMPLATE structures. An extended menu template consists of a MENUEX_TEMPLATE_HEADER structure followed by one or more contiguous MENUEX_TEMPLATE_ITEM structures.

Return Values

If the function succeeds, the return value is the handle to the menu.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

For both the ANSI and the Unicode version of this function, the strings in the MENUITEMTEMPLATE structure must be Unicode strings.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Menus Overview, Menu Functions, LoadMenu, MENUEX_TEMPLATE_HEADER, MENUEX_TEMPLATE_ITEM, MENUITEMTEMPLATE, MENUITEMTEMPLATEHEADER


MenuItemFromPoint

The MenuItemFromPoint function determines which menu item, if any, is at the specified location.

UINT WINAPI MenuItemFromPoint(
  HWND hWnd,
  HMENU hMenu,
  POINT ptScreen
);

Parameters

hWnd
Handle to the window containing the menu.

Windows NT 5.0 and Windows 98: If this value is NULL and the hMenu parameter represents a popup menu, the function will find the menu window.

hMenu
Handle to the menu containing the menu items to hit test.
ptScreen
POINT structure specifying the location to test. If hMenu specifies a menu bar, this parameter is in window coordinates. Otherwise, it is in client coordinates.

Return Values

Returns the zero-based position of the menu item at the specified location or –1 if no menu item is at the specified location.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Menus Overview, Menu Functions, POINT


ModifyMenu

The ModifyMenu function changes an existing menu item. This function is used to specify the content, appearance, and behavior of the menu item.

The ModifyMenu function has been superseded by the SetMenuItemInfo function. You can still use ModifyMenu, however, if you do not need any of the extended features of SetMenuItemInfo.

BOOL ModifyMenu(
  HMENU hMnu,       // handle to menu
  UINT uPosition,   // menu item to modify
  UINT uFlags,      // menu item flags
  UINT uIDNewItem,  // menu item identifier or handle to drop-down
                    // menu or submenu
  LPCTSTR lpNewItem // menu item content
);

Parameters

hMnu
Handle to the menu to be changed.
uPosition
Specifies the menu item to be changed, as determined by the uFlags parameter.
uFlags
Specifies flags that control the interpretation of the uPosition parameter and the content, appearance, and behavior of the menu item. This parameter must be a combination of one of the following required values and at least one of the values listed in the following Remarks section.
Value | Meaning
MF_BYCOMMAND | Indicates that the uPosition parameter gives the identifier of the menu item. The MF_BYCOMMAND flag is the default if neither the MF_BYCOMMAND nor MF_BYPOSITION flag is specified.
MF_BYPOSITION | Indicates that the uPosition parameter gives the zero-based relative position of the menu item.

uIDNewItem
Specifies either the identifier of the modified menu item or, if the uFlags parameter has the MF_POPUP flag set, the handle to the drop-down menu or submenu.
lpNewItem
Pointer to the content of the changed menu item. The interpretation of this parameter depends on whether the uFlags parameter includes the MF_BITMAP, MF_OWNERDRAW, or MF_STRING flag.
Value | Meaning
MF_BITMAP | Contains a bitmap handle.
MF_OWNERDRAW | Contains a 32-bit value supplied by an application that is used to maintain additional data related to the menu item. The value is in the itemData member of the structure pointed to by the lparam parameter of the WM_MEASUREITEM or WM_DRAWITEM messages sent when the menu item is created or its appearance is updated.
MF_STRING | Contains a pointer to a null-terminated string (the default).

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

If ModifyMenu replaces a menu item that opens a drop-down menu or submenu, the function destroys the old drop-down menu or submenu and frees the memory used by it.

In order for keyboard accelerators to work with bitmap or owner-drawn menu items, the owner of the menu must process the WM_MENUCHAR message. See Owner-Drawn Menus and the WM_MENUCHAR Message for more information.

The application must call the DrawMenuBar function whenever a menu changes, whether or not the menu is in a displayed window. To change the attributes of existing menu items, it is much faster to use the CheckMenuItem and EnableMenuItem functions.

The following list describes the flags that may be set in the uFlags parameter:

Value | Meaning
MF_BITMAP | Uses a bitmap as the menu item. The lpNewItem parameter contains the handle to the bitmap.
MF_BYCOMMAND | Indicates that the uPosition parameter specifies the identifier of the menu item (the default).
MF_BYPOSITION | Indicates that the uPosition parameter specifies the zero-based relative position of the new menu item.
MF_CHECKED | Places a check mark next to the item. If your application provides check mark bitmaps (see the SetMenuItemBitmaps function), this flag displays a checked bitmap next to the menu item.
MF_DISABLED | Disables the menu item so that it cannot be selected, but this flag does not gray it.
MF_ENABLED | Enables the menu item so that it can be selected and restores it from its grayed state.
MF_GRAYED | Disables the menu item and grays it so that it cannot be selected.
MF_MENUBARBREAK | Functions the same as the MF_MENUBREAK flag for a menu bar. For a drop-down menu, submenu, or shortcut menu, the new column is separated from the old column by a vertical line.
MF_MENUBREAK | Places the item on a new line (for menu bars) or in a new column (for a drop-down menu, submenu, or shortcut menu) without separating columns.
MF_OWNERDRAW | Specifies that the item is an owner-drawn item. Before the menu is displayed for the first time, the window that owns the menu receives a WM_MEASUREITEM message to retrieve the width and height of the menu item. The WM_DRAWITEM message is then sent to the window procedure of the owner window whenever the appearance of the menu item must be updated.
MF_POPUP | Specifies that the menu item opens a drop-down menu or submenu. The uIDNewItem parameter specifies the handle to the drop-down menu or submenu. This flag is used to add a menu name to a menu bar or a menu item that opens a submenu to a drop-down menu, submenu, or shortcut menu.
MF_SEPARATOR | Draws a horizontal dividing line. This flag is used only in a drop-down menu, submenu, or shortcut menu. The line cannot be grayed, disabled, or highlighted. The lpNewItem and uIDNewItem parameters are ignored.
MF_STRING | Specifies that the menu item is a text string; the lpNewItem parameter points to the string.
MF_UNCHECKED | Does not place a check mark next to the item (the default). If your application supplies check mark bitmaps (see the SetMenuItemBitmaps function), this flag displays an unchecked bitmap next to the menu item.

The following groups of flags cannot be used together:

  • MF_BYCOMMAND and MF_BYPOSITION
  • MF_DISABLED, MF_ENABLED, and MF_GRAYED
  • MF_BITMAP, MF_STRING, MF_OWNERDRAW, and MF_SEPARATOR
  • MF_MENUBARBREAK and MF_MENUBREAK
  • MF_CHECKED and MF_UNCHECKED

See Also

Menus Overview, Menu Functions, AppendMenu, CheckMenuItem, DrawMenuBar, EnableMenuItem, SetMenuItemBitmaps, SetMenuItemInfo, WM_DRAWITEM, WM_MEASUREITEM


RemoveMenu

The RemoveMenu function deletes a menu item or detaches a submenu from the specified menu. If the menu item opens a drop-down menu or submenu, RemoveMenu does not destroy the menu or its handle, allowing the menu to be reused. Before this function is called, the GetSubMenu function should retrieve the handle to the drop-down menu or submenu.

BOOL RemoveMenu(
  HMENU hMenu,     // handle to menu
  UINT uPosition,  // menu item identifier or position
  UINT uFlags      // menu item flag
);

Parameters

hMenu
Handle to the menu to be changed.
uPosition
Specifies the menu item to be deleted, as determined by the uFlags parameter.
uFlags
Specifies how the uPosition parameter is interpreted. This parameter must be one of the following values:
Value | Meaning
MF_BYCOMMAND | Indicates that uPosition gives the identifier of the menu item. If neither the MF_BYCOMMAND nor MF_BYPOSITION flag is specified, the MF_BYCOMMAND flag is the default flag.
MF_BYPOSITION | Indicates that uPosition gives the zero-based relative position of the menu item.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The application must call the DrawMenuBar function whenever a menu changes, whether or not the menu is in a displayed window.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Menus Overview, Menu Functions, CreatePopupMenu, DeleteMenu, DrawMenuBar, GetSubMenu


SetMenu

The SetMenu function assigns a new menu to the specified window.

BOOL SetMenu(
  HWND hWnd,  // handle to window
  HMENU hMenu // handle to menu
);

Parameters

hWnd
Handle to the window to which the menu is to be assigned.
hMenu
Handle to the new menu. If this parameter is NULL, the window's current menu is removed.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The window is redrawn to reflect the menu change.

The SetMenu function replaces the previous menu, if any, but it does not destroy it. An application should call the DestroyMenu function to accomplish this task.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Menus Overview, Menu Functions, DestroyMenu, GetMenu


SetMenuDefaultItem

The SetMenuDefaultItem function sets the default menu item for the specified menu.

BOOL SetMenuDefaultItem(
  HMENU hMenu,
  UINT uItem,
  UINT fByPos
);

Parameters

hMenu
Handle to the menu to set the default item for.
uItem
Identifier or position of the new default menu item or – 1 for no default item. The meaning of this parameter depends on the value of fByPos.
fByPos
Value specifying the meaning of uItem. If this parameter is FALSE, uItem is a menu item identifier. Otherwise, it is a menu item position.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, use the GetLastError function.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Menus Overview, Menu Functions, GetMenuDefaultItem


SetMenuItemBitmaps

The SetMenuItemBitmaps function associates the specified bitmap with a menu item. Whether the menu item is checked or unchecked, the system displays the appropriate bitmap next to the menu item.

BOOL SetMenuItemBitmaps(
  HMENU hMenu,            // handle to menu
  UINT uPosition,         // menu item to receive new bitmaps
  UINT uFlags,            // menu item flags
  HBITMAP hBitmapUnchecked,  // handle to unchecked bitmap
  HBITMAP hBitmapChecked  // handle to checked bitmap
);

Parameters

hMenu
Handle to the menu containing the item to receive new check-mark bitmaps.
uPosition
Specifies the menu item to be changed, as determined by the uFlags parameter.
uFlags
Specifies how the uPosition parameter is interpreted. The uFlags parameter must be one of the following values.
Value | Meaning
MF_BYCOMMAND | Indicates that uPosition gives the identifier of the menu item. If neither MF_BYCOMMAND nor MF_BYPOSITION is specified, MF_BYCOMMAND is the default flag.
MF_BYPOSITION | Indicates that uPosition gives the zero-based relative position of the menu item.

hBitmapUnchecked
Handle to the bitmap displayed when the menu item is not checked.
hBitmapChecked
Handle to the bitmap displayed when the menu item is checked.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

If either the hBitmapUnchecked or hBitmapChecked parameter is NULL, the system displays nothing next to the menu item for the corresponding check state. If both parameters are NULL, the system displays the default check-mark bitmap when the item is checked, and removes the bitmap when the item is not checked.

When the menu is destroyed, these bitmaps are not destroyed; it is up to the application to destroy them.

The checked and unchecked bitmaps should be monochrome. The system uses the Boolean AND operator to combine bitmaps with the menu so that the white part becomes transparent and the black part becomes the menu-item color. If you use color bitmaps, the results may be undesirable.

Use the GetSystemMetrics function with the CXMENUCHECK and CYMENUCHECK values to retrieve the bitmap dimensions.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Menus Overview, Menu Functions, GetSystemMetrics


SetMenuItemInfo

The SetMenuItemInfo function changes information about a menu item.

BOOL SetMenuItemInfo(
  HMENU hMenu,
  UINT uItem,
  BOOL fByPosition,
  LPMENUITEMINFO lpmii
);

Parameters

hMenu
Handle to the menu that contains the menu item.
uItem
Identifier or position of the menu item to change. The meaning of this parameter depends on the value of fByPosition.
fByPosition
Value specifying the meaning of uItem. If this parameter is FALSE, uItem is a menu item identifier. Otherwise, it is a menu item position.
lpmii
Pointer to a MENUITEMINFO structure that contains information about the menu item and specifies which menu item attributes to change.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, use the GetLastError function.

Remarks

In order for keyboard accelerators to work with bitmap or owner-drawn menu items, the owner of the menu must process the WM_MENUCHAR message. See Owner-Drawn Menus and the WM_MENUCHAR Message for more information.

Windows CE: Only the following flags are valid for the fMask member of the MENUITEMINFO structure pointed to by the pmii parameter:

MIIM_DATA

MIIM_ID

MIIM_TYPE

If MIIM_TYPE is specified, then the fType member of MENUITEMINFO must be the current type of the item, in other words, the type cannot be changed.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Menus Overview, Menu Functions, GetMenuItemInfo, MENUITEMINFO


TrackPopupMenu

The TrackPopupMenu function displays a shortcut menu at the specified location and tracks the selection of items on the menu. The shortcut menu can appear anywhere on the screen.

BOOL TrackPopupMenu(
  HMENU hMenu,         // handle to shortcut menu
  UINT uFlags,         // screen-position and mouse-button flags
  int x,               // horizontal position, in screen coordinates
  int y,               // vertical position, in screen coordinates
  int nReserved,       // reserved, must be zero
  HWND hWnd,           // handle to owner window
  CONST RECT *prcRect  // ignored
);

Parameters

hMenu
Handle to the shortcut menu to be displayed. The handle can be obtained by calling CreatePopupMenu to create a new shortcut menu, or by calling GetSubMenu to retrieve the handle to a submenu associated with an existing menu item.
uFlags
A set of bit flags that specify function options.

Use one of the following bit flag constants to specify how the function positions the shortcut menu horizontally.
Value | Meaning
TPM_CENTERALIGN | If this flag is set, the function centers the shortcut menu horizontally relative to the coordinate specified by the x parameter.
TPM_LEFTALIGN | If this flag is set, the function positions the shortcut menu so that its left side is aligned with the coordinate specified by the x parameter.
TPM_RIGHTALIGN | Positions the shortcut menu so that its right side is aligned with the coordinate specified by the x parameter.

Use one of the following bit flag constants to specify how the function positions the shortcut menu vertically.
Value | Meaning
TPM_BOTTOMALIGN | If this flag is set, the function positions the shortcut menu so that its bottom side is aligned with the coordinate specified by the y parameter.
TPM_TOPALIGN | If this flag is set, the function positions the shortcut menu so that its top side is aligned with the coordinate specified by the y parameter.
TPM_VCENTERALIGN | If this flag is set, the function centers the shortcut menu vertically relative to the coordinate specified by the y parameter.

Use the following bit flag constants to determine the user selection without having to set up a parent window for the menu.
Value | Meaning
TPM_NONOTIFY | If this flag is set, the function does not send notification messages when the user clicks on a menu item.
TPM_RETURNCMD | If this flag is set, the function returns the menu item identifier of the user's selection in the return value.

Use one of the following bit flag constants to specify which mouse button the shortcut menu tracks.
Value | Meaning
TPM_LEFTBUTTON | If this flag is set, the user can select menu items with only the left mouse button.
TPM_RIGHTBUTTON | If this flag is set, the user can select menu items with both the left and right mouse buttons.

x
Specifies the horizontal location of the shortcut menu, in screen coordinates.
y
Specifies the vertical location of the shortcut menu, in screen coordinates.
nReserved
Reserved; must be zero.
hWnd
Handle to the window that owns the shortcut menu. This window receives all messages from the menu. The window does not receive a WM_COMMAND message from the menu until the function returns.

If you specify TPM_NONOTIFY in the uFlags parameter, the function does not send messages to the window identified by hWnd. However, you must still pass a window handle in hWnd. It can be any window handle from your application.

prcRect
Ignored.

Return Values

If you specify TPM_RETURNCMD in the uFlags parameter, the return value is the menu-item identifier of the item that the user selected. If the user cancels the menu without making a selection, or if an error occurs, then the return value is zero.

If you do not specify TPM_RETURNCMD in the uFlags parameter, the return value is nonzero if the function succeeds and zero if it fails. To get extended error information, call GetLastError.

Remarks

Windows CE: Windows CE does not support the following flags for the uFlags parameter:

TPM_NONOTIFY

TPM_LEFTBUTTON

TPM_RIGHTBUTTON

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Menus Overview, Menu Functions, CreatePopupMenu, GetSubMenu, RECT, WM_COMMAND


TrackPopupMenuEx

The TrackPopupMenuEx function displays a shortcut menu at the specified location and tracks the selection of items on the shortcut menu. The shortcut menu can appear anywhere on the screen.

BOOL TrackPopupMenuEx(
  HMENU hmenu,
  UINT fuFlags,
  int x,
  int y,
  HWND hwnd,
  LPTPMPARAMS lptpm
);

Parameters

hmenu
Handle to the shortcut menu to be displayed. This handle can be obtained by calling the CreatePopupMenu function to create a new shortcut menu or by calling the GetSubMenu function to retrieve the handle to a submenu associated with an existing menu item.
fuFlags
Positioning and other options. This parameter, which can be zero or more of the values listed with the TrackPopupMenu function, may also include one of the following values:
Value | Meaning
TPM_HORIZONTAL | If the menu cannot be shown at the specified location without overlapping the excluded rectangle, the system tries to accommodate the requested horizontal alignment before the requested vertical alignment.
TPM_VERTICAL | If the menu cannot be shown at the specified location without overlapping the excluded rectangle, the system tries to accommodate the requested vertical alignment before the requested horizontal alignment.

The excluded rectangle is a portion of the screen that the menu should not overlap; it is specified by lptpm.

x
Horizontal location of the shortcut menu, in screen coordinates.
y
Vertical location of the shortcut menu, in screen coordinates.
hwnd
Handle to the window that owns the shortcut menu. This window receives all messages from the menu. The window does not receive a WM_COMMAND message from the menu until the function returns.

If you specify TPM_NONOTIFY in the fuFlags parameter, the function does not send messages to the window identified by hwnd. However, you still have to pass a window handle in hwnd. It can be any window handle from your application.

lptpm
Pointer to a TPMPARAMS structure that specifies an area of the screen the menu should not overlap. This parameter can be NULL.

Return Values

If you specify TPM_RETURNCMD in the fuFlags parameter, the return value is the menu-item identifier of the item that the user selected. If the user cancels the menu without making a selection, or if an error occurs, then the return value is zero.

If you do not specify TPM_RETURNCMD in the fuFlags parameter, the return value is nonzero if the function succeeds and zero if it fails. To get extended error information, call GetLastError.

Remarks

Windows CE: Windows CE does not support the following flags for the uFlags parameter:

TPM_NONOTIFY

TPM_LEFTBUTTON

TPM_RIGHTBUTTON

TPM_HORIZONTAL

TPM_VERTICAL

The lptpm parameter must be set to NULL.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Menus Overview, Menu Functions, CreatePopupMenu, GetSubMenu, TPMPARAMS, TrackPopupMenu, WM_COMMAND


Menu Structures

The following structures are used with menus.

MDINEXTMENU
MENUEX_TEMPLATE_HEADER
MENUEX_TEMPLATE_ITEM
MENUITEMINFO
MENUITEMTEMPLATE
MENUITEMTEMPLATEHEADER
TPMPARAMS


MDINEXTMENU

The MDINEXTMENU structure contains information about the menu to be activated.

typedef struct tagMDINEXTMENU
{
    HMENU  hmenuIn;
    HMENU  hmenuNext;
    HWND   hwndNext;
} MDINEXTMENU, *PMDINEXTMENU, FAR * LPMDINEXTMENU;

Members

hmenuIn
Returns the handle to the current menu.
hmenuNext
Specifies a handle to the menu to be activated.
hwndNext
Specifies a handle to the window to receive the menu notification messages.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Menus Overview, Menu Structures, WM_NEXTMENU


MENUEX_TEMPLATE_HEADER

The MENUEX_TEMPLATE_HEADER structure defines the header for an extended menu template. The structure definition given here is for explanation only; it is not present in any standard header file.

// typedef struct
//     WORD  wVersion;
//     WORD  wOffset;
//     DWORD dwHelpId;
// } MENUEX_TEMPLATE_HEADER;

Members

wVersion
Template version number. This member must be 1 for extended menu templates.
wOffset
Offset of the first MENUEX_TEMPLATE_ITEM structure, relative to the end of this structure member. If the first item definition immediately follows the dwHelpId member, this member should be 4.
dwHelpId
Help identifier of menu bar.

Remarks

An extended menu template consists of a MENUEX_TEMPLATE_HEADER structure followed by one or more contiguous MENUEX_TEMPLATE_ITEM structures. The MENUEX_TEMPLATE_ITEM structures, which are variable in length, are aligned on doubleword boundaries. To create a menu from an extended menu template in memory, use the LoadMenuIndirect function.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.

See Also

Menus Overview, Menu Structures, LoadMenuIndirect, MENUEX_TEMPLATE_ITEM


MENUEX_TEMPLATE_ITEM

The MENUEX_TEMPLATE_ITEM structure defines a menu item in an extended menu template. The structure definition given here is for explanation only; it is not present in any standard header file.

// typedef struct {
//     DWORD  dwType;
//     DWORD  dwState;
//     UINT   uId;
//     WORD   bResInfo;
//     WCHAR  szText[1];
//     // DWORD dwHelpId;
// } MENUEX_TEMPLATE_ITEM;

Members

dwType
Menu item type. This member can be a combination of the type (beginning with MFT) values listed with the MENUITEMINFO structure.
dwState
Menu item state. This member can be a combination of the state (beginning with MFS) values listed with the MENUITEMINFO structure.
uId
Menu item identifier. This is an application-defined 16-bit value that Handle to the menu item. In an extended menu resource, items that open drop-down menus or submenus as well as command items can have identifiers.
bResInfo
Value specifying whether the menu item is the last item in the menu bar, drop-down menu, submenu, or shortcut menu and whether it is an item that opens a drop-down menu or submenu. This member can be zero or more of these values:
Value | Meaning
0x80 | The structure defines the last menu item in the menu bar, drop-down menu, submenu, or shortcut menu.
0x01 | The structure defines a item that opens a drop-down menu or submenu. Subsequent structures define menu items in the corresponding drop-down menu or submenu.

For 32-bit applications, this member is a WORD; for 16-bit applications, it is a BYTE.

szText
Menu item text. This member, which is a null-terminated Unicode string, is aligned on a word boundary. The size of the menu item definition varies depending on the length of this string.
dwHelpId
Help identifier for a drop-down menu or submenu. This member, which is included only for items that open drop-down menus or submenus, is located at the first doubleword boundary following the variable-length szText member.

Remarks

An extended menu template consists of a MENUEX_TEMPLATE_HEADER structure followed by one or more contiguous MENUEX_TEMPLATE_ITEM structures. The MENUEX_TEMPLATE_ITEM structures, which are variable in length, are aligned on doubleword boundaries. To create a menu from an extended menu template in memory, use the LoadMenuIndirect function.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.

See Also

Menus Overview, Menu Structures, LoadMenuIndirect, MENUEX_TEMPLATE_HEADER, MENUITEMINFO


MENUITEMINFO

The MENUITEMINFO structure contains information about a menu item.

typedef struct tagMENUITEMINFO {
    UINT    cbSize;
    UINT    fMask;
    UINT    fType;
    UINT    fState;
    UINT    wID;
    HMENU   hSubMenu;
    HBITMAP hbmpChecked;
    HBITMAP hbmpUnchecked;
    DWORD   dwItemData;
    LPTSTR  dwTypeData;
    UINT    cch;
} MENUITEMINFO, FAR *LPMENUITEMINFO;

Members

cbSize
Size of structure, in bytes.
fMask
Members to retrieve or set. This member can be one or more of these values:
Value | Meaning
MIIM_CHECKMARKS | Retrieves or sets the hbmpChecked and hbmpUnchecked members.
MIIM_DATA | Retrieves or sets the dwItemData member.
MIIM_ID | Retrieves or sets the wID member.
MIIM_STATE | Retrieves or sets the fState member.
MIIM_SUBMENU | Retrieves or sets the hSubMenu member.
MIIM_TYPE | Retrieves or sets the fType and dwTypeData members.

fType
Menu item type. This member can be one or more of these values:
Value | Meaning
MFT_BITMAP | Displays the menu item using a bitmap. The low-order word of the dwTypeData member is the bitmap handle, and the cch member is ignored.
MFT_MENUBARBREAK | Places the menu item on a new line (for a menu bar) or in a new column (for a drop-down menu, submenu, or shortcut menu). For a drop-down menu, submenu, or shortcut menu, a vertical line separates the new column from the old.
MFT_MENUBREAK | Places the menu item on a new line (for a menu bar) or in a new column (for a drop-down menu, submenu, or shortcut menu). For a drop-down menu, submenu, or shortcut menu, the columns are not separated by a vertical line.
MFT_OWNERDRAW | Assigns responsibility for drawing the menu item to the window that owns the menu. The window receives a WM_MEASUREITEM message before the menu is displayed for the first time, and a WM_DRAWITEM message whenever the appearance of the menu item must be updated. If this value is specified, the dwTypeData member contains an application-defined 32-bit value.
MFT_RADIOCHECK | Displays checked menu items using a radio-button mark instead of a check mark if the hbmpChecked member is NULL.
MFT_RIGHTJUSTIFY | Right-justifies the menu item and any subsequent items. This value is valid only if the menu item is in a menu bar.
MFT_RIGHTORDER | Windows 95, Windows NT 5.0, and later: Specifies that menus cascade right-to-left (the default is left-to-right). This is used to support right-to-left languages, such as Arabic and Hebrew. `
MFT_SEPARATOR | Specifies that the menu item is a separator. A menu item separator appears as a horizontal dividing line. The dwTypeData and cch members are ignored. This value is valid only in a drop-down menu, submenu, or shortcut menu.
MFT_STRING | Displays the menu item using a text string. The dwTypeData member is the pointer to a null-terminated string, and the cch member is the length of the string.

The MFT_BITMAP, MFT_SEPARATOR, and MFT_STRING values cannot be combined with one another.

fState
Menu item state. This member can be one or more of these values:
Value | Meaning
MFS_CHECKED | Checks the menu item. For more information about checked menu items, see the hbmpChecked member.
MFS_DEFAULT | Specifies that the menu item is the default. A menu can contain only one default menu item, which is displayed in bold.
MFS_DISABLED | Disables the menu item so that it cannot be selected, but does not gray it.
MFS_ENABLED | Enables the menu item so that it can be selected. This is the default state.
MFS_GRAYED | Disables the menu item and grays it so that it cannot be selected.
MFS_HILITE | Highlights the menu item.
MFS_UNCHECKED | Unchecks the menu item. For more information about unchecked menu items, see the hbmpUnchecked member.
MFS_UNHILITE | Removes the highlight from the menu item. This is the default state.

wID
Application-defined 16-bit value that identifies the menu item.
hSubMenu
Handle to the drop-down menu or submenu associated with the menu item. If the menu item is not an item that opens a drop-down menu or submenu, this member is NULL.
hbmpChecked
Handle to the bitmap to display next to the item if it is checked. If this member is NULL, a default bitmap is used. If the MFT_RADIOCHECK type value is specified, the default bitmap is a bullet. Otherwise, it is a check mark.
hbmpUnchecked
Handle to the bitmap to display next to the item if it is not checked. If this member is NULL, no bitmap is used.
dwItemData
Application-defined value associated with the menu item.
dwTypeData
Content of the menu item. This member is used only if the MIIM_TYPE flag is set in the fMask member.

Before calling GetMenuItemInfo, the application must set this member to point to a buffer whose length is specified by the cch member. If the retrieved menu item is of the type MFT_STRING, then GetMenuItemInfo copies the menu item text to the buffer. If the retrieved menu item is of some other type, then GetMenuItemInfo sets the dwTypeData member to a value whose type is specified by the fType member.

When using with the SetMenuItemInfo function, this member should contains a value whose type is specified by the fType member.

cch
Length of the menu item text when information is received about a menu item of the MFT_STRING type. This member is used only if the MIIM_TYPE flag is set in the fMask member and is zero otherwise. This member is ignored when the content of a menu item is set by calling SetMenuItemInfo.

Before calling GetMenuItemInfo, the application must set this member to the length of the buffer pointed to by the dwTypeData member. If the retrieved menu item is of type MFT_STRING (as indicated by the fType member), then GetMenuItemInfo sets cch to the length of the retrieved string. If the retrieved menu item is of some other type, GetMenuItemInfo sets the cch field to zero.

Remarks

The MENUITEMINFO structure is used with the GetMenuItemInfo, InsertMenuItem, and SetMenuItemInfo functions.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Unicode: Defined as Unicode and ANSI structures.

See Also

Menus Overview, Menu Structures, GetMenuItemInfo, InsertMenuItem, SetMenuItemInfo, WM_DRAWITEM, WM_MEASUREITEM


MENUITEMTEMPLATE

The MENUITEMTEMPLATE structure defines a menu item in a menu template.

typedef struct {
    WORD mtOption;       // menu item flags
    WORD mtID;           // menu item identifier
    WCHAR mtString[1];   // null-terminated string for menu item
} MENUITEMTEMPLATE;

Members

mtOption
Specifies one or more of the following predefined menu options that control the appearance of the menu item:
Value | Meaning
MF_CHECKED | Indicates that the menu item has a check mark next to it.
MF_GRAYED | Indicates that the menu item is initially inactive and drawn with a gray effect.
MF_HELP | Indicates that the menu item has a vertical separator to its left.
MF_MENUBARBREAK | Indicates that the menu item is placed in a new column. The old and new columns are separated by a bar.
MF_MENUBREAK | Indicates that the menu item is placed in a new column.
MF_OWNERDRAW | Indicates that the owner window of the menu is responsible for drawing all visual aspects of the menu item, including highlighted, checked, and inactive states. This option is not valid for an item in a menu bar.
MF_POPUP | Indicates that the item is one that opens a drop-down menu or submenu.

mtID
Specifies the menu item identifier of a command item; a command item sends a command message to its owner window. The MENUITEMTEMPLATE structure for an item that opens a drop-down menu or submenu does not contain the mtID member.
mtString
Specifies the null-terminated string for the menu item.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Menus Overview, Menu Structures, LoadMenuIndirect, MENUITEMTEMPLATEHEADER


MENUITEMTEMPLATEHEADER

The MENUITEMTEMPLATEHEADER structure defines the header for a menu template. A complete menu template consists of a header and one or more menu item lists.

typedef struct {          // mith
    WORD versionNumber;   // version number; must be zero
    WORD offset;          // offset first MENUITEMTEMPLATE structure
} MENUITEMTEMPLATEHEADER;

Members

versionNumber
Specifies the version number. This member must be zero.
offset
Specifies the offset, in bytes, from the end of the header. The menu item list begins at this offset. Usually, this member is zero, and the menu item list follows immediately after the header.

Remarks

One or more MENUITEMTEMPLATE structures are combined to form the menu item list.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Menus Overview, Menu Structures, LoadMenuIndirect, MENUITEMTEMPLATE


TPMPARAMS

The TPMPARAMS structure contains extended parameters for the TrackPopupMenuEx function.

typedef struct tagTPMPARAMS {
    UINT cbSize;
    RECT rcExclude;
} TPMPARAMS, FAR *LPTPMPARAMS;

Members

cbsize
Size of structure, in bytes.
rcExclude
Rectangle to exclude when positioning the window, in screen coordinates.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Menus Overview, Menu Structures, TrackPopupMenuEx, Rectangle


Menu Messages

The following messages are used with menus.

WM_COMMAND
WM_CONTEXTMENU
WM_DRAWITEM
WM_ENTERMENULOOP
WM_EXITMENULOOP
WM_INITMENU
WM_INITMENUPOPUP
WM_MEASUREITEM
WM_MENUCHAR
WM_MENUSELECT
WM_NEXTMENU
WM_SYSCOMMAND


WM_CONTEXTMENU

The WM_CONTEXTMENU message notifies a window that the user clicked the right mouse button (right clicked) in the window.

hwnd = (HWND) wParam;
xPos = LOWORD(lParam);
yPos = HIWORD(lParam);

Parameters

hwnd
Handle to the window in which the user right clicked the mouse. This can be a child window of the window receiving the message. For more information about processing this message, see the Remarks section.
xPos
Horizontal position of the cursor, in screen coordinates, at the time of the mouse click.
yPos
Vertical position of the cursor, in screen coordinates, at the time of the mouse click.

Return Values

No return value.

Remarks

A window can process this message by displaying a shortcut menu using the TrackPopupMenu or TrackPopupMenuEx function.

If a window does not display a shortcut menu it should pass this message to the DefWindowProc function. If a window is a child window, DefWindowProc sends the message to the parent. Otherwise, DefWindowProc displays a default shortcut menu if the specified position is in the window's caption.

DefWindowProc generates the WM_CONTEXTMENU message when it processes the WM_RBUTTONUP or WM_NCRBUTTONUP message.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Menus Overview, Menu Messages, DefWindowProc, TrackPopupMenu, TrackPopupMenuEx, WM_NCRBUTTONUP, WM_RBUTTONUP


WM_ENTERMENULOOP

The WM_ENTERMENULOOP message informs an application's main window procedure that a menu modal loop has been entered.

WM_ENTERMENULOOP
wParam = (BOOL) fIsTrackPopupMenu  // flags a shortcut menu
lParam = 0 ;                       // not used; must be zero

Parameters

fIsTrackPopupMenu
Specifies whether the window menu was entered using the TrackPopupMenu function. This parameter has a value of TRUE if the window menu was entered using TrackPopupMenu, and FALSE if it was not.

Return Values

An application should return zero if it processes this message.

Remarks

The DefWindowProc function returns zero.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Menus Overview, Menu Messages, DefWindowProc, WM_EXITMENULOOP


WM_EXITMENULOOP

The WM_EXITMENULOOP message informs an application's main window procedure that a menu modal loop has been exited.

WM_EXITLOOP
wParam = (BOOL) fIsTrackPopupMenu    // flags a shortcut menu
lParam = 0 ;                         // not used; must be zero

Parameters

fIsTrackPopupMenu
Specifies whether the menu involved is a shortcut menu. This parameter has a value of TRUE if it is a shortcut menu, FALSE if it isn't.

Return Values

An application should return zero if it processes this message.

Remarks

The DefWindowProc function returns zero.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Menus Overview, Menu Messages, DefWindowProc, WM_ENTERMENULOOP


WM_NEXTMENU

The WM_NEXTMENU message is sent to an application when the right or left arrow key is used to switch between the menu bar and the system menu.

WM_NEXTMENU
nVirtKey = (int) wParam;
pmdin = (LPMDINEXTMENU) lParam;

Parameters

nVirtKey
Value of wParam. Specifies virtual-key code of the key.
pmdin
Value of lParam. Specifies the address of the MDINEXTMENU structure that contains information about the menu to be activated.

Remarks

In responding to this message, the application can specify the menu to switch to in the hmenuNext member of MDINEXTMENU and the window to receive the menu notification messages in the hwndNext member of the MDINEXTMENU structure. You must set both members for the changes to take effect (they are initially NULL).

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Menus Overview, Menu Messages, MDINEXTMENU


Resources

A resource is binary data that you can add to the executable file of a Win32-based application. A resource can be either standard or defined. The data in a standard resource describes an icon, cursor, menu, dialog box, bitmap, enhanced metafile, font, accelerator table, message-table entry, string-table entry, or version. An application-defined resource, also called a custom resource, contains any data required by a specific application.


About Resources

This overview describes the functions that enable applications to find a resource in a module; load a resource into memory; add, delete or replace a resource in an executable file; and generate a list of the resources contained in a module. For specific information about the organization of resource data within executable files, refer to the resource formats documentation.

For information about how to create standard resources, refer to the following table.

Resource | Topic
Accelerator table | Keyboard Accelerators
Bitmap | Bitmaps
Cursor | Cursors
Dialog box | Dialog Boxes
Enhanced metafile | Metafiles
Font | Fonts and Text
Icon | Icons
Menu | Menus
Message-table entry | Your message-compiler documentation
String-table entry | String Manipulation
Version information | File Installation Library

For information about how to include resource data in a Win32-based executable file, refer to the documentation for your resource compiler.


Finding and Loading Resources

Before using a resource, an application must load it into memory. The FindResource and FindResourceEx functions find a resource in a module and return a handle to the binary resource data. FindResource locates a resource by type and name. FindResourceEx locates the resource by type, name, and language. Information about FindResource in this topic also applies to FindResourceEx.

The LoadResource function uses the resource handle returned by FindResource to load the resource into memory. After an application loads a resource by using LoadResource, the system automatically unloads and reloads the resource as memory conditions and application execution require. Thus, an application need not explicitly unload a resource it no longer needs.

An application can use FindResource and LoadResource to find and load any type of resource, but these functions should be used only if the application must access the binary resource data for subsequent function calls. To use a resource immediately, an application should use one of the following resource-specific functions to find and load resources in one call.

Function | Action
FormatMessage | Loads and formats a message-table entry.
LoadAccelerators | Loads an accelerator table.
LoadBitmap | Loads a bitmap resource.
LoadCursor | Loads a cursor resource.
LoadIcon | Loads an icon resource.
LoadImage | Loads an icon, cursor, bitmap, or enhanced metafile resource.
LoadMenu | Loads a menu resource.
LoadString | Loads a string-table entry.

Before terminating, an application should release the memory occupied by accelerator tables, bitmaps, cursors, icons, and menus by using one of the functions in the following table.

Resource | Release function
Accelerator table | DestroyAcceleratorTable
Bitmap | DeleteObject
Cursor | DestroyCursor
Icon | DestroyIcon
Menu | DestroyMenu

When the application terminates, the system automatically releases the memory occupied by the other types of resources.


Adding, Deleting, and Replacing Resources

Applications must frequently add, delete, or replace resources in executable files. Two methods can be used to accomplish these tasks. The first is to edit the resource-definition file, recompile the resources, and add the recompiled resources to the application's executable file. The second method is to copy the resource data directly into the application's executable file.

For example, to localize an English-language application for use in Norway, it may be necessary to replace the English dialog box with one using Norwegian. A developer creates an appropriate dialog box by using a dialog box editor or by writing a template in the resource-definition file. The developer then recompiles the resources and adds the new resources to the application's executable file.

If an appropriate dialog box exists in binary form, however, the developer can copy the data directly to the executable file being localized by using three Win32 functions. The BeginUpdateResource function creates an update handle for the executable file whose resources are to be changed. The UpdateResource function uses this handle to add, delete, or replace a resource in the executable file. The EndUpdateResource function closes the handle.

After an update handle to an executable file is created by BeginUpdateResource, an application can use UpdateResource repeatedly to make changes to the resource data. Each call to UpdateResource contributes to an internal list of additions, deletions, and replacements but does not actually write the data to the executable file. Immediately before closing the update handle, EndUpdateResource writes the accumulated changes to the executable file.

Sometimes, an application must copy resources or find resource sizes. The LoadLibrary function provides a module handle to an executable file whose resources are to be copied, and the LockResource function provides a pointer to the resource data in the specified module. The SizeofResource function returns the size, in bytes, of a specified resource.


Enumerating Resources

Three Win32 functions enable an application to obtain lists of resource types, names, and languages in a specified module. The EnumResourceTypes function provides a list of resource types found in the module, the EnumResourceNames function provides the name of each resource within a given type, and the EnumResourceLanguages function provides the language of each resource of a given name and type. These functions and their associated callback functions enable applications to create a list of all resources in a module. This process is described in Creating a Resource List.


Win32 Resource File Formats

This section describes the format of the binary resource file that the resource compiler creates based on the contents of the resource-definition file. This file usually has an .RES extension. The linker reformats the .RES file into a resource object file and then links it to the executable file of a Win32-based application.

A binary resource file consists of a number of concatenated resource entries. Each entry consists of a resource header and the data for that resource. A resource header is DWORD-aligned in the file and consists of the following:

  • A DWORD that contains the size of the resource header
  • A DWORD that contains the size of the resource data
  • The resource type
  • The resource name
  • Additional resource information

The RESOURCEHEADER structure describes the format of this header. The data for the resource follows the resource header and is specific to each type of resource. Some resources also employ a resource-specific group header structure to provide information about a group of resources.

An accelerator table is one resource entry in a resource file. It does not have a group header. An ACCELTABLEENTRY structure describes each entry in the accelerator table. Multiple accelerator tables are permitted.

A dialog box is also one resource entry in the resource file. It consists of one DLGTEMPLATE dialog box header structure plus one DLGITEMTEMPLATE structure for each control in the dialog box. The DLGTEMPLATEEX and the DLGITEMTEMPLATEEX structures describe the format of extended dialog box resources.

Fonts are stored in the resource file as a group of resources. Individual fonts make up a font group. A FONT Statement resource definition statement in the .RC file defines each font. Each individual font in the resource consists of the complete contents of the related .FNT file. A FONTGROUPHDR structure follows all the individual font components in the .RES file.

Font resources are not added to the resources of a specific application. Instead, they are normally added to executable files that have a .FON extension. These files are usually resource-only dynamic-link libraries (DLLs) rather than applications.

The system handles each icon and cursor as a single file. However, these are stored in .RES files and in executable files as a group of icon resources or a group of cursor resources. The file formats of icon and cursor resources are similar. In the .RES file a resource group header follows all of the individual icon or cursor group components.

The format of each icon component closely resembles the format of the .ICO file. Each icon image is stored in a BITMAPINFO structure followed by the color device-independent bitmap (DIB) bits of the icon's XOR mask. The monochrome DIB bits of the icon's AND mask follow the color DIB bits.

The format of each cursor component resembles the format of the .CUR file. Each cursor image is stored in a BITMAPINFO structure followed by the monochrome device-independent bitmap (DIB) bits of the cursor's XOR mask, and then by the monochrome DIB bits of the cursor's AND mask. Note that there is a difference in the bitmaps of the two resources: Unlike icons, cursor XOR masks do not have color DIB bits. Although the bitmaps of the cursor masks are monochrome and do not have DIB headers or color tables, the bits are still in DIB format with respect to alignment and direction. Another significant difference between cursors and icons is that cursors have a hotspot and icons do not.

The group header for both icon and cursor resources consists of a NEWHEADER structure plus one or more RESDIR structures. There is one RESDIR structure for each icon or cursor. The group header contains the information a Win32-based application needs to select the correct icon or cursor to display. Both the group header and the data that repeats for each icon or cursor in the group have a fixed length. This allows the application to randomly access the information.

A menu resource consists of a MENUHEADER structure followed by one or more NORMALMENUITEM or POPUPMENUITEM structures, one for each menu item in the menu template. The MENUEX_TEMPLATE_HEADER and the MENUEX_TEMPLATE_ITEM structures describe the format of extended menu resources.

A message table is a resource that contains formatted text for display as an error message or in a message box. The main structure in a message table resource is the MESSAGE_RESOURCE_DATA structure.

The main structure in a version resource is the VS_FIXEDFILEINFO structure. Additional structures include the VarFileInfo structure to store language information data, and StringFileInfo for user-defined string information. All strings in a version resource are in Unicode format for Win32-based applications. Each block of information is aligned on a DWORD boundary.

For a group list of the structures that describe the format of resources, see Resource Structures.


Using Resources

  • Updating resources
  • Creating a resource list


Updating Resources

The following example copies a dialog box resource from one executable file, HAND.EXE, to another, FOOT.EXE, by following these steps:

  1. Use the LoadLibrary function to load the executable file HAND.EXE.
  2. Use the FindResource and LoadResource functions to locate and load the dialog box resource.
  3. Use the LockResource function to retrieve a pointer to the dialog box resource data.
  4. Use the BeginUpdateResource function to open an update handle to FOOT.EXE.
  5. Use the UpdateResource function to copy the dialog box resource from HAND.EXE to FOOT.EXE.
  6. Use the EndUpdateResource function to complete the update.

The following code implements these steps.

HRSRC hResLoad;     // handle to loaded resource
HANDLE hExe;        // handle to existing .EXE file
HRSRC hRes;         // handle/ptr. to res. info. in hExe
HANDLE hUpdateRes;  // update resource handle
char *lpResLock;    // pointer to resource data
BOOL result;

// Load the .EXE file that contains the dialog box you want to copy.
hExe = LoadLibrary("hand.exe");

if (hExe == NULL)
{
    ErrorHandler("Could not load exe.");
}

// Locate the dialog box resource in the .EXE file.
hRes = FindResource(hExe, "AboutBox", RT_DIALOG);

if (hRes == NULL)
{
    ErrorHandler("Could not locate dialog box.");
}

// Load the dialog box into global memory.
hResLoad = LoadResource(hExe, hRes);

if (hResLoad == NULL)
{
    ErrorHandler("Could not load dialog box.");
}

// Lock the dialog box into global memory.
lpResLock = LockResource(hRes);

if (lpResLock == NULL)
{
    ErrorHandler("Could not lock dialog box.");
}

// Open the file to which you want to add the dialog box resource.
hUpdateRes = BeginUpdateResource("foot.exe", FALSE);

if (hUpdateRes == NULL)
{
    ErrorHandler("Could not open file for writing.");
}

// Add the dialog box resource to the update list.
result = UpdateResource(hUpdateRes,       // update resource handle
     RT_DIALOG,                   // change dialog box resource
     "AboutBox",                  // dialog box name
     MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL),  // neutral language
     lpResLock,                   // ptr to resource info
     SizeofResource(hExe, hRes)); // size of resource info.

if (result == FALSE)
{
    ErrorHandler("Could not add resource.");
}

// Write changes to FOOT.EXE and then close it.
if (!EndUpdateResource(hUpdateRes, FALSE))
{
    ErrorHandler("Could not write changes to file.");
}

// Clean up.
if (!FreeLibrary(hExe))
{
    ErrorHandler("Could not free executable.");
}


Creating a Resource List

The following example creates a list of every resource in the HAND.EXE file. The list is written to the RESINFO.TXT file.

The code demonstrates how to load the executable file, create a file in which to write resource information, and call the EnumResourceTypes function to send each resource type found in the module to the application-defined callback function EnumTypesFunc. See EnumResTypeProc for information on callback functions of this type. This callback function uses the EnumResourceNames function to pass the name of every resource within the specified type to another application-defined callback function, EnumNamesFunc. See EnumResNameProc for information on callback functions of this type. EnumNamesFunc uses the EnumResourceLanguages function to pass the language of every resource of the specified type and name to a third callback function, EnumLangsFunc. See EnumResLangProc for information on callback functions of this type. EnumLangsFunc writes information about the resource of the specified type, name, and language to the RESINFO.TXT file.

char szBuffer[80]; // print buffer for EnumResourceTypes
DWORD cbWritten;   // number of bytes written to res. info. file
int cbString;      // length of string in sprintf

// Declare callback functions.
BOOL EnumTypesFunc(
    HANDLE hModule,
    LPTSTR lpType,
    LONG lParam);

BOOL EnumNamesFunc(
    HANDLE hModule,
    LPCTSTR lpType,
    LPTSTR lpName,
    LONG lParam);

BOOL EnumLangsFunc(
    HANDLE hModule,
    LPCTSTR lpType,
    LPCTSTR lpName,
    WORD wLang,
    LONG lParam);

// Load the .EXE whose resources you want to list.
hExe = LoadLibrary("hand.exe");

if (hExe == NULL)
{
    ErrorHandler("Could not load .EXE.");
}

// Create a file to contain the resource info.
hFile = CreateFile("resinfo.txt",      // name of file
    GENERIC_READ | GENERIC_WRITE,      // access mode
    0,                                 // share mode
    (LPSECURITY_ATTRIBUTES) NULL,      // no security
    CREATE_ALWAYS,                     // create flags
    FILE_ATTRIBUTE_NORMAL,             // file attributes
    (HANDLE) NULL);                    // no template
if (hFile == INVALID_HANDLE_VALUE) {
    ErrorHandler("Could not open file.");
}

// Find all of the loaded file's resources.
cbString = sprintf(szBuffer,
    "The file contains the following resources:\n\n");

WriteFile(hFile,           // file to hold resource info.
    szBuffer,              // what to write to the file
    (DWORD) cbString,      // number of bytes in szBuffer
    &cbWritten,            // number of bytes written
    NULL);                 // no overlapped I/O

EnumResourceTypes(hExe,              // module handle
    (ENUMRESTYPEPROC)EnumTypesFunc,  // callback function
    0);                              // extra parameter

// Unload the executable file whose resources were
// enumerated and close the file created to contain
// the resource information.

FreeLibrary(hExe);
CloseHandle(hFile);

//    FUNCTION: EnumTypesFunc(HANDLE, LPSTR, LONG)
//
//    PURPOSE:  Resource type callback

BOOL EnumTypesFunc(
    HANDLE hModule,   // module handle
    LPTSTR lpType,    // address of resource type
    LONG lParam)      // extra parameter, could be
                      // used for error checking
{
    int cbString;

    // Write the resource type to a resource information file.
    // The type may be a string or an unsigned decimal
    // integer, so test before printing.

    if ((ULONG)lpType & 0xFFFF0000)
    {
        cbString = sprintf(szBuffer, "Type: %s\n", lpType);
    }
    else
    {
        cbString = sprintf(szBuffer, "Type: %u\n", (USHORT)lpType);
    }

    WriteFile(hFile, szBuffer, (DWORD) cbString,
        &cbWritten, NULL);

    // Find the names of all resources of type lpType.
    EnumResourceNames(hModule,
        lpType,
        (ENUMRESNAMEPROC)EnumNamesFunc,
        0);

    return TRUE;
}

//    FUNCTION: EnumNamesFunc(HANDLE, LPSTR, LPSTR, LONG)
//
//    PURPOSE:  Resource name callback

BOOL EnumNamesFunc(
    HANDLE hModule,   // module handle
    LPCTSTR lpType,   // address of resource type
    LPTSTR lpName,    // address of resource name
    LONG lParam)      // extra parameter, could be
                      // used for error checking
{
    int cbString;

     // Write the resource name to a resource information file.
     // The name may be a string or an unsigned decimal
     // integer, so test before printing.

    if ((ULONG)lpName & 0xFFFF0000)
    {
        cbString = sprintf(szBuffer, "\tName: %s\n", lpName);
    }
    else
    {
        cbString = sprintf(szBuffer, "\tName: %u\n",
            (USHORT)lpName);
    }

    WriteFile(hFile, szBuffer, (DWORD) cbString,
        &cbWritten, NULL);

     // Find the languages of all resources of type
     // lpType and name lpName.

    EnumResourceLanguages(hModule,
        lpType,
        lpName,
        (ENUMRESLANGPROC)EnumLangsFunc,
        0);

    return TRUE;
}

//    FUNCTION: EnumLangsFunc(HANDLE, LPSTR, LPSTR, WORD, LONG)
//
//    PURPOSE:  Resource language callback

BOOL EnumLangsFunc(
    HANDLE hModule,  // module handle
    LPCTSTR lpType,  // address of resource type
    LPCTSTR lpName,  // address of resource name
    WORD wLang,      // resource language
    LONG lParam)     // extra parameter, could be
                        used for error checking
{
    HANDLE hResInfo;
    char szBuffer[80];
    int cbString = 0;

    hResInfo = FindResourceEx(hModule, lpType, lpName, wLang);

    // Write the resource language to the resource information file.
    cbString = sprintf(szBuffer, "\t\tLanguage: %u\n", USHORT)wLang);

    WriteFile(hFile, szBuffer, (DWORD) cbString,
        &cbWritten, NULL);

    // Write the resource handle and size to buffer.
    cbString = sprintf(szBuffer,
        "\t\thResInfo == %lx,  Size == %lu\n\n",
        hResInfo,
        SizeofResource(hModule, hResInfo));

    WriteFile(hFile, szBuffer, (DWORD) cbString,
        &cbWritten, NULL);

    return TRUE;
}


Resource Reference

The following elements are used with resources.

  • Resource Functions
  • Resource Structures
  • Resource Macros


Resource Functions

The following functions are used with resources.

BeginUpdateResource
CopyImage
EndUpdateResource
EnumResLangProc
EnumResNameProc
EnumResourceLanguages
EnumResourceNames
EnumResourceTypes
EnumResTypeProc
FindResource
FindResourceEx
LoadImage
LoadResource
LockResource
SizeofResource
UpdateResource

Obsolete Functions

FreeResource
UnlockResource


BeginUpdateResource

The BeginUpdateResource function returns a handle that can be used by the UpdateResource function to add, delete, or replace resources in an executable file.

HANDLE BeginUpdateResource(
  LPCTSTR pFileName,             // pointer to executable file name
  BOOL bDeleteExistingResources  // deletion option
);

Parameters

pFileName
Pointer to a null-terminated string that specifies a Win32-based executable file in which to update resources. An application must be able to obtain write access to this file; it cannot be currently executing. If pFileName does not specify a full path, the system searches for the file in the current directory.
bDeleteExistingResources
Specifies whether to delete the pFileName parameter's existing resources. If this parameter is TRUE, existing resources are deleted and the updated executable file includes only resources added with the UpdateResource function. If this parameter is FALSE, the updated executable file includes existing resources unless they are explicitly deleted or replaced by using UpdateResource.

Return Values

If the function succeeds, the return value is a handle that can be used by the UpdateResource and EndUpdateResource functions. The return value is NULL if the specified file is not an executable file, the executable file is already loaded, the file does not exist, or the file cannot be opened for writing. To get extended error information, call GetLastError.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Unsupported.
Windows CE: Unsupported.
Header: Declared in winbase.h.
Import Library: Use kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Resources Overview, Resource Functions, EndUpdateResource, UpdateResource


CopyImage

The CopyImage function creates a new image (icon, cursor, or bitmap) and copies the attributes of the specified image to the new one. If necessary, the function stretches the bits to fit the desired size of the new image.

HANDLE CopyImage(
  HANDLE hImage,  // handle to the image to copy
  UINT uType,     // type of image to copy
  int cxDesired,  // desired width of new image
  int cyDesired,  // desired height of new image
  UINT fuFlags    // copy flags
);

Parameters

hinst
Handle to an instance of the module that contains the image to be copied.
uType
Specifies the type of image to be copied. This parameter can be one of the following values:
Value | Meaning
IMAGE_BITMAP | Copies a bitmap.
IMAGE_CURSOR | Copies a cursor.
IMAGE_ICON | Copies an icon.

cxDesired
Specifies the desired width, in pixels, of the image.
cyDesired
Specifies the desired height, in pixels, of the image.
fuFlags
Specifies a combination of the following values:
Value | Meaning
LR_COPYDELETEORG | Deletes the original image after creating the copy.
LR_COPYRETURNORG | Creates an exact copy of the image, ignoring the cxDesired and cyDesired parameters.
LR_MONOCHROME | Creates a new monochrome image.
LR_COPYFROMRESOURCE Tries to reload an icon or cursor resource from the original resource file rather than simply copying the current image. This is useful for creating a different-sized copy when the resource file contains multiple sizes of the resource. Without this flag, CopyImage stretches the original image to the new size. If this flag is set, CopyImage uses the size in the resource file closest to the desired size.

This will succeed only if hImage was loaded by LoadIcon or LoadCursor, or by LoadImage with the LR_SHARED flag.

Return Values

If the function succeeds, the return value is the handle to the newly created image.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

When you are finished using the resource, you can release its associated memory by calling one of the functions in the following table.

Resource | Release function
Bitmap | DeleteObject
Cursor | DestroyCursor
Icon | DestroyIcon

The system automatically deletes the resource when its process terminates, however, calling the appropriate function saves memory and decreases the size of the process's working set.

QuickInfo

Windows NT: Requires version 3.5 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Resources Overview, Resource Functions, LoadImage


EndUpdateResource

The EndUpdateResource function ends a resource update in an executable file.

BOOL EndUpdateResource(
  HANDLE hUpdate, // update-file handle
  BOOL fDiscard   // write flag
);

Parameters

hUpdate
Handle used in a resource update. This handle is returned by the BeginUpdateResource function.
fDiscard
Specifies whether to write resource updates to an executable file. If this parameter is TRUE, no changes are made to the executable file. If it is FALSE, the changes are made.

Return Values

If the function succeeds and the accumulated resource modifications specified by calls to the UpdateResource function are written to the specified executable file, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Unsupported.
Windows CE: Unsupported.
Header: Declared in winbase.h.
Import Library: Use kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Resources Overview, Resource Functions, BeginUpdateResource, UpdateResource


EnumResLangProc

The EnumResLangProc function is an application-defined callback function used with the EnumResourceLanguages function. It receives resource languages. The ENUMRESLANGPROC type defines a pointer to this callback function. EnumResLangProc is a placeholder for the application-defined function name.

BOOL CALLBACK EnumResLangProc(
  HANDLE hModule,    // module handle
  LPCTSTR lpszType,  // pointer to resource type
  LPCTSTR lpszName,  // pointer to resource name
  WORD wIDLanguage,  // resource language identifier
  LONG lParam        // application-defined parameter
);

Parameters

hModule
Handle to the module whose executable file contains the resources for which the languages are being enumerated. If this parameter is NULL, the function enumerates the resource languages in the module used to create the current process.
lpszType
Pointer to a null-terminated string specifying the type name of the resource for which the language is being enumerated. For standard resource types, this parameter should be one of the following values:
Value | Meaning
RT_ACCELERATOR | Accelerator table
RT_ANICURSOR | Animated cursor
RT_ANIICON | Animated icon
RT_BITMAP | Bitmap resource
RT_CURSOR | Hardware-dependent cursor resource
RT_DIALOG | Dialog box
RT_FONT | Font resource
RT_FONTDIR | Font directory resource
RT_GROUP_CURSOR | Hardware-independent cursor resource
RT_GROUP_ICON | Hardware-independent icon resource
RT_HTML | HTML document
RT_ICON | Hardware-dependent icon resource
RT_MENU | Menu resource
RT_MESSAGETABLE | Message-table entry
RT_PLUGPLAY | Plug and play resource
RT_RCDATA | Application-defined resource (raw data)
RT_STRING | String-table entry
RT_VERSION | Version resource
RT_VXD | VXD

lpszName
Pointer to a null-terminated string specifying the name of the resource for which the language is being enumerated.
wIDLanguage
Specifies the language identifier for the resource for which the language is being enumerated. The EnumResourceLanguages function provides this value. For a list of the primary language identifiers and sublanguage identifiers that constitute a language identifier, see MAKELANGID.
lParam
Specifies the application-defined parameter passed to the EnumResourceLanguages function. This parameter can be used in error checking.

Return Values

This callback function should return TRUE to continue enumeration; otherwise, it should return FALSE to stop enumeration.

Remarks

An application must register this function by passing its address to the EnumResourceLanguages function.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winbase.h.
Import Library: User-defined.

See Also

Resources Overview, Resource Functions, EnumResourceLanguages, MAKELANGID


EnumResNameProc

The EnumResNameProc function is an application-defined callback function used with the EnumResourceNames function. It receives resource names. The ENUMRESNAMEPROC type defines a pointer to this callback function. EnumResNameProc is a placeholder for the application-defined function name.

BOOL CALLBACK EnumResNameProc(
  HANDLE hModule,   // module handle
  LPCTSTR lpszType, // pointer to resource type
  LPTSTR lpszName,  // pointer to resource name
  LONG lParam       // application-defined parameter
);

Parameters

hModule
Handle to the module whose executable file contains the resources for which the names are being enumerated. If this parameter is NULL, the function enumerates the resource names in the module used to create the current process.
lpszType
Pointer to a null-terminated string specifying the type name of the resource for which the name is being enumerated. For standard resource types, this parameter should be one of the following values:
Value | Meaning
RT_ACCELERATOR | Accelerator table
RT_ANICURSOR | Animated cursor
RT_ANIICON | Animated icon
RT_BITMAP | Bitmap resource
RT_CURSOR | Hardware-dependent cursor resource
RT_DIALOG | Dialog box
RT_FONT | Font resource
RT_FONTDIR | Font directory resource
RT_GROUP_CURSOR | Hardware-independent cursor resource
RT_GROUP_ICON | Hardware-independent icon resource
RT_HTML | HTML document
RT_ICON | Hardware-dependent icon resource
RT_MENU | Menu resource
RT_MESSAGETABLE | Message-table entry
RT_PLUGPLAY | Plug and play resource
RT_RCDATA | Application-defined resource (raw data)
RT_STRING | String-table entry
RT_VERSION | Version resource
RT_VXD | VXD

lpszName
Pointer to a null-terminated string specifying the name of the resource for which the name is being enumerated.
lParam
Specifies the application-defined parameter passed to the EnumResourceNames function. This parameter can be used in error checking.

Return Values

This callback function should return TRUE to continue enumeration; otherwise, it should return FALSE to stop enumeration.

Remarks

An application must register this function by passing its address to the EnumResourceNames function.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winbase.h.
Import Library: User-defined.

See Also

Resources Overview, Resource Functions, EnumResourceNames


EnumResourceLanguages

The EnumResourceLanguages function searches a module for each resource of the specified type and name and passes the language of each resource it locates to a defined callback function.

BOOL EnumResourceLanguages(
  HMODULE hModule,             // resource-module handle
  LPCTSTR lpType,              // pointer to resource type
  LPCTSTR lpName,              // pointer to resource name
  ENUMRESLANGPROC lpEnumFunc,  // pointer to callback function
  LONG lParam                  // application-defined parameter
);

Parameters

hModule
Handle to the module whose executable file contains the resources for which the languages are to be enumerated. If this parameter is NULL, the function enumerates the resource languages in the module used to create the current process.
lpType
Pointer to a null-terminated string specifying the type of the resource for which the language is being enumerated. For standard resource types, this parameter can be one of the following values:
Value | Meaning
RT_ACCELERATOR | Accelerator table
RT_ANICURSOR | Animated cursor
RT_ANIICON | Animated icon
RT_BITMAP | Bitmap resource
RT_CURSOR | Hardware-dependent cursor resource
RT_DIALOG | Dialog box
RT_FONT | Font resource
RT_FONTDIR | Font directory resource
RT_GROUP_CURSOR | Hardware-independent cursor resource
RT_GROUP_ICON | Hardware-independent icon resource
RT_HTML | HTML document
RT_ICON | Hardware-dependent icon resource
RT_MENU | Menu resource
RT_MESSAGETABLE | Message-table entry
RT_PLUGPLAY | Plug and play resource
RT_RCDATA | Application-defined resource (raw data)
RT_STRING | String-table entry
RT_VERSION | Version resource
RT_VXD | VXD

lpName
Pointer to a null-terminated string specifying the name of the resource for which the language is being enumerated.
lpEnumFunc
Pointer to the callback function to be called for each enumerated resource language. For more information, see EnumResLangProc.
lParam
Specifies an application-defined value passed to the callback function. This parameter may be used in error checking.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The EnumResourceLanguages function continues to enumerate resource languages until the callback function returns FALSE or all resource languages have been enumerated.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winbase.h.
Import Library: Use kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows and Windows NT.

See Also

Resources Overview, Resource Functions, EnumResLangProc, EnumResourceNames, EnumResourceTypes


EnumResourceNames

The EnumResourceNames function searches a module for each resource of the specified type and passes the name of each resource it locates to an application-defined callback function.

BOOL EnumResourceNames(
  HINSTANCE hModule,           // resource-module handling
  LPCTSTR lpszType,            // pointer to resource type
  ENUMRESNAMEPROC lpEnumFunc,  // pointer to callback function
  LONG lParam                  // application-defined parameter
);

Parameters

hModule
Handle to the module whose executable file contains the resources for which the names are to be enumerated. If this parameter is NULL, the function enumerates the resource names in the module used to create the current process.
lpszType
Pointer to a null-terminated string specifying the type name of the resource for which the name is being enumerated. For standard resource types, this parameter can be one of the following values:
Value | Meaning
RT_ACCELERATOR | Accelerator table
RT_ANICURSOR | Animated cursor
RT_ANIICON | Animated icon
RT_BITMAP | Bitmap resource
RT_CURSOR | Hardware-dependent cursor resource
RT_DIALOG | Dialog box
RT_FONT | Font resource
RT_FONTDIR | Font directory resource
RT_GROUP_CURSOR | Hardware-independent cursor resource
RT_GROUP_ICON | Hardware-independent icon resource
RT_HTML | HTML document
RT_ICON | Hardware-dependent icon resource
RT_MENU | Menu resource
RT_MESSAGETABLE | Message-table entry
RT_PLUGPLAY | Plug and play resource
RT_RCDATA | Application-defined resource (raw data)
RT_STRING | String-table entry
RT_VERSION | Version resource
RT_VXD | VXD

lpEnumFunc
Pointer to the callback function to be called for each enumerated resource name. For more information, see EnumResNameProc.
lParam
Specifies an application-defined value passed to the callback function. This parameter can be used in error checking.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The EnumResourceNames function continues to enumerate resource names until the callback function returns FALSE or all resource names have been enumerated.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winbase.h.
Import Library: Use kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows and Windows NT.

See Also

Resources Overview, Resource Functions, EnumResNameProc, EnumResourceLanguages, EnumResourceTypes


EnumResourceTypes

The EnumResourceTypes function searches a module for resources and passes each resource type it finds to an application-defined callback function.

BOOL EnumResourceTypes(
  HMODULE hModule,             // resource-module handle
  ENUMRESTYPEPROC lpEnumFunc,  // pointer to callback function
  LONG lParam                  // application-defined parameter
);

Parameters

hModule
Handle to the module whose executable file contains the resources for which the types are to be enumerated. If this parameter is NULL, the function enumerates the resource types in the module used to create the current process.
lpEnumFunc
Pointer to the callback function to be called for each enumerated resource type. For more information, see the EnumResTypeProc function.
lParam
Specifies an application-defined value passed to the callback function.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The EnumResourceTypes function continues to enumerate resource types until the callback function returns FALSE or all resource types have been enumerated.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winbase.h.
Import Library: Use kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows and Windows NT.

See Also

Resources Overview, Resource Functions, EnumResourceLanguages, EnumResourceNames, EnumResTypeProc


EnumResTypeProc

The EnumResTypeProc function is an application-defined callback function used with the EnumResourceTypes function. It receives resource types. The ENUMRESTYPEPROC type defines a pointer to this callback function. EnumResTypeProc is a placeholder for the application-defined function name.

BOOL CALLBACK EnumResTypeProc(
  HANDLE hModule,  // resource-module handle
  LPTSTR lpszType, // pointer to resource type
  LONG lParam      // application-defined parameter
);

Parameters

hModule
Handle to the module whose executable file contains the resources for which the types are to be enumerated. If this parameter is NULL, the function enumerates the resource types in the module used to create the current process.
lpszType
Pointer to a null-terminated string specifying the type name of the resource for which the type is being enumerated. For standard resource types, this parameter can be one of the following values:
Value | Meaning
RT_ACCELERATOR | Accelerator table
RT_ANICURSOR | Animated cursor
RT_ANIICON | Animated icon
RT_BITMAP | Bitmap resource
RT_CURSOR | Hardware-dependent cursor resource
RT_DIALOG | Dialog box
RT_FONT | Font resource
RT_FONTDIR | Font directory resource
RT_GROUP_CURSOR | Hardware-independent cursor resource
RT_GROUP_ICON | Hardware-independent icon resource
RT_HTML | HTML document
RT_ICON | Hardware-dependent icon resource
RT_MENU | Menu resource
RT_MESSAGETABLE | Message-table entry
RT_PLUGPLAY | Plug and play resource
RT_RCDATA | Application-defined resource (raw data)
RT_STRING | String-table entry
RT_VERSION | Version resource
RT_VXD | VXD

lParam
Specifies the application-defined parameter passed to the EnumResourceTypes function. This parameter can be used in error checking.

Return Values

The callback function should return TRUE to continue enumeration; otherwise, it should return FALSE to stop enumeration.

Remarks

An application must register this function by passing its address to the EnumResourceTypes function.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winbase.h.
Import Library: User-defined.

See Also

Resources Overview, Resource Functions, EnumResourceTypes


FindResource

The FindResource function determines the location of a resource with the specified type and name in the specified module.

HRSRC FindResource(
  HMODULE hModule, // module handle
  LPCTSTR lpName,  // pointer to resource name
  LPCTSTR lpType   // pointer to resource type
);

Parameters

hModule
Handle to the module whose executable file contains the resource.

A value of NULL specifies the module handle associated with the image file that the operating system used to create the current process.

lpName
Specifies the name of the resource. For more information, see the Remarks section.
lpType
Specifies the resource type. For more information, see the Remarks section. For standard resource types, this parameter can be one of the following values:
Value | Meaning
RT_ACCELERATOR | Accelerator table
RT_ANICURSOR | Animated cursor
RT_ANIICON | Animated icon
RT_BITMAP | Bitmap resource
RT_CURSOR | Hardware-dependent cursor resource
RT_DIALOG | Dialog box
RT_FONT | Font resource
RT_FONTDIR | Font directory resource
RT_GROUP_CURSOR | Hardware-independent cursor resource
RT_GROUP_ICON | Hardware-independent icon resource
RT_HTML | HTML document
RT_ICON | Hardware-dependent icon resource
RT_MENU | Menu resource
RT_MESSAGETABLE | Message-table entry
RT_RCDATA | Application-defined resource (raw data)
RT_STRING | String-table entry
RT_VERSION | Version resource

Return Values

If the function succeeds, the return value is a handle to the specified resource's info block. To obtain a handle to the resource, pass this handle to the LoadResource function.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

If the high-order word of the lpName or lpType parameter is zero, the low-order word specifies the integer identifier of the name or type of the given resource. Otherwise, those parameters are long pointers to null-terminated strings. If the first character of the string is a pound sign (#), the remaining characters represent a decimal number that specifies the integer identifier of the resource's name or type. For example, the string "#258" represents the integer identifier 258.

An application should reduce the amount of memory required for the resources by referring to them by integer identifier instead of by name.

When you are finished using an accelerator table, bitmap, cursor, icon, or menu, you can release its associated memory by calling one of the functions in the following table.

Resource | Release function
Accelerator table | DestroyAcceleratorTable
Bitmap | DeleteObject
Cursor | DestroyCursor
Icon | DestroyIcon
Menu | DestroyMenu

The system automatically deletes these resources when the process that created them terminates, however, calling the appropriate function saves memory and decreases the size of the process's working set.

An application can use FindResource to find any type of resource, but this function should be used only if the application must access the binary resource data when making subsequent calls to LoadLibrary and LockResource.

To use a resource immediately, an application should use one of the following resource-specific functions to find and load the resources in one call:

Function | Action
FormatMessage | Loads and formats a message-table entry.
LoadAccelerators | Loads an accelerator table.
LoadBitmap | Loads a bitmap resource.
LoadCursor | Loads a cursor resource.
LoadIcon | Loads an icon resource.
LoadMenu | Loads a menu resource.
LoadString | Loads a string-table entry.

For example, an application can use the LoadIcon function to load an icon for display on the screen. However, the application should use FindResource and LoadResource if it is loading the icon to copy its data to another application.

String resources are stored in sections of up to 16 strings per section. The strings in each section are stored as a sequence of counted (not null-terminated) Unicode strings. The LoadString function will extract the string resource from its corresponding section.

Windows CE: The hModule parameter cannot be a NULL handle.

The lpName parameter does not support the resource ID zero — that is, FindResource(h, 0 ,t) will not work as expected.

You cannot pass the RT_ANICURSOR or RT_ANIICON values in the lpType parameter.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winbase.h.
Import Library: Use kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows and Windows NT.

See Also

Resources Overview, Resource Functions, FindResourceEx, FormatMessage, LoadAccelerators, LoadBitmap, LoadCursor, LoadIcon, LoadMenu, LoadResource, LoadString, LockResource, SizeofResource


FindResourceEx

The FindResourceEx function determines the location of the resource with the specified type, name, and language in the specified module.

HRSRC FindResourceEx(
  HMODULE hModule, // resource-module handle
  LPCTSTR lpType,  // pointer to resource type
  LPCTSTR lpName,  // pointer to resource name
  WORD wLanguage   // resource language
);

Parameters

hModule
Handle to the module whose executable file contains the resource. If this parameter is NULL, the function searches the module used to create the current process.
lpType
Pointer to a null-terminated string specifying the type name of the resource. For more information, see the Remarks section. For standard resource types, this parameter can be one of the following values:
Value | Meaning
RT_ACCELERATOR | Accelerator table
RT_ANICURSOR | Animated cursor
RT_ANIICON | Animated icon
RT_BITMAP | Bitmap resource
RT_CURSOR | Hardware-dependent cursor resource
RT_DIALOG | Dialog box
RT_FONT | Font resource
RT_FONTDIR | Font directory resource
RT_GROUP_CURSOR | Hardware-independent cursor resource
RT_GROUP_ICON | Hardware-independent icon resource
RT_HTML | HTML document
RT_ICON | Hardware-dependent icon resource
RT_MENU | Menu resource
RT_MESSAGETABLE | Message-table entry
RT_RCDATA | Application-defined resource (raw data)
RT_STRING | String-table entry
RT_VERSION | Version resource

lpName
Pointer to a null-terminated string specifying the name of the resource. For more information, see the Remarks section.
wLanguage
Specifies the language of the resource. If this parameter is MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), the current language associated with the calling thread is used.

To specify a language other than the current language, use the MAKELANGID macro to create this parameter. For more information, see MAKELANGID.

Return Values

If the function succeeds, the return value is a handle to the specified resource's info block. To obtain a handle to the resource, pass this handle to the LoadResource function.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

If the high-word of the lpType or lpName parameter is zero, the low-word specifies the integer identifier of the type or name of the given resource. Otherwise, those parameters are pointers to null-terminated strings. If the first character of the string is a pound sign (#), the remaining characters represent a decimal number that specifies the integer identifier of the resource's name or type. For example, the string "#258" represents the integer identifier 258.

Applications should reduce the amount of memory required for the resources by referring to them by integer identifier instead of by name.

When you are finished using an accelerator table, bitmap, cursor, icon, or menu, you can release its associated memory by calling one of the functions in the following table.

Resource | Release function
Accelerator table | DestroyAcceleratorTable
Bitmap | DeleteObject
Cursor | DestroyCursor
Icon | DestroyIcon
Menu | DestroyMenu

The system automatically deletes these resources when the process that created them terminates, however, calling the appropriate function saves memory and decreases the size of the process's working set.

An application can use FindResourceEx to find any type of resource, but this function should be used only if the application must access the binary resource data when making subsequent calls to the LoadLibrary and LockResource functions.

To use a resource immediately, an application should use the following resource-specific functions to find and load the resources in one call:

Function | Action
FormatMessage | Loads and formats a message-table entry.
LoadAccelerators | Loads an accelerator table.
LoadBitmap | Loads a bitmap resource.
LoadCursor | Loads a cursor resource.
LoadIcon | Loads an icon resource.
LoadMenu | Loads a menu resource.
LoadString | Loads a string-table entry.

For example, an application can use the LoadIcon function to load an icon for display on the screen. However, the application should use FindResourceEx and LoadResource if it is loading the icon to copy its data to another application.

String resources are stored in sections of up to 16 strings per section. The strings in each section are stored as a sequence of counted (not null-terminated) Unicode strings. The LoadString function will extract the string resource from its corresponding section.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winbase.h.
Import Library: Use kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows and Windows NT.

See Also

Resources Overview, Resource Functions, FormatMessage, LoadAccelerators, LoadBitmap, LoadCursor, LoadIcon, LoadMenu, LoadString, LoadResource, MAKELANGID


FreeResource

The FreeResource function is obsolete. It is provided to simplify porting of 16-bit Win32-based applications. It is not necessary for Win32-based applications to free resources loaded by using the LoadResource function. The resource obtained by LoadResource is automatically freed when the module is was loaded from is unloaded. However, to save memory and decrease the size of your process's working set, you should release the memory associated with accelerator tables, bitmaps, cursors, icons, and menus by calling the functions in the following table.

Resource | Release function
Accelerator table | DestroyAcceleratorTable
Bitmap | DeleteObject
Cursor | DestroyCursor
Icon | DestroyIcon
Menu | DestroyMenu

See Also

Resources Overview, Resource Functions


LoadImage

The LoadImage function loads an icon, cursor, or bitmap.

HANDLE LoadImage(
  HINSTANCE hinst,   // handle of the instance containing the image
  LPCTSTR lpszName,  // name or identifier of image
  UINT uType,        // type of image
  int cxDesired,     // desired width
  int cyDesired,     // desired height
  UINT fuLoad        // load flags
);

Parameters

hinst
Handle to an instance of the module that contains the image to be loaded. To load an OEM image, set this parameter to zero.
lpszName
Handle to the image to load.

If the hinst parameter is non-NULL and the fuLoad parameter does not include LR_LOADFROMFILE, lpszName is a pointer to a null-terminated string that contains the name of the image resource in the hinst module.

If hinst is NULL and LR_LOADFROMFILE is not specified, the low-order word of this parameter must be the identifier of the OEM image to load. The OEM image identifiers are defined in WINUSER.H and have the following prefixes:
Prefix | Meaning
OBM_ | OEM bitmaps
OIC_ | OEM icons
OCR_ | OEM cursors

If the fuLoad parameter includes the LR_LOADFROMFILE value, lpszName is the name of the file that contains the image.

uType
Specifies the type of image to be loaded. This parameter can be one of the following values:
Value | Meaning
IMAGE_BITMAP | Loads a bitmap.
IMAGE_CURSOR | Loads a cursor.
IMAGE_ICON | Loads an icon.

cxDesired
Specifies the width, in pixels, of the icon or cursor. If this parameter is zero and the fuLoad parameter is LR_DEFAULTSIZE, the function uses the SM_CXICON or SM_CXCURSOR system metric value to set the width. If this parameter is zero and LR_DEFAULTSIZE is not used, the function uses the actual resource width.
cyDesired
Specifies the height, in pixels, of the icon or cursor. If this parameter is zero and the fuLoad parameter is LR_DEFAULTSIZE, the function uses the SM_CYICON or SM_CYCURSOR system metric value to set the height. If this parameter is zero and LR_DEFAULTSIZE is not used, the function uses the actual resource height.
fuLoad
Specifies a combination of the following values:
Value | Meaning
LR_DEFAULTCOLOR | The default flag; it does nothing. All it means is "not LR_MONOCHROME".
LR_CREATEDIBSECTION | When the uType parameter specifies IMAGE_BITMAP, causes the function to return a DIB section bitmap rather than a compatible bitmap. This flag is useful for loading a bitmap without mapping it to the colors of the display device.
LR_DEFAULTSIZE | Uses the width or height specified by the system metric values for cursors or icons, if the cxDesired or cyDesired values are set to zero. If this flag is not specified and cxDesired and cyDesired are set to zero, the function uses the actual resource size. If the resource contains multiple images, the function uses the size of the first image.
LR_LOADFROMFILE | Loads the image from the file specified by the lpszName parameter. If this flag is not specified, lpszName is the name of the resource.
LR_LOADMAP3DCOLORS | Searches the color table for the image and replaces the following shades of gray with the corresponding 3D color:

Color Replaced with
Dk Gray,
RGB(128,128,128) 		COLOR_3DSHADOW
Gray,
RGB(192,192,192) 		COLOR_3DFACE
Lt Gray,
RGB(223,223,223) 		COLOR_3DLIGHT

LR_LOADTRANSPARENT Retrieves the color value of the first pixel in the image and replaces the corresponding entry in the color table with the default window color (COLOR_WINDOW). All pixels in the image that use that entry become the default window color. This value applies only to images that have corresponding color tables.

If fuLoad includes both the LR_LOADTRANSPARENT and LR_LOADMAP3DCOLORS values, LRLOADTRANSPARENT takes precedence. However, the color table entry is replaced with COLOR_3DFACE rather than COLOR_WINDOW.
LR_MONOCHROME | Loads the image in black and white.
LR_SHARED Shares the image handle if the image is loaded multiple times. If LR_SHARED is not set, a second call to LoadImage for the same resource will load the image again and return a different handle.

Do not use LR_SHARED for images that have non-standard sizes, that may change after loading, or that are loaded from a file.

Windows 95 and Windows 98: The function finds the first image with the requested resource name in the cache, regardless of the size requested.
LR_VGACOLOR | Uses true VGA colors.

Return Values

If the function succeeds, the return value is the handle of the newly loaded image.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

When you are finished using the bitmap, cursor, or icon, you can release its associated memory by calling one of the functions in the following table.

Resource | Release function
Bitmap | DeleteObject
Cursor | DestroyCursor
Icon | DestroyIcon

The system automatically deletes these resources when the process that created them terminates, however, calling the appropriate function saves memory and decreases the size of the process's working set.

Windows CE: The cxDesired and cyDesired parameters must be zero for IMAGE_BITMAP.

Windows CE does not support stretching and shrinking of icons.

The fuLoad parameter must be zero (==LR_DEFAULTCOLOR).

If you are targeting a platform that does not support mouse cursors, you cannot specify the SM_CXCURSOR and SM_CYCURSOR values in the cxDesired and cyDesired parameters, and you cannot specify IMAGE_CURSOR for the uType parameter.

If you are targeting a platform that supports mouse cursors, you can specify SM_CXCURSOR and SM_CYCURSOR in the cxDesired and cyDesired parameters, and IMAGE_CURSOR in the uType parameter.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Resources Overview, Resource Functions, CopyImage, GetSystemMetrics, LoadBitmap, LoadCursor, LoadIcon


LoadResource

The LoadResource function loads the specified resource into global memory.

HGLOBAL LoadResource(
  HMODULE hModule, // resource-module handle
  HRSRC hResInfo   // resource handle
);

Parameters

hModule
Handle to the module whose executable file contains the resource. If hModule is NULL, the system loads the resource from the module that was used to create the current process.
hResInfo
Handle to the resource to be loaded. This handle must be created by using the FindResource or FindResourceEx function.

Return Values

If the function succeeds, the return value is a handle to the data associated with the resource.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The return type of LoadResource is HGLOBAL for backward compatibility, not because the function returns a handle to a global memory block. Do not pass this handle to the GlobalLock or GlobalFree function. To obtain a pointer to the resource data, call the LockResource function.

When you are finished using an accelerator table, bitmap, cursor, icon, or menu, you can release its associated memory by calling one of the functions in the following table.

Resource | Release function
Accelerator table | DestroyAcceleratorTable
Bitmap | DeleteObject
Cursor | DestroyCursor
Icon | DestroyIcon
Menu | DestroyMenu

The system automatically deletes these resources when the process that created them terminates, however, calling the appropriate function saves memory and decreases the size of the process's working set.

Windows CE: The hModule parameter must be non-NULL.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winbase.h.
Import Library: Use kernel32.lib.

See Also

Resources Overview, Resource Functions, FindResource, FindResourceEx, LoadLibrary, LoadModule, LockResource


LockResource

The LockResource function locks the specified resource in memory.

LPVOID LockResource(
  HGLOBAL hResData   // handle to resource to lock
);

Parameters

hResData
Handle to the resource to be locked. The LoadResource function returns this handle.

Return Values

If the loaded resource is locked, the return value is a pointer to the first byte of the resource; otherwise, it is NULL.

Remarks

Trying to lock a resource by using the handle returned by the FindResource or FindResourceEx function will not work. You will get back a value that is incorrect and points to random data.

When you are finished using an accelerator table, bitmap, cursor, icon, or menu, you can release its associated memory by calling one of the functions in the following table.

Resource | Release function
Accelerator table | DestroyAcceleratorTable
Bitmap | DeleteObject
Cursor | DestroyCursor
Icon | DestroyIcon
Menu | DestroyMenu

The system automatically deletes these resources when the process that created them terminates, however, calling the appropriate function saves memory and decreases the size of the process's working set.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winbase.h.
Import Library: Use kernel32.lib.

See Also

Resources Overview, Resource Functions, FindResource, FindResourceEx, LoadResource


SizeofResource

The SizeofResource function returns the size, in bytes, of the specified resource.

DWORD SizeofResource(
  HMODULE hModule, // resource-module handle
  HRSRC hResInfo   // resource handle
);

Parameters

hModule
Handle to the module whose executable file contains the resource.
hResInfo
Handle to the resource. This handle must be created by using the FindResource or FindResourceEx function.

Return Values

If the function succeeds, the return value is the number of bytes in the resource.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winbase.h.
Import Library: Use kernel32.lib.

See Also

Resources Overview, Resource Functions, FindResource, FindResourceEx


UnlockResource

The UnlockResource function is obsolete. This function is provided only for compatibility with 16-bit versions of Windows. It is not necessary for Win32-based applications to unlock resources.

See Also

Resources Overview, Resource Functions, LoadResource, LockResource


UpdateResource

The UpdateResource function adds, deletes, or replaces a resource in an executable file.

BOOL UpdateResource(
  HANDLE hUpdate, // update-file handle
  LPCTSTR lpType, // address of resource type to update
  LPCTSTR lpName, // address of resource name to update
  WORD wLanguage, // language identifier of resource
  LPVOID lpData,  // address of resource data
  DWORD cbData    // length of resource data, in bytes
);

Parameters

hUpdate
Specifies an update-file handle. This handle is returned by the BeginUpdateResource function.
lpType
Pointer to a null-terminated string specifying the resource type to be updated. This parameter can also be an integer value passed to the MAKEINTRESOURCE macro, or it can be one of the following predefined resource types:
Value | Meaning
RT_ACCELERATOR | Accelerator table
RT_ANICURSOR | Animated cursor
RT_ANIICON | Animated icon
RT_BITMAP | Bitmap resource
RT_CURSOR | Hardware-dependent cursor resource
RT_DIALOG | Dialog box
RT_FONT | Font resource
RT_FONTDIR | Font directory resource
RT_GROUP_CURSOR | Hardware-independent cursor resource
RT_GROUP_ICON | Hardware-independent icon resource
RT_HTML | HTML document
RT_ICON | Hardware-dependent icon resource
RT_MENU | Menu resource
RT_MESSAGETABLE | Message-table entry
RT_RCDATA | Application-defined resource (raw data)
RT_STRING | String-table entry
RT_VERSION | Version resource

lpName
Pointer to a null-terminated string specifying the name of the resource to be updated. This parameter can also be an integer value passed to the MAKEINTRESOURCE macro.
wLanguage
Specifies the language identifier of the resource to be updated. For a list of the primary language identifiers and sublanguage identifiers that make up a language identifier, see the MAKELANGID macro.
lpData
Pointer to the resource data to be inserted into the executable file. If the resource is one of the predefined types, the data must be valid and properly aligned. Note that this is the raw binary data stored in the executable file, not the data provided by LoadIcon, LoadString, or other resource-specific load functions. All data containing strings or text must be in Unicode format; lpData must not point to ANSI data.

If lpData is NULL, the specified resource is deleted from the executable file.

cbData
Specifies the size, in bytes, of the resource data at lpData.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

An application can use UpdateResource repeatedly to make changes to the resource data. Each call to UpdateResource contributes to an internal list of additions, deletions, and replacements but does not actually write the data to the executable file. The application must use the EndUpdateResource function to write the accumulated changes to the executable file.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Unsupported.
Windows CE: Unsupported.
Header: Declared in winbase.h.
Import Library: Use kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Resources Overview, Resource Functions, BeginUpdateResource, EndUpdateResource, LoadIcon, LoadString, LockResource, MAKEINTRESOURCE, MAKELANGID, SizeofResource


Resource Structures

The structures that describe the format of resources are grouped in the following manner. An alphabetic list follows.

Resource File Header

RESOURCEHEADER

Accelerator Table Resources

ACCELTABLEENTRY

Cursor Resources

CURSORDIR
LOCALHEADER
NEWHEADER
RESDIR

Icon Resources

ICONRESDIR
NEWHEADER
RESDIR

Dialog Box Resources

DLGTEMPLATE
DLGITEMTEMPLATE

Extended Dialog Box Resources

DLGTEMPLATEEX
DLGITEMTEMPLATEEX

Font and Font Directory Resources

DIRENTRY
FONTDIRENTRY
FONTGROUPHDR

Menu Resources

MENUHEADER
menuhelpid
NORMALMENUITEM
POPUPMENUITEM

Extended Menu Resources

MENUEX_TEMPLATE_HEADER
MENUEX_TEMPLATE_ITEM

Message Table Resources

MESSAGE_RESOURCE_BLOCK
MESSAGE_RESOURCE_DATA
MESSAGE_RESOURCE_ENTRY

Version Resources

String
StringFileInfo
StringTable
Var
VarFileInfo
VS_FIXEDFILEINFO
VS_VERSIONINFO

The following structures are used with resource files.

ACCELTABLEENTRY
CURSORDIR
CURSORSHAPE
DIRENTRY
DLGITEMTEMPLATE
DLGITEMTEMPLATEEX
DLGTEMPLATE
DLGTEMPLATEEX
FONTDIRENTRY
FONTGROUPHDR
ICONRESDIR
LOCALHEADER
MENUEX_TEMPLATE_HEADER
MENUEX_TEMPLATE_ITEM
MENUHEADER
menuhelpid
MESSAGE_RESOURCE_BLOCK
MESSAGE_RESOURCE_DATA
MESSAGE_RESOURCE_ENTRY
NEWHEADER
NORMALMENUITEM
POPUPMENUITEM
RESDIR
RESOURCEHEADER
String
StringFileInfo
StringTable
Var
VarFileInfo
VS_FIXEDFILEINFO
VS_VERSIONINFO


ACCELTABLEENTRY

The ACCELTABLEENTRY structure describes the data in an individual accelerator table resource. The structure definition provided here is for explanation only; it is not present in any standard header file.

struct ACCELTABLEENTRY {
    WORD fFlags;
    WORD wAnsi;
    WORD wId;
    WORD padding;
};

Members

fFlags
Specifies a set of flags that you can use to describe keyboard accelerator characteristics. This member can have one or more of the following values.
Value | Meaning
FVIRTKEY | The accelerator key is a virtual-key code. If this flag is not specified, the accelerator key is assumed to specify an ASCII character code.
FNOINVERT | A menu item on the menu bar is not highlighted when an accelerator is used.
FSHIFT | The accelerator is activated only if the user presses the SHIFT key. This flag applies only to virtual keys.
FCONTROL | The accelerator is activated only if the user presses the CTRL key. This flag applies only to virtual keys.
FALT | The accelerator is activated only if the user presses the ALT key. This flag applies only to virtual keys.
0x80 | The entry is last in an accelerator table.

wAnsi
Specifies an ANSI character value or a virtual-key code that identifies the accelerator key.
wId
Identifies the keyboard accelerator. This is the value passed to the window procedure when the user presses the specified key.
padding
The number of bytes inserted to ensure that the structure is aligned on a DWORD boundary.

Remarks

The ACCELTABLEENTRY structure is repeated for all accelerator table entries in the resource. The last entry in the table is flagged with the value 0x0080.

You can compute the number of elements in the table if you divide the length of the resource by eight. Then your application can randomly access the individual fixed-length entries.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.

See Also

Resources Overview, Resource Structures, CreateAcceleratorTable


CURSORDIR

The CURSORDIR structure contains the dimensions of an individual cursor image in a resource group. The structure definition provided here is for explanation only; it is not present in any standard header file.

struct CURSORDIR {
    WORD Width;
    WORD Height;
} CURSORDIR;

Members

Width
Specifies the width of the cursor, in pixels. Acceptable values are 16, 32, and 64.
Height
Specifies the height of the cursor, in pixels. Acceptable values are 16, 32, and 64.

Remarks

The CURSORDIR structure is passed in the RESDIR structure if the RESDIR structure describes a cursor.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.

See Also

Resources Overview, Resource Structures, RESDIR


CURSORSHAPE

The CURSORSHAPE structure contains information about a cursor.

typedef struct tagCURSORSHAPE {    // cs
    int     xHotSpot;
    int     yHotSpot;
    int     cx;
    int     cy;
    int     cbWidth;
    BYTE    Planes;
    BYTE    BitsPixel;
} CURSORSHAPE, FAR *LPCURSORSHAPE;

Members

xHotSpot
Specifies the horizontal position of the hot spot, relative to the upper left corner of the cursor bitmap.
yHotSpot
Specifies the vertical position of the hot spot, relative to the upper left corner of the cursor bitmap.
cx
Specifies the width, in pixels, of the cursor.
cy
Specifies the height, in pixels, of the cursor.
cbWidth
Width, in bytes, of the cursor bitmap.
Planes
Specifies the number of color planes.
BitsPixel
Specifies the number of bits used to indicate the color of a single pixel in the cursor.

Remarks

When an application passes a cursor handle to the LockResource function, the function returns a pointer to a buffer containing information about the cursor. An application can use the CURSORSHAPE structure to access the information.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Resources Overview, Resource Structures, LockResource


DIRENTRY

The DIRENTRY structure contains a unique ordinal that identifies an individual font in the font resource group. The structure definition provided here is for explanation only; it is not present in any standard header file.

struct DIRENTRY {
    WORD fontOrdinal;
};

Member

fontOrdinal
Specifies a unique ordinal identifier for an individual font in a font resource group.

Remarks

The FONTDIRENTRY structure for the specified font directly follows the DIRENTRY structure for that font.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.

See Also

Resources Overview, Resource Structures, FONTDIRENTRY, FONTGROUPHDR


FONTDIRENTRY

The FONTDIRENTRY structure contains information about an individual font in a font resource group. The structure definition provided here is for explanation only; it is not present in any standard header file.

struct FONTDIRENTRY {
    WORD dfVersion;
    DWORD dfSize;
    char dfCopyright[60];
    WORD dfType;
    WORD dfPoints;
    WORD dfVertRes;
    WORD dfHorizRes;
    WORD dfAscent;
    WORD dfInternalLeading;
    WORD dfExternalLeading;
    BYTE dfItalic;
    BYTE dfUnderline;
    BYTE dfStrikeOut;
    WORD dfWeight;
    BYTE dfCharSet;
    WORD dfPixWidth;
    WORD dfPixHeight;
    BYTE dfPitchAndFamily;
    WORD dfAvgWidth;
    WORD dfMaxWidth;
    BYTE dfFirstChar;
    BYTE dfLastChar;
    BYTE dfDefaultChar;
    BYTE dfBreakChar;
    WORD dfWidthBytes;
    DWORD dfDevice;
    DWORD dfFace;
    DWORD dfReserved;
    char szDeviceName[];
    char szFaceName[];
};

Members

dfVersion
Specifies a user-defined version number for the resource data that tools can use to read and write resource files.
dfSize
Specifies the size of the file, in bytes.
dfCopyright[60]
Contains a 60-character string with the font supplier's copyright information.
dfType
Specifies the type of font file.
dfPoints
Specifies the point size at which this character set looks best.
dfVertRes
Specifies the vertical resolution, in dots per inch, at which this character set was digitized.
dfHorizRes
Specifies the horizontal resolution, in dots per inch, at which this character set was digitized.
dfAscent
Specifies the distance from the top of a character definition cell to the baseline of the typographical font.
dfInternalLeading
Specifies the amount of leading inside the bounds set by the dfPixHeight member. Accent marks and other diacritical characters can occur in this area.
dfExternalLeading
Specifies the amount of extra leading that the application adds between rows.
dfItalic
Specifies an italic font if not equal to zero.
dfUnderline
Specifies an underlined font if not equal to zero.
dfStrikeOut
Specifies a strikeout font if not equal to zero.
dfWeight
Specifies the weight of the font in the range 0 through 1000. For example, 400 is roman and 700 is bold. If this value is zero, a default weight is used. For additional defined values, see the description of the LOGFONT structure.
dfCharSet
Specifies the character set of the font. For predefined values, see the description of the LOGFONT structure.
dfPixWidth
Specifies the width of the grid on which a vector font was digitized. For raster fonts, if the member is not equal to zero, it represents the width for all the characters in the bitmap. If the member is equal to zero, the font has variable-width characters.
dfPixHeight
Specifies the height of the character bitmap for raster fonts or the height of the grid on which a vector font was digitized.
dfPitchAndFamily
Specifies the pitch and the family of the font. For additional information, see the description of the LOGFONT structure.
dfAvgWidth
Specifies the average width of characters in the font (generally defined as the width of the letter x). This value does not include the overhang required for bold or italic characters.
dfMaxWidth
Specifies the width of the widest character in the font.
dfFirstChar
Specifies the first character code defined in the font.
dfLastChar
Specifies the last character code defined in the font.
dfDefaultChar
Specifies the character to substitute for characters not in the font.
dfBreakChar
Specifies the character that will be used to define word breaks for text justification.
dfWidthBytes
Specifies the number of bytes in each row of the bitmap. This value is always even so that the rows start on word boundaries. For vector fonts, this member has no meaning.
dfDevice
Specifies the offset in the file to a null-terminated string that specifies a device name. For a generic font, this value is zero.
dfFace
Specifies the offset in the file to a null-terminated string that names the typeface.
dfReserved
This member is reserved.
szDeviceName
Array that contains a null-terminated string that specifies the name of the device if this font file is designated for a specific device.
szFaceName
Array that contains a null-terminated string that specifies the typeface name of the font.

Remarks

There is one FONTDIRENTRY structure for every font in the .RES file. Applications that generate .RES files with font resources must also add to the file a FONTDIRENTRY structure for each font.

Font declarations can be mixed with other resource declarations in the .RC file because fonts do not need to be contiguous in the .RES file.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.

See Also

Resources Overview, Resource Structures, DIRENTRY, FONTGROUPHDR, LOGFONT


FONTGROUPHDR

The FONTGROUPHDR structure contains the information necessary for an application to access a specific font. The structure definition provided here is for explanation only; it is not present in any standard header file.

struct FONTGROUPHDR {
    WORD NumberOfFonts;
    DIRENTRY  DE [1];
};

Members

NumberOfFonts
Specifies the number of individual fonts associated with this resource.
DE [1]
Specifies a DIRENTRY structure that contains a unique ordinal identifier for each font in the resource. The DE [1] member is a placeholder for the variable-length array of DIRENTRY structures.

Remarks

The FONTGROUPHDR structure follows the data for the individual fonts in the .RES file. The resource compiler automatically adds the FONTGROUPHDR structure, generally as the last entry in the file.

See Also

Resources Overview, Resource Structures, DIRENTRY, FONTDDIRENTRY


ICONRESDIR

The ICONRESDIR structure contains the dimensions and color format of an individual icon image in a resource group. The structure definition provided here is for explanation only; it is not present in any standard header file.

struct ICONRESDIR {
    BYTE Width;
    BYTE Height;
    BYTE ColorCount;
    BYTE reserved;
} ICONRESDIR;

Members

Width
Specifies the width of the icon, in pixels. Acceptable values are 16, 32, and 64.
Height
Specifies the height of the icon, in pixels. Acceptable values are 16, 32, and 64.
ColorCount
Specifies the number of colors in the icon. Acceptable values are 2, 8, and 16.
reserved
Reserved; must be set to the same value as that of the reserved field in the icon file header.

Remarks

The ICONRESDIR structure is passed in the RESDIR structure if the RESDIR structure describes an icon.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.

See Also

Resources Overview, Resource Structures, RESDIR


LOCALHEADER

The LOCALHEADER structure contains the x- and y-coordinates of a hotspot associated with the cursor identified by a RESDIR structure. The LOCALHEADER structure definition provided here is for explanation only; it is not present in any standard header file.

typedef struct tagLOCALHEADER {
    WORD xHotSpot;
    WORD yHotSpot;
} LOCALHEADER;

Members

xHotSpot
Specifies the x-coordinate, in pixels, of the cursor hot spot.
yHotSpot
Specifies the y-coordinate, in pixels, of the cursor hot spot.

Remarks

The LOCALHEADER structure is the first data written to the RT_CURSOR resource if a RESDIR structure contains information about a cursor.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.

See Also

Resources Overview, Resource Structures, CURSORDIR, RESDIR


MENUHEADER

The MENUHEADER structure contains version information for the menu resource. The structure definition provided here is for explanation only; it is not present in any standard header file.

struct MENUHEADER {
    WORD wVersion;
    WORD cbHeaderSize;
};

Members

wVersion
Specifies the version number of the menu template. This member must be equal to zero to indicate that this is an RT_MENU created with a standard menu template.
cbHeaderSize
Specifies the size of the menu template header. This value is zero for menus you create with a standard menu template.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.

See Also

Resources Overview, Resource Structures, MENUEX_TEMPLATE_HEADER, MENUEX_TEMPLATE_ITEM, MENUITEMTEMPLATE, MENUITEMTEMPLATEHEADER, NORMALMENUITEM, POPUPMENUITEM


menuhelpid

The menuhelpid structure is the final data written to the RT_MENU resource for a menu or submenu if the resInfo member of the POPUPMENUITEM structure is set to MFR_POPUP. The structure menuhelpid definition provided here is for explanation only; it is not present in any standard header file.

typedef struct menuhelpid {
    DWORD helpID;
} menuhelpid;

Member

helpID
Specifies a numeric expression indicating the identifier used to identify the menu during WM_HELP processing.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.

See Also

Resources Overview, Resource Structures, MENUHEADER, POPUPMENUITEM


MESSAGE_RESOURCE_BLOCK

The MESSAGE_RESOURCE_BLOCK structure contains information about message strings with identifiers in the range indicated by the LowId and HighId members.

typedef struct _MESSAGE_RESOURCE_BLOCK {
    ULONG LowId;
    ULONG HighId;
    ULONG OffsetToEntries;
} MESSAGE_RESOURCE_BLOCK, *PMESSAGE_RESOURCE_BLOCK;

Members

LowId
Specifies the lowest message identifier contained within this MESSAGE_RESOURCE_BLOCK.
HighId
Specifies the highest message identifier contained within this MESSAGE_RESOURCE_BLOCK.
OffsetToEntries
Specifies the offset, in bytes, from the beginning of the MESSAGE_RESOURCE_DATA structure to the MESSAGE_RESOURCE_ENTRY structures in this MESSAGE_RESOURCE_BLOCK. The MESSAGE_RESOURCE_ENTRY structures contain the message strings.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winnt.h.

See Also

Resources Overview, Resource Structures, MESSAGE_RESOURCE_DATA, MESSAGE_RESOURCE_ENTRY


MESSAGE_RESOURCE_DATA

The MESSAGE_RESOURCE_DATA structure contains information about formatted text for display as an error message or in a message box in a message table resource.

typedef struct _MESSAGE_RESOURCE_DATA {
    ULONG NumberOfBlocks;
    MESSAGE_RESOURCE_BLOCK Blocks[ 1 ];
} MESSAGE_RESOURCE_DATA, *PMESSAGE_RESOURCE_DATA;

Members

NumberOfBlocks
Specifies the number of MESSAGE_RESOURCE_BLOCK structures.
Blocks[ 1 ]
Array that contains the number of MESSAGE_RESOURCE_BLOCK structures indicated by the NumberOfBlocks member. The MESSAGE_RESOURCE_BLOCK Blocks[ 1 ] member is a placeholder for the variable length array of Blocks.

Remarks

A MESSAGE_RESOURCE_DATA structure can contain one or more MESSAGE_RESOURCE_BLOCK structures, which can each contain one or more MESSAGE_RESOURCE_ENTRY structures.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winnt.h.

See Also

Resources Overview, Resource Structures, MESSAGE_RESOURCE_BLOCK, MESSAGE_RESOURCE_ENTRY


MESSAGE_RESOURCE_ENTRY

The MESSAGE_RESOURCE_ENTRY structure contains the error message or message box display text for a message table resource.

typedef struct _MESSAGE_RESOURCE_ENTRY {
    USHORT Length;
    USHORT Flags;
    UCHAR Text[ 1 ];
} MESSAGE_RESOURCE_ENTRY, *PMESSAGE_RESOURCE_ENTRY;

Members

Length
Specifies the length, in bytes, of the message string in this structure.
Flags
Indicates that the string is encoded in Unicode if equal to the value 0x0001; indicates that the string is encoded in ANSI if equal to the value 0x0000.
Text[ 1 ]
An array that contains the error message or message box display text. The Text[ 1 ] member is a placeholder for the variable-length Text array.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winnt.h.

See Also

Resources Overview, Resource Structures, MESSAGE_RESOURCE_BLOCK, MESSAGE_RESOURCE_DATA


NEWHEADER

The NEWHEADER structure contains the number of icon or cursor components in a resource group. The structure definition provided here is for explanation only; it is not present in any standard header file.

struct NEWHEADER {
    WORD Reserved;
    WORD ResType;
    WORD ResCount;
} NEWHEADER, *PNEWHEADER;
NEWHEADER NewHeader;

Members

Reserved
Reserved; must be zero.
ResType
Specifies the resource type. This member must be RES_ICON for icons and RES_CURSOR for cursors.
ResCount
Specifies the number of icon or cursor components in the resource group.

Remarks

One or more RESDIR structures immediately follow the NEWHEADER structure in the .RES file. The ResCount member specifies the number of RESDIR structures.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.

See Also

Resources Overview, Resource Structures, RESDIR


NORMALMENUITEM

The NORMALMENUITEM structure contains information about each item in a menu resource that does not open a menu or a submenu. The structure definition provided here is for explanation only; it is not present in any standard header file.

struct NORMALMENUITEM {
    WORD resInfo;
    szOrOrd menuText;
};

Members

resInfo
A set of bit flags that specify the type of menu item. This member can be one of the following values.
Value | Meaning
MFR_END | The menu item is the last in this submenu or menu resource; this flag is used internally by the system.
MFR_POPUP | The menu item opens a menu or a submenu; the flag is used internally by the system.

menuText
Specifies a null-terminated Unicode string that contains the text for this menu item. There is no fixed limit on the size of this string.

Remarks

There is one NORMALMENUITEM structure for each menu item that does not open a menu or a submenu. Indicate the last menu item on a menu by setting the resInfo member to MFR_END.

A menu separator is a special type of menu item that is inactive but appears as a dividing bar between two active menu items. Indicate a menu separator by leaving the menuText member empty.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.

See Also

Resources Overview, Resource Structures, MENUHEADER, MENUITEMINFO, POPUPMENUITEM


POPUPMENUITEM

The POPUPMENUITEM structure contains information about the menu items in a menu resource that open a menu or a submenu. The structure definition provided here is for explanation only; it is not present in any standard header file.

struct POPUPMENUITEM {
    DWORD type;
    DWORD state;
    DWORD id;
    WORD resInfo;
    szOrOrd menuText;
};

Members

type
Specifies a set of type flags that you can use to describe the menu item. Some of the values this member can have include:
Value | Meaning
MF_END | The menu item is the last on the menu; the flag is used internally by the system.
MF_POPUP | The menu item opens a menu or a submenu; the flag is used internally by the system.

If you specify MF_POPUP, it indicates that the menu item is one that opens a menu or a submenu.

In addition to the values MF_END and MF_POPUP, this member can also be a combination of the type values listed with the dwType member of the MENUITEMINFO structure. The type values are those that begin with MFT_. To use these predefined MFT_* type values, include the following statement in your .RC file:

#include "WINUSER.H"

state
Specifies a set of state flags that you can use to describe the menu item. This member can be a combination of the state values listed with the dwState member of the MENUITEMINFO structure. The state values are those that begin with MFS_. To use these predefined MFS_* state values, include the following statement in your .RC file:

#include "WINUSER.H"

id
A numeric expression that identifies the menu item that is passed in the WM_COMMAND message.
resInfo
A set of bit flags that specify the type of menu item. This member can be one of the following values.
Value | Meaning
MFR_END | The menu item is the last in this submenu or menu resource; this flag is used internally by the system.
MFR_POPUP | The menu item opens a menu or a submenu; the flag is used internally by the system.

menuText
Specifies a null-terminated Unicode string that contains the text for this menu item. There is no fixed limit on the size of this string.

Remarks

There is one POPUPMENUITEM structure for each menu item that opens a menu or a submenu. Identify this type of menu item by setting the type member to MF_POPUP and by setting the MFR_POPUP bit in the resInfo member to 0x0001. In this case, the final data written to the RT_MENU resource for the menu or submenu is the menuhelpid structure. menuhelpid contains a numeric expression that identifies the menu during WM_HELP processing.

Additionally, every POPUPMENUITEM structure that has the MFR_POPUP bit set in the resInfo member will be followed by a menuhelpid structure plus an additional number of POPUPMENUITEM structures, one for each menu item in that submenu. The last POPUPMENUITEM structure in the submenu will have the MFR_END bit set in the resInfo member. To find the end of the resource, look for a matching MFR_END for every MFR_POPUP plus one additional MFR_END that matches the outermost set of menu items.

Indicate the last menu item by setting the type member to MF_END. Because you can nest submenus, there can be multiple levels of MF_END. In these instances, the menu items are sequential.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.

See Also

Resources Overview, Resource Structures, MENUHEADER, menuhelpid, MENUITEMINFO, NORMALMENUITEM


RESDIR

The RESDIR structure contains information about an individual icon or cursor component in a resource group. There is one RESDIR structure for each group component. The structure definition provided here is for explanation only; it is not present in any standard header file.

typedef struct tagRESDIR
{
    union
    {
        ICONRESDIR   Icon;
        CURSORDIR    Cursor;
    } ResInfo;
    WORD    Planes;
    WORD    BitCount;
    DWORD   BytesInRes;
    WORD  IconCursorId;
} RESDIR;

Members

Icon
Specifies an ICONRESDIR structure that contains the width, height, and color count of the indicated icon.
Cursor
Specifies a CURSORDIR structure that contains the width and height of the indicated cursor.
Planes
Specifies the number of color planes in the icon or cursor bitmap.
BitCount
Specifies the number of bits per pixel in the icon or cursor bitmap.
BytesInRes
Specifies the size of the resource, in bytes.
IconCursorId
Specifies the icon or cursor with a unique ordinal identifier.

Remarks

One or more RESDIR structures immediately follow the NEWHEADER structure in the .RES file. The ResCount member of the NEWHEADER structure specifies the number of RESDIR structures. Note that the RESDIR structure consists of either an ICONRESDIR structure or a CURSORDIR structure followed by the Planes, BitCount, BytesInRes and IconCursorId members. If the RESDIR structure contains information about a cursor, the first two WORDS the resource compiler writes to the RT_CURSOR resource are the xHotSpot and yHotSpot members of the LOCALHEADER structure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.

See Also

Resources Overview, Resource Structures, CURSORDIR, ICONRESDIR, LOCALHEADER, NEWHEADER


RESOURCEHEADER

The RESOURCEHEADER structure contains information about the resource header itself and the data specific to this resource. This structure is not a true C-language structure, because it contains variable-length members. The structure definition provided here is for explanation only; it is not present in any standard header file.

struct RESOURCEHEADER {
    DWORD DataSize;
    DWORD HeaderSize;
    [Ordinal or name TYPE];
    [Ordinal or name NAME];
    DWORD DataVersion;
    WORD MemoryFlags;
    WORD LanguageId;
    DWORD Version;
    DWORD Characteristics;
};

Members

DataSize
Specifies the size, in bytes, of the data that follows the resource header for this particular resource. It does not include any file padding between this resource and any resource that follows it in the resource file.
HeaderSize
Specifies the size, in bytes, of the resource header data that follows.
TYPE
Identifies the resource type. The TYPE member can either be a numeric value or a null-terminated Unicode string that specifies the name of the type. See the following Remarks section for a description of Name or Ordinal type members.

If the TYPE member is a numeric value, it can specify either a standard or a user-defined resource type. If the member is a string, then it is a user-defined resource type.

Following are the standard Win32 resource types.
Resource Type Name | Type number
RT_CURSOR | 1
RT_BITMAP | 2
RT_ICON | 3
RT_MENU | 4
RT_DIALOG | 5
RT_STRING | 6
RT_FONTDIR | 7
RT_FONT | 8
RT_ACCELERATOR | 9
RT_RCDATA | 10
RT_MESSAGETABLE | 11
RT_GROUP_CURSOR | 12
RT_GROUP_ICON | 14
RT_VERSION | 16
RT_DLGINCLUDE | 17
RT_PLUGPLAY | 19
RT_VXD | 20
RT_ANICURSOR | 21
RT_ANIICON | 22
RT_HTML | 23

Values less than 256 are reserved for system use.

NAME
Specifies a name that identifies the particular resource. The NAME member, like the TYPE member, can either be a numeric value or a null-terminated Unicode string. See the following Remarks section for a description of Name or Ordinal type members.

You do not need to add padding for DWORD alignment between the TYPE and NAME members because they contain WORD data. However, you may need to add a WORD of padding after the NAME member to align the rest of the header on DWORD boundaries.

DataVersion
Specifies a predefined resource data version. This will determine which version of the resource data the application should use.
MemoryFlags
Specifies a set of attribute flags that can describe the state of the resource. Modifiers in the .RC script file assign these attributes to the resource. The script identifiers can assign the following flag values.
Flag description | Value
MOVEABLE | 0x0010
FIXED | ~MOVEABLE
PURE | 0x0020
IMPURE | ~PURE
PRELOAD | 0x0040
LOADONCALL | ~PRELOAD
DISCARDABLE | 0x1000

Win32-based applications do not use any of these attributes. The attributes are permitted in the script for backward compatibility with existing scripts, but they are ignored. Win32 resources are loaded when the corresponding module is loaded, and are freed when the module is unloaded.

LanguageId
Specifies the language for the resource or set of resources. Set the value for this member with the optional LANGUAGE Statement resource definition statement. The parameters are constants from the WINNT.H file.

Each resource includes a language identifier so the system or application can select a language appropriate for the current locale of the system. If there are multiple resources of the same type and name that differ only in the language of the strings within the resources, you will need to specify a LanguageId for each one.

Version
Specifies a user-defined version number for the resource data that tools can use to read and write resource files. Set this value with the optional VERSION resource definition statement.
Characteristics
Specifies user-defined information about the resource that tools can use to read and write resource files. Set this value with the optional CHARACTERISTICS resource definition statement.

Remarks

A variable type member is called a Name or Ordinal member, and it is used in most places in the resource file where an identifier appears. The first WORD of a Name or Ordinal type member indicates whether the member is a numeric value or a string. If the first WORD in the member is equal to the value 0xffff, which is an invalid Unicode character, then the following WORD is a type number. Otherwise, the member contains a Unicode string and the first WORD in the member is the first character in the name string. For additional information about resource definition statements, see Resource-Definition Statements.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.

See Also

Resources Overview, Resource Structures, CHARACTERISTICS Statement, LANGUAGE Statement, VERSION Statement


Resource Macros

The following macro is used with resources.

MAKEINTRESOURCE


MAKEINTRESOURCE

The MAKEINTRESOURCE macro converts an integer value to a resource type compatible with Win32 resource-management functions. This macro is used in place of a string containing the name of the resource.

LPTSTR MAKEINTRESOURCE(
  WORD wInteger  // integer to convert
);

Parameters

wInteger
Specifies the integer value to be converted.

Return Values

The return value is the specified value in the low-order word and zero in the high-order word.

Remarks

The return value should be passed only to the Win32 resource-management functions, as the lpType parameter.

The MAKEINTRESOURCE macro is defined as follows:

#define MAKEINTRESOURCE(i)  (LPTSTR) ((DWORD) ((WORD) (i)))

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Resources Overview, Resource Macros


Accessibility

The Win32 API provides a set of accessibility features that make it easier for persons with disabilities to use computers. This overview describes the provided accessibility features and the Win32 functions and structures for controlling these features.

For information about other accessibility features, see Microsoft Active Accessibility.


About Accessibility

There are two categories of accessibility features:

  • Accessibility parameters. These are system parameters that can be set by the user. Applications can check the state of an accessibility parameter to determine whether the user wants special behavior that can be provided in an application-specific manner. For example, the ShowSounds parameter indicates that an application that typically uses sound to convey important information should also provide the information visually.
  • Built-in accessibility features. These features are built into the system or provided as an extension to the system. They affect how the user provides keyboard and mouse input to the computer. When enabled, their functionality is available regardless of which applications are running. An example is a keyboard filter that makes it easier for users with movement impairments to type key combinations such as ctrl+alt+del.


Accessibility Parameters

The system maintains a set of accessibility parameters that indicate whether the user has special needs or preferences. The user controls the state of these parameters, typically using a Control Panel application. Control Panel applications or other programs that allow the user to customize the environment can use the SystemParametersInfo function to set the accessibility parameters.

Applications should use the GetSystemMetrics function to determine the state of the accessibility parameters. When an accessibility parameter is set to TRUE, the application should modify its user interface, if necessary, to accommodate the user's preferences.

Win32 supports the following accessibility parameters:

Parameter | Description
ShowSounds | Indicates that an application that typically uses sound to convey important information should provide the information visually.
High Contrast | Indicates that the application should provide high contrast between foreground and background visuals.


ShowSounds Parameter

The ShowSounds parameter indicates whether the user wants applications to present all important information in visual form.

The user controls the setting of the ShowSounds parameter by using the Accessibility Control Panel application or another application for customizing the environment. These applications use the SPI_GETSHOWSOUNDS and SPI_SETSHOWSOUNDS flags with the SystemParametersInfo function to get and set the ShowSounds parameter.

Applications can use the SM_SHOWSOUNDS flag with the GetSystemMetrics function to determine the state of the ShowSounds parameter. This is necessary only for applications that would typically present important information by sound alone. Applications should provide ShowSounds support if they use sounds in either of the following ways:

  • To convey information that is not typically presented visually and is important to the operation of the application.
  • To alert the user that important information is being presented visually. If this is the case, even though the information is presented visually, the sound has the additional function of attracting the attention of the user.

Appropriate visual feedback forms can make the software much more functional for users who cannot rely on sound alone. It is entirely up to you to decide how best to convey this same information in visual form. For example, in order to attract the user's attention when new electronic mail arrives, the application might flash its window or even flash the entire screen. If the application typically makes sound to indicate that the user is trying to perform an illegal operation, it could also display an appropriate message on its status line or use the MessageBox function to display a specific error message. If the application is typically designed to play sound bites that carry meaning, such as digitized speech, it could also display a caption window with the same text.

Redundant use of audible and visual alerts has been shown to increase the usability of software applications. The ShowSounds parameter is a request for visual feedback, but its use does not restrict an application to presenting information visually. Users should be able to request visual feedback regardless of whether they also want audible feedback.


High Contrast Parameter

The High Contrast parameter indicates whether the user wants a high contrast between the colors used for foreground and background visuals.

The user controls the setting of the High Contrast parameter by using the Accessibility Control Panel application or another application for customizing the environment. These applications use the SPI_GETHIGHCONTRAST and SPI_SETHIGHCONTRAST flags with the SystemParametersInfo function to get and set the High Contrast parameter.


Built-in Accessibility Features

The built-in accessibility features are extensions to the operating system. These features affect the behavior of the system regardless of which applications are running.

Win32 supports the following built-in accessibility features:

Feature | Description
AccessTimeout | Enables a user to specify a timeout interval after which system-wide accessibility features are automatically disabled. The AccessTimeout feature is intended for computers that are shared by several users with different preferences. Each individual can use hot keys or the Control Panel to enable preferred features. After a user leaves, the features he or she enabled will be automatically disabled by the timeout. The accessibility features affected by the timeout are FilterKeys, MouseKeys, StickyKeys, and ToggleKeys, and High Contrast. The ACCESSTIMEOUT structure defines the parameters for this feature.
FilterKeys | Enables control of keyboard properties, such as the amount of time before a keystroke is accepted as input and the amount of time before a keystroke begins to repeat. The FilterKeys feature also provides sound feedback when a key is pressed and when it is accepted as input. The FILTERKEYS structure defines the parameters for this feature.
MouseKeys | Enables the user to control the mouse pointer using the numeric keypad. The MOUSEKEYS structure defines the parameters for this feature.
SerialKeys | Enables the user to provide input using an alternate input device attached to the computer's serial port. This feature is designed for users who are unable to use the computer's standard keyboard and mouse. The SERIALKEYS structure defines the parameters for this feature.
SoundSentry | Displays a visual signal when a sound is generated by a Win32-based application or an MS-DOS application running in a window. The SOUNDSENTRY structure defines the parameters for this feature, including the address of the SoundSentryProc callback function.
StickyKeys | Enables the user to type key combinations, such as ctrl+alt+del, in sequence rather than at the same time. The STICKYKEYS structure defines the parameters for this feature.
ToggleKeys | Provides sound feedback when the user turns on or off the caps lock, num lock, or scroll lock keys. The TOGGLEKEYS structure defines the parameters for this feature.

The SystemParametersInfo function provides the programming interface to the built-in accessibility features. This function is useful in Control Panel applications or other programs that allow the user to customize the environment. The SystemParametersInfo function can perform the following tasks:

  • Query the system to determine the availability and current state of a specified built-in accessibility feature
  • Enable a feature and specify parameters that control its behavior
  • Disable a feature
  • Enable a hot key that allows the user to enable or disable a feature

For each of the built-in features, Win32 defines a structure that applications use with SystemParametersInfo to query or set the parameters of the feature.

An application can use SystemParametersInfo to enable or disable a feature directly. For some of the features, SystemParametersInfo can enable a hot key or key combination so the user can toggle the state of a feature. There are no hot keys for the SerialKeys or SoundSentry features, or for the ShowSounds parameter. The following accessibility features have hot keys:

Feature | Description
FilterKeys | Hold down the left shift key for eight seconds to toggle the FilterKeys feature on or off. Holding down the left shift key for 12 seconds enables FilterKeys using the most conservative values for FILTERKEYS.iBounceMSec. Holding down the left shift key for 16 seconds enables FilterKeys using the most conservative values for FILTERKEYS.iWaitMSec.
MouseKeys | Press LEFT ALT + LEFT SHIFT + NUM LOCK.
StickyKeys | Press the shift key 5 times.
ToggleKeys | Hold down the num lock key for 5 seconds.
High Contrast parameter | Press LEFT ALT + LEFT SHIFT + PRINT SCREEN.


Using Accessibility

  • Checking the state of an accessibility parameter
  • Enabling a built-in accessibility feature


Checking the State of an Accessibility Parameter

The following code fragment uses the GetSystemMetrics function to check the ShowSounds parameter. If GetSystemMetrics returns TRUE, the application should present all important information in visual form.

BOOL fShowSounds;
fShowSounds = GetSystemMetrics(SM_SHOWSOUNDS);


Enabling a Built-in Accessibility Feature

The following code fragment uses the SystemParametersInfo function to enable the FilterKeys feature:

FILTERKEYS fk;
BOOL bSuccess;

// Fill in the members of the FILTERKEYS structure.

fk.cbSize = sizeof(FILTERKEYS);
fk.dwFlags = (FKF_FILTERKEYSON | FKF_HOTKEYACTIVE |
                       FKF_AVAILABLE | FKF_HOTKEYSOUND | FKF_CLICKON);
fk.iWaitMSec = 1000;
fk.iDelayMSec = 1000;
fk.iRepeatMSec = 500;
fk.iBounceMSec = 0;

// Call SystemParametersInfo with the SPI_SETFILTERKEYS flag.

bSuccess = SystemParametersInfo(SPI_SETFILTERKEYS, 0, (LPVOID) &fk, 0);


Accessibility Reference

The following elements are used with accessibility features.

  • Accessibility Functions
  • Accessibility Structures


Accessibility Functions

Use the following functions to implement accessibility features:

SoundSentryProc
SystemParametersInfo


SoundSentryProc

The SoundSentryProc function is a library-defined callback function that produces a customized visual signal when the SoundSentry accessibility feature is on and a Win32-based application (or an application running in a window) generates a sound through the computer's built-in speaker.

LRESULT CALLBACK SoundSentryProc(
  DWORD dwMillisec,  // duration of visual signal
  DWORD fdwEffect    // effect-type flag
);

Parameters

dwMillisec
Specifies the duration, in milliseconds, of the visual signal that is displayed when a Win32-based application (or an application running in a window) generates a sound.
fdwEffect
Specifies the type of visual signal to display. Currently, this value must always be SSWF_CUSTOM.

Return Values

If the visual signal was or will be displayed correctly, the return value is TRUE. If the signal is asynchronous and the status is not available when the function is called, it should return TRUE.

If an error prevented the signal from being displayed, the return value is FALSE. To get extended error information, call GetLastError.

Remarks

The library that contains the SoundSentryProc function must be a 32-bit DLL, and the DLL must export a function with the name SoundSentryProc.

The SoundSentryProc function is called only after an application or library calls the SystemParametersInfo function, specifying the SPI_SETSOUNDSENTRY value and the address of a SOUNDSENTRY structure whose iWindowsEffect member is set to SSWF_CUSTOM.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Import Library: User-defined.

See Also

Accessibility Overview, Accessibility Functions, SOUNDSENTRY, SystemParametersInfo


Accessibility Structures

Use the following structures to implement accessibility features:

ACCESSTIMEOUT
FILTERKEYS
HIGHCONTRAST
MOUSEKEYS
SERIALKEYS
SOUNDSENTRY
STICKYKEYS
TOGGLEKEYS


ACCESSTIMEOUT

The ACCESSTIMEOUT structure contains information about the time-out period associated with the Win32 accessibility features. The accessibility time-out period is the length of time that must pass without keyboard and mouse input before the operating system automatically turns off accessibility features. The accessibility features affected by the time-out are the FilterKeys features (SlowKeys, BounceKeys, and RepeatKeys), MouseKeys, ToggleKeys, and StickyKeys. The accessibility time-out is designed for computers that are shared by several users so that options selected by one user do not inconvenience a subsequent user.

The accessibility time-out affects the High Contrast Mode setting.

typedef struct tagACCESSTIMEOUT {     // ato
    UINT cbSize;
    DWORD dwFlags;
    DWORD iTimeOutMSec;
} ACCESSTIMEOUT;

Members

cbSize
Specifies the size, in bytes, of this structure.
dwFlags
A set of bit flags that specify properties of the time-out behavior for accessibility features. The following values are defined:
Value | Meaning
ATF_ONOFFFEEDBACK | If this flag is set, the operating system plays a descending siren sound when the time-out period elapses and the accessibility features are turned off.
ATF_AVAILABLE | If this flag is set, you can set a time-out period for accessibility features. An application can retrieve this value, but cannot set it.
ATF_TIMEOUTON | If this flag is set, a time-out period has been set for accessibility features. If this flag is not set, the features will not time out even though a time-out period is specified.

iTimeOutMSec
Specifies the time-out period, in milliseconds.

Remarks

Use an ACCESSTIMEOUT structure when calling the SystemParametersInfo function with the uiAction parameter set to the SPI_GETACCESSTIMEOUT or SPI_SETACCESSTIMEOUT value. When using SPI_GETACCESSTIMEOUT, you must specify the cbSize member of the ACCESSTIMEOUT structure; the SystemParametersInfo function fills in the remaining members. Specify all structure members when using the SPI_SETACCESSTIMEOUT value.

QuickInfo

Windows NT: Requires version 3.5 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Accessibility Overview, Accessibility Structures, SystemParametersInfo


FILTERKEYS

The FILTERKEYS structure contains information about the FilterKeys accessibility feature, which allow a user with disabilities to set the keyboard repeat rate (RepeatKeys), acceptance delay (SlowKeys), and bounce rate (BounceKeys).

typedef struct tagFILTERKEYS {     // fk
    UINT  cbSize;
    DWORD dwFlags;
    DWORD iWaitMSec;
    DWORD iDelayMSec;
    DWORD iRepeatMSec;
    DWORD iBounceMSec;
} FILTERKEYS;

Members

cbSize
Specifies the structure size, in bytes.
dwFlags
A set of bit flags that specify properties of the FilterKeys feature. The following bit-flag values are defined:
Value | Meaning
FKF_AVAILABLE | The FilterKeys features are available.
FKF_CLICKON | The computer makes a click sound when a key is pressed or accepted, that is, if SlowKeys is on, the acceptance is separated from the press and gets a separate click..
FKF_FILTERKEYSON | The FilterKeys features are on.
FKF_HOTKEYACTIVE | The user can turn the FilterKeys feature on and off by holding down the shift key for eight seconds.
FKF_HOTKEYSOUND | If this flag is set, the computer plays a siren sound when the user turns the FilterKeys feature on or off by using the hot key.
FKF_CONFIRMHOTKEY | Windows 95, Windows NT 5.0, and later: A confirmation dialog box appears when the FilterKeys features are activated by using the hot key.
FKF_INDICATOR | Windows 95, Windows NT 5.0, and later: A visual indicator is displayed when the FilterKeys features are on.

iWaitMSec
Specifies the length of time, in milliseconds, that the user must hold down a key before it is accepted by the computer.
iDelayMSec
Specifies the length of time, in milliseconds, that the user must hold down a key before it begins to repeat.
iRepeatMSec
Specifies the length of time, in milliseconds, between each repetition of the keystroke.
iBounceMSec
Specifies the amount of time, in milliseconds, that must elapse after releasing a key before the computer will accept a subsequent press of the same key.

Remarks

Use a FILTERKEYS structure when calling the SystemParametersInfo function with the wAction parameter set to the SPI_GETFILTERKEYS or SPI_SETFILTERKEYS value. When using SPI_GETFILTERKEYS, you must specify the cbSize member of the FILTERKEYS structure; the SystemParametersInfo function fills the remaining members. Specify all structure members when using the SPI_SETFILTERKEYS value.

At least one of the iDelayMSec and iBounceMSec members must be zero; they cannot both be nonzero at the same time.

If iBounceMSec is nonzero, the BounceKeys feature is on and the SlowKeys feature is off (the iDelayMSec value is ignored). If iBounceMSec is zero, the BounceKeys feature is off.

If iDelayMSec is nonzero and iBounceMSec is zero, the SlowKeys feature is on; otherwise, it is off.

QuickInfo

Windows NT: Requires version 3.5 or later.
Windows: Unsupported.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Accessibility Overview, Accessibility Structures, SystemParametersInfo


HIGHCONTRAST

The HIGHCONTRAST structure contains information about the High Contrast accessibility feature, which sets the appearance scheme of the user interface for maximum visibility for a visually-impaired user, and advises applications to comply with this appearance scheme.

typedef struct tagHIGHCONTRAST {     // hc
    UINT             cbSize;
    DWORD            dwFlags;
    LPTSTR           lpszDefaultScheme;
} HIGHCONTRAST, FAR* LPHIGHCONTRAST;

Members

cbSize
Specifies the size, in bytes, of this structure.
dwFlags
Specifies a combination of the following values:
Value | Meaning
HCF_AVAILABLE | The High Contrast feature is available.
HCF_CONFIRMHOTKEY | A confirmation dialog appears when the High Contrast feature is activated by using the hot key.
HCF_HIGHCONTRASTON | The High Contrast feature is on.
HCF_HOTKEYACTIVE | The user can turn the High Contrast feature on and off by simultaneously pressing the left alt, left shift, and print screen keys.
HCF_HOTKEYAVAILABLE | The hot key associated with the High Contrast feature can be enabled. An application can retrieve this value, but cannot set it.
HCF_HOTKEYSOUND | A siren is played when the user turns the High Contrast feature on or off by using the hot key.
HCF_INDICATOR | A visual indicator is displayed when the High Contrast feature is on. This value is not currently used and is ignored.

lpszDefaultScheme
Points to a string that contains the name of the default color scheme.

Remarks

An application uses this structure when calling the SystemParametersInfo function with the SPI_GETHIGHCONTRAST or SPI_SETHIGHCONTRAST value. When using SPI_GETHIGHCONTRAST, an application must specify the cbSize member of the HIGHCONTRAST structure; the SystemParametersInfo function fills the remaining members. An application must specify all structure members when using the SPI_SETHIGHCONTRAST value.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Unicode: Defined as Unicode and ANSI structures.

See Also

Accessibility Overview, Accessibility Structures, SystemParametersInfo


MOUSEKEYS

The MOUSEKEYS structure contains information about the MouseKeys accessibility feature. When the MouseKeys feature is active, the user can use the numeric keypad to control the mouse pointer, and to click, double-click, drag, and drop. By pressing numlock, the user can toggle the numeric keypad between mouse control mode and normal operation.

typedef struct _MOUSEKEYS {     // mk
    DWORD cbSize;
    DWORD dwFlags;
    DWORD iMaxSpeed;
    DWORD iTimeToMaxSpeed;
    DWORD iCtrlSpeed;
    DWORD dwReserved1;
    DWORD dwReserved2;
} MOUSEKEYS;

Members

cbSize
Specifies the size, in bytes, of this structure.
dwFlags
A set of bit-flags that specify properties of the FilterKeys feature. The following bit-flag values are defined:
Value | Meaning
MKF_AVAILABLE | If this flag is set, the MouseKeys feature is available.
MKF_CONFIRMHOTKEY | Windows 95, Windows NT 5.0, and later: A confirmation dialog box appears when the MouseKeys feature is activated by using the hot key.
MKF_HOTKEYACTIVE | If this flag is set, the user can turn the MouseKeys feature on and off by using the hot key, which is LEFT ALT+LEFT SHIFT+NUM LOCK.
MKF_HOTKEYSOUND | If this flag is set, the system plays a siren sound when the user turns the MouseKeys feature on or off by using the hot key.
MKF_INDICATOR | Windows 95, Windows NT 5.0, and later: A visual indicator is displayed when the MouseKeys feature is on.
MKF_MOUSEKEYSON | If this flag is set, the MouseKeys feature is on.
MKF_MODIFIERS | Windows 95, Windows NT 5.0, and later: The CTRL key increases cursor speed by the value specified by the iCtrlSpeed member, and the SHIFT key causes the cursor to delay briefly after moving a single pixel, allowing fine positioning of the cursor. If this value is not specified, the CTRL and SHIFT keys are ignored while the user moves the mouse cursor using the arrow keys.
MKF_REPLACENUMBERS | Windows 95, Windows NT 5.0, and later: The numeric keypad moves the mouse when the NUM LOCK key is on. If this flag is not specified, the numeric keypad moves the mouse cursor when the NUM LOCK key is off.

iMaxSpeed
Specifies the maximum speed the mouse cursor attains when an arrow key is held down.

Windows 95: Range checking is not performed.

Windows NT: Valid values are from 10 to 360.

iTimeToMaxSpeed
Specifies the length of time, in milliseconds, that it takes for the mouse cursor to reach maximum speed when an arrow key is held down. Valid values are from 1000 to 5000.
iCtrlSpeed
Specifies the multiplier to apply to the mouse cursor speed when the user holds down the ctrl key while using the arrow keys to move the cursor. this value is ignored if MKF_MODIFIERS is not set.
dwReserved1
This member is reserved for future use. It must be set to zero.
dwReserved2
This member is reserved for future use. It must be set to zero.

Remarks

An application uses a MOUSEKEYS structure when calling the SystemParametersInfo function with the wAction parameter set to the SPI_GETMOUSEKEYS or SPI_SETMOUSEKEYS value. When using SPI_GETMOUSEKEYS, an application must specify the cbSize member of the MOUSEKEYS structure; the SystemParametersInfo function fills the remaining members. An application must specify all structure members when using the SPI_SETMOUSEKEYS value.

QuickInfo

Windows NT: Requires version 3.5 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Accessibility Overview, Accessibility Structures, SystemParametersInfo


SERIALKEYS

The SERIALKEYS structure contains information about the SerialKeys accessibility feature, which interprets data from a communication aid attached to a serial port as commands causing the system to simulate keyboard and mouse input.

typedef struct tagSERIALKEYS {     // sk
    DWORD cbSize;
    DWORD dwFlags;
    LPSTR lpszActivePort;
    LPSTR lpszPort;
    DWORD iBaudRate;
    DWORD iPortState;
} SERIALKEYS, FAR* LPSERIALKEYS;

Members

cbSize
Specifies the structure size, in bytes.
dwFlags
Specifies a combination of the following values:
Value | Meaning
SERKF_ACTIVE | The SerialKeys feature is currently receiving input on the serial port specified by lpszPort.
SERKF_AVAILABLE | The SerialKeys feature is available.
SERKF_INDICATOR | A visual indicator is displayed when the SerialKeys feature is on. This value is not currently used and is ignored.
SERKF_SERIALKEYSON | The SerialKeys feature is on.

lpszActivePort
Points to a string that contains the name of the serial port that receives input from the communication aid when the SerialKeys feature is on. If no port is being used, this member is NULL. If this member is "Auto", the system watches all unused serial ports for input from communication aids.
lpszPort
Reserved; must be NULL.
iBaudRate
Specifies the baud rate setting for the serial port specified by the lpszActivePort member. This member should be set to one of the CBR_ values defined in the SDK header files. If lpszActivePort is NULL, this member is zero.
iPortState
Specifies the state of the port specified by the lpszActivePort member. If lpszActivePort is NULL, iPortState is zero; otherwise, it is one of the following values:
Value | Meaning
0 | All input on this port is ignored by the SerialKeys feature.
1 | Input on this port is watched for SerialKeys activation sequences when no other application has the port open.
2 | All input on this port is treated as SerialKeys commands.

Remarks

An application uses this structure when calling the SystemParametersInfo function with the SPI_GETSERIALKEYS or SPI_SETSERIALKEYS value. When using SPI_GETSERIALKEYS, an application must specify the cbSize, lpszActivePort, and lpszPort members of the SERIALKEYS structure; the SystemParametersInfo function fills the remaining members. An application must specify all structure members when using the SPI_SETSERIALKEYS value.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Unicode: Defined as Unicode and ANSI structures.

See Also

Accessibility Overview, Accessibility Structures, SystemParametersInfo


SOUNDSENTRY

The SOUNDSENTRY structure contains information about the SoundSentry accessibility feature. When the SoundSentry feature is on, the computer displays a visual indication only when a sound is generated.

Windows 95: The visual indication is displayed when a sound is generated through the computer's internal speaker.

Windows NT: The visual indication is displayed when a sound is generated through either the multimedia sound services or through the computer's speaker.

typedef struct tagSOUNDSENTRY {     // ss
    UINT cbSize;
    DWORD dwFlags;
    DWORD iFSTextEffect;
    DWORD iFSTextEffectMSec;
    DWORD iFSTextEffectColorBits;
    DWORD iFSGrafEffect;
    DWORD iFSGrafEffectMSec;
    DWORD iFSGrafEffectColor;
    DWORD iWindowsEffect;
    DWORD iWindowsEffectMSec;
    LPTSTR lpszWindowsEffectDLL;
    DWORD iWindowsEffectOrdinal;
} SOUNDSENTRY, *LPSOUNDSENTRY;

Members

cbSize
Specifies the size, in bytes, of this structure.
dwFlags
A set of bit flags that specify properties of the SoundSentry feature. The following bit-flag values are defined:
Value | Meaning
SSF_AVAILABLE | If this flag is set, the SoundSentry feature is available.
SSF_SOUNDSENTRYON | If this flag is set, the SoundSentry feature is on.

iFSTextEffect
Windows 95: Specifies the visual signal to present when a text-mode application generates a sound while running in a full-screen virtual machine. This member can be one of the following values:
Value | Meaning
SSTF_BORDER | Flash the screen border (that is, the overscan area), which is unavailable on some displays.
SSTF_CHARS | Flash characters in the corner of the screen.
SSTF_DISPLAY | Flash the entire display.
SSTF_NONE | No visual signal.

Windows NT: This member is reserved for future use. It must be set to zero.

iFSTextEffectMSec
Windows 95: Specifies the duration, in milliseconds, of the visual signal that is displayed when a full-screen, text-mode application generates a sound.

Wndows NT: This member is reserved for future use. It must be set to zero.

iFSTextEffectColorBits
Windows 95: Specifies the RGB value of the color to be used when displaying the visual signal shown when a full-screen, text-mode application generates a sound.

Windows NT: This member is reserved for future use. It must be set to zero.

iFSGrafEffect
Windows 95: Specifies the visual signal to present when a graphics-mode application generates a sound while running in a full-screen virtual machine. This member can be one of the following values:
Value | Meaning
SSGF_DISPLAY | No visual signal.
SSGF_NONE | Flash the entire display.

Windows NT: This member is reserved for future use. It must be set to zero.

iFSGrafEffectMSec
Windows 95: Specifies the duration, in milliseconds, of the visual signal that is displayed when a full-screen, graphics-mode application generates a sound.

Windows NT: This member is reserved for future use. It must be set to zero.

iFSGrafEffectColor
Windows 95: Specifies the RGB value of the color to be used when displaying the visual signal shown when a full-screen, graphics-mode application generates a sound.

Windows NT: This member is reserved for future use. It must be set to zero.

iWindowsEffect
Specifies the visual signal to display when a sound is generated by a Windows-based application or an MS-DOS application running in a window. This member can be one of the following values:
Value | Meaning
SSWF_CUSTOM | Call the SoundSentryProc routine exported by the DLL specified by the iFSWindowsEffectDLL member.
SSWF_DISPLAY | Flash the entire display.
SSWF_NONE | No visual signal.
SSWF_TITLE | Flash the title bar of the active window.
SSWF_WINDOW | Flash the active window.

iWindowsEffectMSec
Windows 95: Specifies the duration, in milliseconds, of the visual signal that is displayed when a Win32-based application (or an application running in a window) generates a sound.

Windows NT: This member is reserved for future use. It must be set to zero.

lpszWindowsEffectDLL
Points to the buffer that contains the name of the DLL that contains a SoundSentryProc callback function. The length of the name must not exceed the value of MAX_PATH. This member is NULL if no DLL is used. When retrieving information about the SoundSentry feature, the size of the buffer must be equal to, or larger than, the value of MAX_PATH.
iWindowsEffectOrdinal
This member is reserved for future use. It must be set to zero.

Remarks

An application uses a SOUNDSENTRY structure when calling the SystemParametersInfo function with the wAction parameter set to SPI_GETSOUNDSENTRY or SPI_SETSOUNDSENTRY. When using SPI_GETSOUNDSENTRY, an application must specify the cbSize member of the SOUNDSENTRY structure; the SystemParametersInfo function fills the remaining members. An application must specify the cbSize, dwFlags, and iWindowsEffect members when using the SPI_SETSOUNDSENTRY value.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Unicode: Defined as Unicode and ANSI structures.

See Also

Accessibility Overview, Accessibility Structures, SoundSentryProc, SystemParametersInfo


STICKYKEYS

The STICKYKEYS structure contains information about the StickyKeys accessibility feature. When the StickyKeys feature is on, the user can press a modifier key (shift, ctrl, or alt) and then another key in sequence rather than at the same time, to enter shifted (modified) characters and other key combinations.

typedef struct tagSTICKYKEYS {     // sk
    DWORD cbSize;
    DWORD dwFlags;
} STICKYKEYS, *LPSTICKYKEYS;

Members

cbSize
Specifies the size, in bytes, of this structure.
dwFlags
A set of bit-flags that specify properties of the StickyKeys feature. The following bit-flag values are defined:
Value | Meaning
SKF_AUDIBLEFEEDBACK | If this flag is set, the system plays a sound when the user latches, locks, or releases modifier keys using the StickyKeys feature.
SKF_AVAILABLE | If this flag is set, the StickyKeys feature is available.
SKF_CONFIRMHOTKEY | Windows 95, Windows NT 5.0, and later: A confirmation dialog appears when the StickyKeys feature is activated by using the hot key.
SKF_HOTKEYACTIVE | If this flag is set, the user can turn the StickyKeys feature on and off by pressing the shift key five times.
SKF_HOTKEYSOUND | If this flag is set, the system plays a siren sound when the user turns the StickyKeys feature on or off by using the hot key.
SKF_INDICATOR | Windows 95, Windows NT 5.0, and later: A visual indicator should be displayed when the StickyKeys feature is on.
SKF_STICKYKEYSON | If this flag is set, the StickyKeys feature is on.
SKF_TRISTATE | If this flag is set, pressing a modifier key twice in a row locks down the key until the user presses it a third time.
SKF_TWOKEYSOFF | If this flag is set, releasing a modifier key that has been pressed in combination with any other key turns off the StickyKeys feature.

Remarks

An application uses a STICKYKEYS structure when calling the SystemParametersInfo function with the wAction parameter set to SPI_GETSTICKYKEYS or SPI_SETSTICKYKEYS. When using SPI_GETSTICKYKEYS, an application must specify the cbSize member of the STICKYKEYS structure; the SystemParametersInfo function fills the remaining members. You must specify all structure members when using the SPI_SETSTICKYKEYS value.

QuickInfo

Windows NT: Requires version 3.5 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Accessibility Overview, Accessibility Structures, SystemParametersInfo


TOGGLEKEYS

The TOGGLEKEYS structure contains information about the ToggleKeys accessibility feature. When the ToggleKeys feature is on, the computer emits a high-pitched tone whenever the user turns on the caps lock, num lock, or scroll lock key, and a low-pitched tone whenever the user turns off one of those keys.

typedef struct tagTOGGLEKEYS {     // tk
    DWORD cbSize;
    DWORD dwFlags;
} TOGGLEKEYS;

Members

cbSize
Specifies the size, in bytes, of this structure.
dwFlags
A set of bit flags that specify properties of the ToggleKeys feature. The following bit flag values are defined:
Value | Meaning
TKF_AVAILABLE | If this flag is set, the ToggleKeys feature is available.
TKD_CONFIRMHOTKEY | Windows 95, Windows NT 5.0, and later: A confirmation dialog box appears when the ToggleKeys feature is activated by using the hot key.
TKF_HOTKEYACTIVE | If this flag is set, the user can turn the ToggleKeys feature on and off by holding down the num lock key for eight seconds.
TKF_HOTKEYSOUND | If this flag is set, the system plays a siren sound when the user turns the ToggleKeys feature on or off by using the hot key.
TKF_TOGGLEKEYSON | If this flag is set, the ToggleKeys feature is on.

Remarks

An application uses a TOGGLEKEYS structure when calling the SystemParametersInfo function with the wAction parameter set to SPI_GETTOGGLEKEYS or SPI_SETTOGGLEKEYS. When using SPI_GETTOGGLEKEYS, an application must specify the cbSize member of the TOGGLEKEYS structure; the SystemParametersInfo function fills the remaining members. An application must specify all structure members when using the SETTOGGLEKEYS value.

QuickInfo

Windows NT: Requires version 3.5 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Accessibility Overview, Accessibility Structures, SystemParametersInfo


Common Dialog Box Library

The Common Dialog Box Library contains a set of dialog boxes for performing common tasks, such as opening files and printing documents. The common dialog boxes provide a uniform user interface that lets users carry out these common tasks without being forced to learn new techniques with each application.


About Common Dialog Boxes

This overview describes the common dialog boxes and explains how to use them in Win32-based applications. The common dialog boxes include the Open and Save As file dialog boxes; the Find and Replace editing dialog boxes; the Print, Print Setup, and Page Setup printing dialog boxes; and the Color and Font dialog boxes.

You can create common dialog boxes for your applications by using the common dialog box functions. These functions supply the dialog box procedures and templates for the common dialog boxes. You supply the initial values for the dialog boxes and the addresses of the variables and buffers that receive the input from the dialog boxes.


Dialog Box Types

The Common Dialog Box Library provides a creation function and a structure for each type of common dialog box. To use a common dialog box in its simplest form, you call its creation function and specify a pointer to a structure containing initial values and option flags. After initializing the dialog box, the dialog box procedure uses the structure to return information about the user's input. You can also customize a common dialog box to suit the needs of your application.

The following table provides a brief description of the different types of common dialog boxes, and shows the function and structure used with each type.

Common Dialog Box | Description
Color | Displays available colors and optionally lets the user create custom colors. The user can select a basic or custom color. Use the ChooseColor function and CHOOSECOLOR structure.
Find | Displays a dialog box in which the user can type the string to find. The user can also specify search options, such as the search direction and whether the search is case sensitive. Use the FindText function and FINDREPLACE structure.
Font | Displays lists of available fonts, point sizes, and other font attributes that the user can select. Use the ChooseFont function and CHOOSEFONT structure.
Open | Displays lists of drives, directories, and filename extensions from which the user can select to display a list of filenames. The user can type a filename or select one from the list to identify the file to be opened. Use the GetOpenFileName function and OPENFILENAME structure.
Print | Displays information about the installed printer and its configuration. The user can select print job options, such as the range of pages to print and the number of copies, and start the printing process. Use the PrintDlg function and PRINTDLG structure. Windows NT 5.0 and later: To display a Print property sheet rather than a Print dialog box, use the PrintDlgEx function with the PRINTDLGEX structure. The General page of the property sheet is similar to the Print dialog box. The property sheet can also have additional application-specific and driver-specific property pages following the General page.
Page Setup | Displays the current page configuration. The user can select page configuration options, such as paper orientation, size, source, and margins. Use the PageSetupDlg function and PAGESETUPDLG structure.
Replace | Displays a dialog box in which the user can type the string to find and the replacement string. The user can specify search options, such as whether the search is case sensitive, and replacement options, such as the scope of replacement. Use the ReplaceText function and FINDREPLACE structure.
Save As | Displays lists of drives, directories, and filename extensions from which the user can select to display a list of filenames. The user can type a filename or select one from the list to specify the name with which to save the file. Use the GetSaveFileName function and OPENFILENAME structure.

Note Although a Print Setup dialog box is also available, it has been superseded by the Page Setup dialog box. New applications written for Windows 95 or for Windows NT versions 3.51 or later should use the Page Setup dialog box rather than the Print Setup dialog box.

All common dialog boxes are modal, except the Find and Replace dialog boxes. Modal dialog boxes must be closed by the user before the function used to create the dialog box can return. The Find and Replace dialog boxes are modeless; the function returns before the dialog box closes. If you use the Find and Replace dialog boxes, you must also use the IsDialogMessage function in the main message loop of your application to ensure that these dialog boxes correctly process keyboard input, such as the tab and esc keys.


Common Dialog Box Initialization Flags

You can use initialization flags to modify the behavior and appearance of a common dialog box. Initialization flags are the values that you set in the Flags member of the structure used to create the dialog box. You use the flags to specify which controls in a dialog box receive initial values, to disable selected controls, and to modify the range of values the user can set with the controls. You also use the flags to enable hook procedures and custom templates for the dialog boxes.

For example, you set the CF_EFFECTS value in the Flags member of the CHOOSEFONT structure to direct the Font dialog box to display a set of controls. These controls let the user choose the color of the logical font as well as whether to use strikethrough and underline effects.

The initialization flag values are unique to each common dialog box and are described in detail with the structures that correspond to them.


Customizing Common Dialog Boxes

You can use the common dialog boxes in their standard form, or you can customize them. From the user's perspective, the chief benefit of the common dialog box is its consistent appearance and functionality from application to application. Therefore, it is important that you customize a common dialog box only when it is absolutely necessary for an application. Otherwise, the consistent appearance and simple coding interface are lost. Appropriate customizations leave intact as many of the original controls as possible. Increasing the size of the dialog box or adding new controls in the space already available in the dialog box is an appropriate customization. Hiding original controls or otherwise changing the intended functionality of the original controls is a less appropriate customization.

This section discusses the following methods for customizing a common dialog box:

  • Providing a custom dialog template that defines additional controls or modifies the standard controls
  • Creating a hook procedure to monitor and filter messages sent to the dialog box procedure
  • Using registered messages to receive or send information to the dialog box
  • Providing help support for a common dialog box


Custom Templates

Common dialog boxes have default templates that define the number, type, and position of the standard controls in the dialog box. You can define a custom template to give users access to additional controls that are unique to your application.

For all common dialog boxes except the Explorer-style Open and Save As dialog boxes, you modify the default template to create a custom template that replaces the default template. The custom template defines the type and position of the standard controls as well as any additional controls.

When you create a custom dialog box template by modifying the default dialog box template, make sure the identifiers for any added controls are unique and do not conflict with the identifiers of the standard controls. The following table lists the name of the default template file and include file for each of the common dialog box types.

Dialog box type | Template file | Include file
Color | COLOR.DLG | COLORDLG.H
Find | FINDTEXT.DLG | DLGS.H
Font | FONT.DLG | DLGS.H
Open (multiple selection) | FILEOPEN.DLG | DLGS.H
Open (single selection) | FILEOPEN.DLG | DLGS.H
Page Setup | PRNSETUP.DLG | DLGS.H
Print | PRNSETUP.DLG | DLGS.H
Print Setup (obsolete) | PRNSETUP.DLG | DLGS.H
Replace | FINDTEXT.DLG | DLGS.H

To enable a custom template, you must set a flag in the Flags member of the corresponding structure for the dialog box. If the template is a resource in an application or dynamic-link library, set an ENABLETEMPLATE flag in the Flags member, and use the hInstance and lpTemplateName members of the structure to identify the module and resource name. If the template is already in memory, set an ENABLETEMPLATEHANDLE flag in the Flags member, and use the hInstance member to identify the memory object that contains the template.

In most cases, you must also enable a hook procedure for the dialog box to support and process input for the additional controls in your custom template.

For the Explorer-style Open and Save As dialog boxes, the default templates are not available for modification. Instead, your custom template defines a child dialog box that includes only the items to be added to the standard dialog box. The custom template can also define a static control that specifies the location of the cluster of standard controls in the child dialog box. For more information, see Explorer-Style Custom Templates.


Hook Procedures for Common Dialog Boxes

For each of the common dialog boxes, you can enable a hook procedure to process messages from the default dialog box procedure. There are two general types of common dialog hook procedures:

  • The standard hook procedure used with most common dialog boxes
  • The Explorer-style hook procedure supported by the Open and Save As dialog boxes

When you provide a standard hook procedure for one of the common dialog boxes, the default dialog box procedure handles its messages as follows.

Message | Handling
WM_INITDIALOG | The default dialog box procedure processes the message before passing it to the hook procedure. The message's lParam parameter is a pointer to the initialization structure specified when the dialog was created.
All other messages | The hook procedure receives the message first. Then, the return value of the hook procedure determines whether the default dialog procedure processes the message or ignores it.

For the Explorer-style Open and Save As dialog boxes, the hook procedure does not receive messages intended for the standard controls in the common dialog box. Instead, it receives notification messages from the dialog box and messages for any additional controls that you defined in a custom template. For more information, see Explorer-Style Hook Procedures.

To enable a hook procedure, set an ENABLEHOOK value in the Flags member of the corresponding structure for the dialog box. If an ENABLEHOOK flag is set, an lpfnHook member of the structure must specify the address of the hook procedure.

The following table shows the type of hook procedure to provide for each of the common dialog boxes.

Common dialog box type | Hook procedure
Color | CCHookProc
Find or Replace | FRHookProc
Font | CFHookProc
Open or Save As (Explorer-style) | OFNHookProc
Open or Save As (Old-style) | OFNHookProcOldStyle
Print | PrintHookProc
Page Setup | PageSetupHook

For the Page Setup dialog box, you can also specify a PagePaintHook hook procedure. This is a special hook procedure that you can use to customize the appearance of the sample page displayed by the Page Setup dialog box.

Note The Print Setup dialog box has been superseded by the Page Setup dialog box, which should be used by new applications written for Windows 95 or for Windows NT versions 3.51 or later. However, for compatibility, the PrintDlg function continues to support display of the Print Setup dialog box. You can provide a SetupHookProc hook procedure for the Print Setup dialog box.


Common Dialog Messages

Common dialog boxes use messages to notify your window procedure or hook procedure when certain events occur. In addition, there are messages that you can send to a common dialog box to retrieve information or to control the behavior or appearance of the dialog box. This section describes the common dialog messages registered by the RegisterWindowMessage function, messages used by the Font dialog box and Page Setup dialog box, and messages used by the Explorer-style Open and Save As dialog boxes.

The Common Dialog Box Library defines a set of message strings. You can pass a constant associated with one of these message strings to RegisterWindowMessage to get a message identifier. You can then use the identifier to detect and process messages sent from a common dialog box, or to send messages to a common dialog box. The following table shows the message constants and describes their use.

COLOROKSTRING | A Color dialog box sends this message to the hook procedure when the user selects a color and clicks the OK button. The hook procedure can accept the color, or reject it and force the dialog box to remain open.
FILEOKSTRING | An Open or Save As dialog box sends this message to the hook procedure when the user selects a filename and clicks the OK button. The hook procedure can accept the filename, or reject it and force the dialog box to remain open. For Explorer-style Open and Save As dialog boxes, this message has been superseded by the CDN_FILEOK notification message.
FINDMSGSTRING | A Find or Replace dialog box sends this message to the window procedure of its parent window when the user clicks the Find Next, Replace, or Replace All button, or closes the dialog box. The message's lParam parameter points to a FINDREPLACE structure containing the user's input.
HELPMSGSTRING | All common dialog boxes send this message to the window procedure of their parent window when the user clicks the Help button. For Explorer-style Open and Save As dialog boxes, this message has been superseded by the CDN_HELP notification message.
LBSELCHSTRING | An Open or Save As dialog box sends this message to the hook procedure when the user changes the selection in the Filename list box. For Explorer-style Open and Save As dialog boxes, this message has been superseded by the CDN_SELCHANGE notification message.
SETRGBSTRING | A hook procedure can send this message to a Color dialog box to set the current color selection.
SHAREVISTRING | An Open or Save As dialog box sends this message to the hook procedure if a sharing violation occurs for the selected file when the user clicks the OK button. For Explorer-style Open and Save As dialog boxes, this message has been superseded by the CDN_SHAREVIOLATION notification message.

Some common dialog boxes send and receive other window messages. The hook procedure for a Font dialog box can send any of the WM_CHOOSEFONT_* messages to the Font dialog box. For more information, see Font Dialog Box. The Page Setup dialog box sends the WM_PSD_* messages if you have enabled a PagePaintHook hook procedure. For more information, see Page Setup Dialog Box.

The Explorer-style Open and Save As dialog boxes support a set of predefined messages. These include notification messages sent in the form of a WM_NOTIFY message to your hook procedure, and messages that your hook procedure can send to the dialog box. For a complete list of these messages, see Explorer-Style Hook Procedures.


Help Support

Common dialog boxes provide context-sensitive Help for the standard controls of the dialog box. To provide additional help for a common dialog box, you can display a Help button and process messages generated when the user clicks the button. The Help button is a supplement to the default context-sensitive Help. The Help button is useful for describing the general purpose of the dialog box as it applies to your application.

Context-Sensitive Help

All common dialog boxes provide context-sensitive Help for the standard controls of the dialog box. The user can display Help for individual controls by any of the following methods:

  • Selecting the control and pressing the f1 key
  • Clicking the ? button in the title bar and subsequently clicking on a control
  • Clicking the right mouse button over a control

If you customize a dialog box by adding new controls, you must also extend help support for these controls by processing requests for help in the hook procedure. The hook procedure receives the following messages when the user requests help.

User Action | Message
The user clicked the right mouse button over a control. | WM_CONTEXTMENU
The user pressed the f1 key. | WM_HELP
The user clicked the ? button on the title bar and then clicked a control. | WM_HELP

You should process these messages for the controls you have added, but let the default dialog box procedure process the messages for the standard controls. For more information about how to process these messages, see the Help overview.

The Help Button

You can display a Help button in any of the common dialog boxes by setting a SHOWHELP value in the Flags member of the initialization structure for the dialog box. If you display the Help button, you must process the user's request for help. The processing can be done either in one of your application's window procedures or in a hook procedure for the dialog box. Typically, you would process the request for help by calling the WinHelp function.

To process help messages in one of your window procedures, you must get a message identifier for the string defined by the HELPMSGSTRING value and identify the window to receive messages. To get the message identifier, specify HELPMSGSTRING as the parameter in a call to the RegisterWindowMessage function. When you create the common dialog box, use the hwndOwner member of the dialog box initialization structure to identify the window that is to receive the messages. The dialog box procedure sends the message to the window procedure whenever the user clicks the Help button.

To process help messages in a hook procedure, you should process the WM_COMMAND message. The hook procedure provides help if the wParam parameter of this message indicates that the user clicked the Help button. The identifier of the Help button is the pshHelp constant defined in the DLGS.H file.

Hook procedures for the Explorer-style Open and Save As common dialog boxes do not receive WM_COMMAND messages for the Help button. Instead, the dialog box sends a CDN_HELP notification message to the hook procedure when the Help button is clicked.


Color Dialog Box

The Color dialog box returns the RGB value of a color selected by the user. The user can select from a set of basic colors determined by the display driver or from a set of custom colors. You must specify the initial set of custom colors, but you can allow users to create their own custom colors.

You create and display a Color dialog box by initializing a CHOOSECOLOR structure and passing the structure to the ChooseColor function.

You can partially open the Color dialog box to display the basic and custom colors from which the user can select, or you can completely open the dialog box to display additional controls that allow the user to create custom colors. The following illustration shows the fully opened Color dialog box.

If the user clicks the OK button, ChooseColor returns TRUE. The rgbResult member of the CHOOSECOLOR structure contains the RGB color value of the color selected by the user. The RGB color value specifies the intensities of the individual red, green, and blue colors that make up the selected color. The individual values range from 0 through 255. Use the GetRValue, GetBValue, and GetGValue macros to extract individual colors from an RGB color value.

If the user cancels the Color dialog box or an error occurs, ChooseColor returns FALSE and the rgbResult member is not defined. To determine the cause of the error, call the CommDlgExtendedError function to retrieve the extended error value.


Basic and Extended Color Dialog Boxes

The Color dialog box has a basic version and an extended version. The basic version has controls that display the basic and custom colors from which the user can select. The extended version includes the basic controls and has additional controls that allow the user to create custom colors.

The basic version of the Color dialog box includes a Define Custom Colors button. The user can click this button to display the extended version. You can direct the Color dialog box to always display this extension by setting the CC_FULLOPEN flag in the Flags member of the CHOOSECOLOR structure. To prevent the user from creating custom colors, you can set the CC_PREVENTFULLOPEN flag to disable the Define Custom Colors button.

The basic colors represent a selection of the colors available on the given device. The actual number of colors displayed is determined by the display driver. For example, a VGA driver displays 48 colors, and a monochrome display driver displays only 16.

The custom colors are those that you specify or that the user creates. When you create a Color dialog box, you must use the lpCustColors member of the CHOOSECOLOR structure to specify the initial values for the 16 custom colors. If the extended version of the Color dialog box is open, the user can create a custom color by one the following methods:

  • Moving the cursor in the color spectrum control and the luminosity slide control
  • Typing red, green, and blue (RGB) values in the Red, Green, and Blue edit controls
  • Typing hue, saturation, and luminosity (HSL) values in the Hue, Sat, and Lum edit controls

To add a new custom color to the custom colors display, the user can click the Add to Custom Colors button. This also causes the dialog box to copy the RGB value of the new color to the corresponding element in the array pointed to by the lpCustColors member. To preserve new custom colors between calls to ChooseColor, you should allocate static memory for the array. For more information about the RGB and HSL color models, see Color Models Used by the Color Dialog Box.


Customizing the Color Dialog Box

To customize a Color dialog box, you can use any of the following methods:

  • Specify values in the CHOOSECOLOR structure when you create the dialog box.
  • Provide a custom template.
  • Provide a hook procedure.

You can modify the appearance and behavior of the Color dialog box by setting flags in the Flags member of the CHOOSECOLOR structure. For example, you can set the CC_SOLIDCOLOR flag to direct the dialog box to display only solid colors. To cause the dialog box to initially select a color other than black, set the CC_RGBINIT flag and specify a color in the rgbResult member.

You can provide a custom template for the Color dialog box, for example, if you want to include additional controls that are unique to your application. The ChooseColor function uses your custom template in place of the default template.

To provide a custom template for the Color dialog box
  1. Create the custom template by modifying the default template specified in the COLOR.DLG file. The control identifiers used in the default Color dialog template are defined in the COLORDLG.H file.
  2. Use the CHOOSECOLOR structure to enable the template as follows:
    • If your custom template is a resource in an application or dynamic-link library, set the CC_ENABLETEMPLATE flag in the Flags member. Use the hInstance and lpTemplateName members of the structure to identify the module and resource name.

      -Or-

    • If your custom template is already in memory, set the CC_ENABLETEMPLATEHANDLE flag. Use the hInstance member to identify the memory object that contains the template.

You can provide a CCHookProc hook procedure for the Color dialog box. The hook procedure can process messages sent to the dialog box. It can also use registered messages to control the behavior of the dialog box. If you use a custom template to define additional controls, you must provide a hook procedure to process input for your controls.

To enable a hook procedure for the Color dialog box
  1. Set the CC_ENABLEHOOK flag in the Flags member of the CHOOSECOLOR structure.
  2. Specify the address of the hook procedure in the lpfnHook member.

After processing its WM_INITDIALOG message, the dialog box procedure sends a WM_INITDIALOG message to the hook procedure. The lParam parameter of this message is a pointer to the CHOOSECOLOR structure used to initialize the dialog box.

The dialog box sends the COLOROKSTRING registered message to the hook procedure when the user clicks the OK button. The hook procedure can reject the selected color and force the dialog box to remain open by returning zero when it receives this message. The hook procedure can force the dialog box to select a particular color by sending the SETRGBSTRING registered message to the dialog box. To use these registered messages, you must pass the COLOROKSTRING and SETRGBSTRING constants to the RegisterWindowMessage function to get a message identifier. You can then use the identifier to detect and process messages sent from the dialog box, or to send messages to the dialog box.


Color Models Used by the Color Dialog Box

The custom colors extension of the Color dialog box allows the user to specify a color using RGB or HSL values. However, the CHOOSECOLOR structure uses only RGB values to report the colors created or selected by the user.

RGB Color Model

The RGB model is used to designate colors for displays and other devices that emit light. Valid red, green, and blue values range from 0 through 255, with 0 indicating minimum intensity and 255 indicating maximum intensity. The following illustration shows how the primary colors red, green, and blue can be combined to produce four additional colors. (For display devices, the color black results when the red, green, and blue values are set to 0. In display technology, black is the absence of all colors.)

Following are eight colors and their associated RGB values.

Color | RGB values
Red | 255, 0, 0
Green | 0, 255, 0
Blue | 0, 0, 255
Cyan | 0, 255, 255
Magenta | 255, 0, 255
Yellow | 255, 255, 0
White | 255, 255, 255
Black | 0, 0, 0

The system stores internal colors as 32-bit RGB values that have the following hexadecimal form:

0x00bbggrr

The low-order byte contains a value for the relative intensity of red; the second byte contains a value for green; and the third byte contains a value for blue. The high-order byte must be zero.

You can use the RGB macro to get an RGB value based on specified intensities for the red, green, and blue components. Use the GetRValue, GetBValue, and GetGValue macros to extract individual colors from an RGB color value.

HSL Color Model

The Color dialog box provides controls for specifying HSL values. The following illustration shows the color spectrum control and the luminosity slide control that appear in the Color dialog box. The illustration also shows the ranges of values the user can specify with these controls.

In the Color dialog box, the saturation and luminosity values must be in the range 0 through 240, and the hue value must be in the range 0 through 239.

Converting HSL Values to RGB Values

The dialog box procedure provided in COMDLG32.DLL for the Color dialog box contains code that converts HSL values to the corresponding RGB values. Following are several colors and their associated HSL and RGB values.

Color | HSL values | RGB values
Red | (0, 240, 120) | (255, 0, 0)
Yellow | (40, 240, 120) | (255, 255, 0)
Green | (80, 240, 120) | (0, 255, 0)
Cyan | (120, 240, 120) | (0, 255, 255)
Blue | (160, 240, 120) | (0, 0, 255)
Magenta | (200, 240, 120) | (255, 0, 255)
White | (0, 0, 240) | (255, 255, 255)
Black | (0, 0, 0) | (0, 0, 0)


Font Dialog Box

The Font dialog box lets the user choose attributes for a logical font, such as typeface name, style (bold, italic, or regular), point size, effects (underline, strikeout, and text color), and a script (or character set).

You create and display a Font dialog box by initializing a CHOOSEFONT structure and passing the structure to the ChooseFont function.

The following illustration shows a typical Font dialog box.

If the user clicks the OK button, ChooseFont returns TRUE and sets the members of the LOGFONT structure pointed to by the lpLogFont member of the CHOOSEFONT structure. You can use the LOGFONT structure with the CreateFontIndirect function to create a logical font. ChooseFont also sets other CHOOSEFONT members to indicate the user's selections.

If the user cancels the Font dialog box or an error occurs, ChooseFont returns FALSE and the contents of the LOGFONT structure are not defined. You can determine the cause of an error by using the CommDlgExtendedError function to retrieve the extended error value.


Font Dialog Initialization Flags

Before calling ChooseFont, the Flags member of the CHOOSEFONT structure must specify CF_SCREENFONTS, CF_PRINTERFONTS, or CF_BOTH, to indicate whether the dialog box should list screen fonts, printer fonts, or both. If you specify CF_PRINTERFONTS or CF_BOTH, the hDC member of the CHOOSEFONT structure must specify a handle to a device context for the printer.

You can use the Flags member to enable or disable some of the dialog box controls, and you can use the Flags member in conjunction with other CHOOSEFONT members to control the initial values of some controls.

To display the controls that allow the user to select strikeout, underline, and color options
  • Set the CF_EFFECTS flag. You can use the rgbColors member of the CHOOSEFONT structure to specify an initial font color.
To specify the initial values of the Font, Font Style, Size, Strikeout, and Underline dialog box controls
  • Set the CF_INITTOLOGFONTSTRUCT flag to use members of the LOGFONT structure to specify the initial values.
  • You can also use the CF_NOFACESEL, CF_NOSTYLESEL, and CF_NOSIZESEL flags to selectively prevent the dialog box from displaying initial values for the corresponding controls. This is useful when working with a selection of text that has more than one typeface, style, or point size. These values will also be set in Flags when ChooseFont returns if the user did not select a corresponding value.
To initialize the Font Style control to a specified style name
  • Set the CF_USESTYLE flag and use the lpszStyle member to specify the style name.
To display the Apply button
  • Set the CF_APPLY flag and provide a hook procedure to process WM_COMMAND messages for the Apply button. The hook procedure can send the WM_CHOOSEFONT_GETLOGFONT message to the dialog box to retrieve the address of the LOGFONT structure that contains the current selections for the font.
To display the Help button
  • Set the CF_SHOWHELP flag. The hwndOwner member must identify the window to receive the HELPMSGSTRING registered message when the user clicks the Help button.
To restrict the fonts the dialog box displays
  • Set any combination of the CF_TTONLY, CF_FIXEDPITCHONLY, CF_NOVECTORFONTS, CF_NOVERTFONTS, CF_SCALABLEONLY, and CF_WYSIWYG flags. You can also restrict the available styles, point sizes, and effects the dialog box displays for some fonts by using the CF_NOSIMULATIONS value.
To restrict the typeface names, styles, and point sizes that the user can specify
  • Set the CF_FORCEFONTEXIST flag to restrict the user to specifying only valid typeface names, styles, and point sizes.
  • Set the CF_LIMITSIZE flag to restrict the user to specifying point sizes in the range specified by the nSizeMin and nSizeMax members.
To restrict or disable the Scripts combo box
  • Set the CF_NOSCRIPTSEL flag to disable the Scripts combo box, or set the CF_SELECTSCRIPT flag to restrict selections in the Scripts combo box to a specified character set.


Customizing the Font Dialog Box

You can provide a custom template for the Font dialog box, for example, if you want to include additional controls that are unique to your application. The ChooseFont function uses your custom template in place of the default template.

To provide a custom template for the Font dialog box
  1. Create the custom template by modifying the default template specified in the FONT.DLG file. The control identifiers used in the default Font dialog template are defined in the DLGS.H file.
  2. Use the CHOOSEFONT structure to enable the template as follows:
    • If your custom template is a resource in an application or dynamic-link library, set the CF_ENABLETEMPLATE flag in the Flags member. Use the hInstance and lpTemplateName members of the structure to identify the module and resource name.

      -Or-

    • If your custom template is already in memory, set the CF_ENABLETEMPLATEHANDLE flag. Use the hInstance member to identify the memory object that contains the template.

You can provide a CFHookProc hook procedure for the Font dialog box. The hook procedure can process messages sent to the dialog box. It can also send messages to the dialog box. If you use a custom template to define additional controls, you must provide a hook procedure to process input for your controls.

To enable a hook procedure for the Font dialog box
  1. Set the CF_ENABLEHOOK flag in the Flags member of the CHOOSEFONT structure.
  2. Specify the address of the hook procedure in the lpfnHook member.

After processing its WM_INITDIALOG message, the dialog box procedure sends a WM_INITDIALOG message to the hook procedure. The lParam parameter of this message is a pointer to the CHOOSEFONT structure used to initialize the dialog box.

The hook procedure can send the WM_CHOOSEFONT_GETLOGFONT, WM_CHOOSEFONT_SETLOGFONT, and WM_CHOOSEFONT_SETFLAGS messages to the dialog box to get and set the current values and flags of the dialog box.


Open and Save As Dialog Boxes

The Open dialog box lets the user specify the drive, directory, and the name of a file or set of files to open. You create and display an Open dialog box by initializing an OPENFILENAME structure and passing the structure to the GetOpenFileName function.

The Save As dialog box lets the user specify the drive, directory, and name of a file to save. You create and display a Save As dialog box by initializing an OPENFILENAME structure and passing the structure to the GetSaveFileName function.

Beginning with Windows 95 and Windows NT version 4.0, a new version of the Open and Save As dialog boxes provides user-interface features that are similar to the Windows Explorer. However, the system continues to support the old-style Open and Save As dialog boxes for applications that must be consistent with the older user interface.

In addition to the difference in appearance, the Explorer-style and old-style dialog boxes differ in their use of custom templates and hook procedures for customizing the dialog boxes. However, the Explorer-style and old-style dialog boxes have the same behavior for most basic operations, such as specifying a filename filter, validating the user's input, and getting the filename specified by the user. For more information about the Explorer-style and old-style dialog boxes, see Open and Save As Dialog Box Customization.

The following illustration shows a typical Explorer-style Open dialog box.

The following illustration shows a typical Explorer-style Save As dialog box.

If the user specifies a filename and clicks the OK button, GetOpenFileName or GetSaveFileName returns TRUE. The buffer pointed to by the lpstrFile member of the OPENFILENAME structure contains the full path and filename specified by the user.

If the user cancels the Open or Save As dialog box or an error occurs, the function returns FALSE. To determine the cause of the error, call the CommDlgExtendedError function to retrieve the extended error value. If the lpstrFile buffer is too small to receive the full name, CommDlgExtendedError returns FNERR_BUFFERTOOSMALL and the first 2 bytes of the buffer pointed to by the lpstrFile member are set to an integer value specifying the size required to receive the full name.

Explorer style dialog boxes are only available to 32-bit applications. 16-bit applications cannot use thunking to display an Explorer-style dialog box.

Windows 95 and Windows 98: Win32-based applications that use the old-style dialog boxes do so using a thunk. This means that any pointer passed to your hook procedure is a nonpersistent copy of the data. For example, the OPENFILENAME pointer passed in the WM_INITDIALOG message is not a pointer to the buffer that you originally specified. If you need to pass private data to your hook procedure, bundle it in a structure and store a pointer to the structure in the lCustData member of the OPENFILENAME structure.


Filenames and Directories

The information in this section applies to both Explorer-style and old-style Open and Save As dialog boxes.

Before calling the GetOpenFileName or GetSaveFileName functions, the lpstrFile member of the OPENFILENAME structure must point to the buffer to receive the filename. The nMaxFile member must specify the size, in bytes (ANSI version) or 16-bit characters (Unicode version), of the lpstrFile buffer.

If the user specifies a filename and clicks the OK button, the dialog box copies the selected drive, directory, and filename to the lpstrFile buffer. The function also sets the nFileOffset and nFileExtension members to the offsets, in bytes (ANSI version) or 16-bit characters (Unicode version), from the start of the buffer to the filename and to the filename extension, respectively.

To retrieve just the filename and extension, set the lpstrFileTitle member to point to a buffer and set the nMaxFileTitle member to the size, in bytes (ANSI version) or 16-bit characters (Unicode version), of the buffer. Alternatively, you can pass the lpstrFile buffer in a call to the GetFileTitle function to get the display name of the selected file. Note, however, that the filename that GetFileTitle returns includes an extension only if that is the user's preference for displaying filenames.

The dialog box uses the current directory for the calling process as the initial directory from which to display files and directories. Use the GetCurrentDirectory or SetCurrentDirectory functions to get or change your current directory. To specify a different initial directory without changing your current directory, use the lpstrInitialDir member to specify the name of a directory. The dialog box automatically changes your current directory when the user selects a different drive or directory. To prevent the dialog box from changing your current directory, set the OFN_NOCHANGEDIR flag. This flag does not prevent the user from changing directories to find a file.

To specify a default filename extension, use the lpstrDefExt member. If the user specifies a filename that does not have an extension, the dialog box adds your default extension. If you specify a default extension and the user specifies a filename with a different extension, the dialog box sets the OFN_EXTENSIONDIFFERENT flag.

To let the user select more than one file from a directory, set the OFN_ALLOWMULTISELECT flag. For compatibility with older applications, the default multiple selection dialog box uses the old-style user interface. To display an Explorer-style multiple selection dialog box, you must also set the OFN_EXPLORER flag.

If the user selects more than one file, the buffer pointed to by the lpstrFile member returns the path to the current directory followed by the filenames of the selected files. The nFileOffset member is the offset to the first filename, and the nFileExtension member is not used. The following table describes the difference between Explorer-style and old-style dialog boxes in returning multiple filenames.

Dialog box style | Description
Explorer-style dialog boxes | The directory and filename strings are NULL separated, with an extra NULL character after the last filename. This format enables the Explorer-style dialogs to return long filenames that include spaces.
Old-style dialog boxes | The directory and filename strings are separated by spaces. For filenames with spaces, the function uses short filenames.

You can use the FindFirstFile function to convert between long and short filenames.


Filters

The information in this section applies to both Explorer-style and old style Open and Save As dialog boxes.

You can provide filename filters to assist the user in limiting the filenames that the dialog box displays. A filename filter consists of a pair of null-terminated strings, a description and a pattern, one concatenated to the other. The dialog box displays the description to let the user pick which filter to use; and it uses the pattern to select the files to display.

To specify the filters, set the lpstrFilter member of the OPENFILENAME structure to point to a buffer that contains an array of filter string pairs. The last string in the array must be followed by an extra null character.

A pattern string can be a combination of valid filename characters and the asterisk (*). The asterisk is a wildcard that represents any combination of valid filename characters. The dialog box displays only those files that match the pattern. To specify multiple patterns for the same description, you must use a semicolon (;) to separate the patterns. Note that space characters in the pattern string can produce unexpected results.

The following code fragment specifies two filters. The filter with the "Source" description has two patterns. If the user selects this filter, the dialog box displays only files that have the .C and .CXX extensions.

OPENFILENAME ofn;       // common dialog box structure

ofn.lpstrFilter = "Source\0*.C;*.CXX\0All\0*.*\0"
ofn.nFilterIndex = 1;

The nFilterIndex member of the OPENFILENAME structure specifies an index that indicates which filter the dialog box initially uses. The first filter in the buffer has index 1, the second 2, and so on. If the user changes the filter while using the dialog box, the nFilterIndex member is set to the index of the selected filter on return.

You can create a custom filter by setting the lpstrCustomFilter member to the address of a buffer that contains a single filter, and by setting the nMaxCustFilter member to the size of the buffer, in characters or bytes. The dialog box always places the custom filter at the beginning of the list of filters and, on return, always updates the pattern part of the filter with the pattern from the filter selected by the user.

For Explorer-style dialog boxes, the default extension may change if the user selects a different filter. If the user selects a filter whose first pattern is of the form *.xxx (that is, the extension does not include a wildcard character), the dialog box uses xxx as the default extension. This occurs only if you specified a default extension in the lpstrDefExt member of the OPENFILENAME structure. For example, if the user selects the "Source\0*.C;*.CXX\0" filter, the default extension changes to "C". However, if you had defined the filter as "Source\0*.C*\0", the default extension would not change because the extension includes a wildcard.


File and Directory Validation

Except as noted, the information in this section applies to both Explorer-style and old-style Open and Save As dialog boxes.

The dialog box automatically validates filenames typed by the user to ensure that the names contain only valid characters. To override the filename character validation, set the OFN_NOVALIDATE flag.

To force the dialog box to verify that the user specified the name of an existing file, set the OFN_FILEMUSTEXIST flag. To force verification that the specified path exists, set the OFN_PATHMUSTEXIST flag. If you set the OFN_CREATEPROMPT flag, the dialog box prompts the user for permission to create a nonexistent file. If this flag is set and the user chooses to create a new file, the dialog box closes, and the function returns the specified name. Otherwise, the dialog box remains open.

When using the Save As dialog box, you can direct the dialog box to prompt the user for permission to overwrite an existing file by setting the OFN_OVERWRITEPROMPT flag.

By default, the dialog box creates a zero-length test file to determine whether a new file can be created in the selected directory. To prevent the creation of this test file, set the OFN_NOTESTFILECREATE flag.

If you enable a hook procedure, the dialog box notifies your hook procedure when a network sharing violation occurs for the filename specified by the user. If you set the OFN_EXPLORER flag, the dialog box sends the CDN_SHAREVIOLATION message to the hook procedure. If you do not set OFN_EXPLORER, the dialog box sends the SHAREVISTRING registered message to the hook procedure. To prevent the dialog box from sending any notifications for sharing violations, set the OFN_SHAREAWARE flag.

If the user selects the read-only check box, the dialog box sets the OFN_READONLY flag on return. To hide the Open As Read Only check box, set the OFN_HIDEREADONLY flag. To prevent the dialog box from returning names of existing files that have the read-only attribute, set the OFN_NOREADONLYRETURN flag.

To prevent the dialog box from dereferencing link files, set the OFN_NODEREFERENCELINKS value. In this case, the dialog box returns the name of the link file rather than the name of the file referenced by the link file.


Open and Save As Dialog Box Customization

You can customize an Open or Save As dialog box by providing a hook procedure, a custom template, or both. However, the Explorer-style and old-style versions of the dialog boxes differ in their use of custom templates and hook procedures.

For information about customizing an Explorer-style dialog box, see Explorer-Style Hook Procedures, Explorer-Style Custom Templates, and Explorer-Style Control Identifiers. For information about customizing an old-style dialog box, see Customizing Old-Style Dialog Boxes.

The following table summarizes the differences between the two styles.

Customization | Description
Explorer-style Hook procedure | The hook procedure receives notification messages sent from the common dialog box and messages for any additional controls that you defined by specifying a child dialog template. The hook procedure does not receive messages for the standard controls of the default dialog box.
Explorer-style Custom template | The system uses the custom template to create a child dialog box. The template can define additional controls, and can specify the location of the cluster of standard controls. The custom template does not replace the default template.
Old-style Hook procedure | The hook procedure receives all messages sent to the dialog box, including messages for the standard controls and any custom controls. The hook procedure also receives registered messages sent from the common dialog box.
Old-style Custom template | The custom template replaces the default template. Create the custom template by modifying the default template specified in the FILEOPEN.DLG file.

The default title for both Explorer-style and old-style dialog boxes is either "Open" or "Save As." To change the title, specify the new title in the lpstrTitle member of the OPENFILENAME structure.


Explorer-Style Hook Procedures

You can customize an Explorer-style Open or Save As dialog box by providing a hook procedure, a custom template, or both. If you provide a hook procedure for an Explorer-style dialog box, the system creates a dialog box that is a child of the default dialog box. The hook procedure acts as the dialog procedure for the child dialog box. This child dialog box is based on the custom template, or on a default template if none is provided. For more information, see Explorer-Style Custom Templates.

To enable a hook procedure for an Explorer-style Open or Save As dialog box, use the OPENFILENAME structure when you create the dialog box. Set the OFN_ENABLEHOOK and OFN_EXPLORER flags in the Flags member and specify the address of an OFNHookProc hook procedure in the lpfnHook member. If you provide a hook procedure and omit the OFN_EXPLORER flag, you must use an OFNHookProcOldStyle hook procedure and you will get the old-style user-interface. For more information, see Customizing Old-Style Dialog Boxes.

An Explorer-style hook procedure receives a variety of messages while the dialog box is open. These include the following:

  • The WM_INITDIALOG message and other standard dialog box messages such as the WM_CTLCOLORDLG control color message.
  • A set of WM_NOTIFY notification messages indicating actions taken by the user or other dialog box events.
  • Messages for any additional controls that you defined by specifying a child dialog template.

In addition, there is a set of messages that you can send to an Explorer-style dialog box to get information or to control the behavior and appearance of the dialog box.

If you provide a hook procedure for an Explorer-style dialog box, the default dialog box procedure creates a child dialog box when the default dialog procedure is processing its WM_INITDIALOG message. The hook procedure acts as the dialog procedure for the child dialog box. At this time, the hook procedure receives its own WM_INITDIALOG message with the lParam parameter set to the address of the OPENFILENAME structure used to initialize the dialog box. After the child dialog finishes processing its own WM_INITDIALOG message, the default dialog procedure moves the standard controls, if necessary, to make room for any additional controls of the child dialog box. The default dialog procedure then sends the CDN_INITDONE notification message to the hook procedure.

The hook procedure receives WM_NOTIFY notification messages indicating actions taken by the user in the dialog box. You can use some of these messages to control the behavior of the dialog box. For example, the hook procedure receives the CDN_FILEOK message when the user chooses a filename and clicks the OK button. In response to this message, the hook procedure can use the SetWindowLong function to reject the selected name and force the dialog box to remain open.

The lParam parameter for each WM_NOTIFY message is a pointer to an OFNOTIFY structure that defines the action. The code member in the header for the OFNOTIFY structure contains one of the following notification codes.

CDN_FILEOK | The user clicked the OK button; the dialog box is about to close.
CDN_FOLDERCHANGE | The user opened a new folder or directory.
CDN_HELP | The user clicked the Help button.
CDN_INITDONE | The system has finished initializing the dialog box, and the dialog box has finished processing the WM_INITDIALOG message. Also, the system has finished arranging controls in the common dialog box to make room for the controls of the child dialog box (if any).
CDN_SELCHANGE | The user selected a new file or folder from the file list.
CDN_SHAREVIOLATION | The common dialog box encountered a sharing violation on the file about to be returned.
CDN_TYPECHANGE | The user selected a new file type from the list of file types.

These WM_NOTIFY messages supersede the FILEOKSTRING, LBSELCHSTRING, SHAREVISTRING, and HELPMSGSTRING registered messages used by previous versions of the Open and Save As dialog boxes. However, the hook procedure also receives the superseded message after the WM_NOTIFY message if the WM_NOTIFY processing does not use SetWindowLong to set a nonzero DWL_MSGRESULT value.

To retrieve information about the status of the dialog box or to control the behavior and appearance of the dialog box, the hook procedure can send the following messages to the dialog box.

CDM_GETFILEPATH | Retrieves the path and filename of the selected file.
CDM_GETFOLDERIDLIST | Retrieves the item identifier list corresponding to the current folder that the dialog box has open. For more information about item identifier lists, see Item Identifiers and Identifier Lists.
CDM_GETFOLDERPATH | Retrieves the path of the current folder or directory for the dialog box.
CDM_GETSPEC | Retrieves the filename (not including the path) of the file currently selected in the dialog box.
CDM_HIDECONTROL | Hides the specified control.
CDM_SETCONTROLTEXT | Sets the text in the specified control.
CDM_SETDEFEXT | Sets the default filename extension for the dialog box.


Explorer-Style Custom Templates

To define additional controls for an Explorer-style Open or Save As dialog box, use the OPENFILENAME structure to specify a template for a child dialog box that contains the additional controls. If your child dialog template is a resource in an application or dynamic-link library, set the OFN_ENABLETEMPLATE flag in the Flags member and use the hInstance and lpTemplateName members of the structure to identify the module and resource name. If the template is already in memory, set the OFN_ENABLETEMPLATEHANDLE flag and use the hInstance member to identify the memory object that contains the template. When providing a child dialog template for an Explorer-style dialog box, you must also set the OFN_EXPLORER flag; otherwise, the system assumes you are providing a replacement template for an old-style dialog box. Typically, if you provide additional controls, you must also provide an Explorer-style hook procedure to process messages for the new controls.

You can create your child dialog box template as you do any other template, except that you must specify the WS_CHILD and WS_CLIPSIBLINGS styles and should specify the DS_3DLOOK and DS_CONTROL styles. The system requires the WS_CHILD style because your template defines a child dialog of the default Open or Save As dialog box. The WS_CLIPSIBLINGS style ensures that the child dialog box does not paint over any of the controls in the default dialog box. The DS_3DLOOK style makes sure that the appearance of the controls in the child dialog box is consistent with the controls in the default dialog box. The DS_CONTROL style makes sure that the user can use the tab and other navigation keys to move between all controls, default or custom, in the customized dialog box.

To make room for the new controls, the system expands the default dialog box by the width and height of the custom dialog box. By default, all controls from the custom dialog box are positioned below the controls in the default dialog box. However, you can override this default positioning by including a static text control in your custom dialog box template and assigning it the control identifier value of stc32. (This value is defined in the DLG.H header file.) In this case, the system uses the control as the point of reference for determining where to position the new controls. All new controls above and to the left of the stc32 control are positioned the same amount above and to the left of the controls in the default dialog box. New controls below and to the right of the stc32 control are positioned below and to the right of the default controls. In general, each new control is positioned so that it has the same position relative to the default controls as it had to the stc32 control. To make room for these new controls, the system adds space to the left, right, bottom, and top of the default dialog box as needed.

The system requires the hook procedure to process all messages intended for the custom dialog box and therefore sends the same window messages to the hook procedure as to any other dialog box procedure. For example, the hook procedure receives WM_COMMAND messages when the user clicks on button controls in the custom dialog box. The hook procedure is responsible for initializing these controls and retrieving values from the controls when the dialog box is closed. Note that when the hook procedure receives the WM_INITDIALOG message, the system has not yet moved the controls to their final positions.

The default dialog box procedure handles messages for all the controls in the default dialog box, but the hook procedure receives the WM_NOTIFY notification messages for user actions on these controls as described in Explorer-Style Hook Procedures.


Explorer-Style Control Identifiers

The Platform SDK provides the default dialog box template for the old-style dialog boxes, but does not include the default template for the Explorer-style dialog boxes. This is because the Explorer-style dialogs allow you to add your own controls but do not support modifying the template for the standard controls. However, in some cases, you may need to know the control identifiers used in the default templates. For example, the CDM_HIDECONTROL and CDM_SETCONTROLTEXT messages require a control identifier.

The following table shows the identifiers of the standard controls in the Explorer-style Open and Save As dialog boxes. The identifiers are constants defined in DLGS.H and WINUSER.H.

Control identifier | Control Description
cmb2 | Drop-down combo box that displays the current drive or folder, and that allows the user to select a drive or folder to open
stc4 | Label for the cmb2 combo box
lst1 | List box that displays the contents of the current drive or folder
stc1 | Label for the lst1 list box
edt1 | Edit control that displays the name of the current file, or in which the user can type the name of the file to open
stc3 | Label for the edt1 edit control
cmb1 | Drop-down combo box that displays the list of file type filters
stc2 | Label for the cmb1 combo box
chx1 | The read-only check box
IDOK | The OK command button (push button)
IDCANCEL | The Cancel command button (push button)
pshHelp | The Help command button (push button)


Customizing Old-Style Dialog Boxes

You can customize an old-style Open or Save As dialog box by providing an OFNHookProcOldStyle hook procedure that receives messages or notifications intended for the default dialog box procedure. You can also provide a custom template to use in place of the default template. The hook procedures and templates used with the old-style dialog boxes are similar to those used with the other common dialog boxes. For more information, see Hook Procedures for Common Dialog Boxes and Custom Templates.

To enable a hook procedure for an old-style Open or Save As dialog box, use the OPENFILENAME structure when you create the dialog box. Set the OFN_ENABLEHOOK flag in the Flags member and specify the address of an OFNHookProcOldStyle hook procedure in the lpfnHook member. The dialog box procedure sends a WM_INITDIALOG message to the hook procedure with the lParam parameter set to the address of the OPENFILENAME structure used to initialize the dialog box.

You can use the OPENFILENAME structure to specify a custom template for the Open or Save As dialog box to use in place of the default template. If your custom template is a resource in an application or dynamic-link library, set the OFN_ENABLETEMPLATE flag in the Flags member and use the hInstance and lpTemplateName members of the structure to identify the module and resource name. If your custom template is already in memory, set the OFN_ENABLETEMPLATEHANDLE flag and use the hInstance member to identify the memory object that contains the template. Create the custom template by modifying the default template specified in the FILEOPEN.DLG file. The control identifiers used in the default Find and Replace dialog templates are defined in the DLGS.H file.

By default, the GetOpenFileName and GetSaveFileName functions display the Explorer-style dialog boxes. If you want to display an old-style dialog box, you must provide an OFNHookProcOldStyle hook procedure and ensure that the OFN_EXPLORER flag is not set in the Flags member of the OPENFILENAME structure.

If you set the OFN_EXPLORER flag, the system treats a hook procedure or custom template as an Explorer-style customization. For information about customizing an Explorer-style dialog box, see Explorer-Style Custom Templates.


Print Dialog Box

The Print dialog box lets the user select options for a particular print job. For example, the user can specify the printer to use, the range of pages to print, and the number of copies.

Windows NT 5.0 and later: You can use the PrintDlgEx function to display a Print property sheet, which has a General page containing controls similar to the Print dialog box. The property sheet can also have additional application-specific and driver-specific property pages following the General page.

You create and display a Print dialog box by initializing a PRINTDLG structure and passing the structure to the PrintDlg function.

The following illustration shows a typical Print dialog box.

If the user clicks the OK button, PrintDlg returns TRUE and uses the PRINTDLG structure to return information about the user's selections. For example, the hDevMode and hDevNames members typically return global memory handles for DEVMODE and DEVNAMES structures. You can use the information in these structures to create a device context or an information context for the selected printer.

If the user cancels the Print dialog box or an error occurs, PrintDlg returns FALSE. You can determine the cause of an error by using the CommDlgExtendedError function to retrieve the extended error value.

The Print dialog box includes a Print Range group of radio buttons that indicate whether the user wants to print all pages, a range of pages, or only the selected text. Before calling PrintDlg, you can set one of the PD_ALLPAGES, PD_SELECTION, or PD_PAGENUMS flags to indicate which button is initially selected. When PrintDlg returns TRUE, the function sets one of these flags to indicate the user's selections. If PD_PAGENUMS is set, the nFromPage and nToPage members of the PRINTDLG structure contain the starting and ending pages specified by the user. To disable the Pages radio button and its associated From and To edit controls, set the PD_NOPAGENUMS flag. To disable the Selection radio button, set the PD_NOSELECTION flag.

The dialog box includes an edit control in which the user can type the number of copies to print. If the hDevMode member of the PRINTDLG structure is non-NULL, the dmCopies member of the DEVMODE structure specifies the initial value for this edit control. If hDevMode is NULL, the nCopies member of the PRINTDLG structure specifies the initial value. When PrintDlg returns, nCopies typically indicates the number of copies specified by the user. However, if you set the PD_USEDEVMODECOPIESANDCOLLATE flag when you create the dialog box, nCopies is always set to 1 on return and the dmCopies member of DEVMODE indicates the number of copies to print.

The Collate check box indicates whether the user wants to collate the pages if multiple copies are being printed. The PD_COLLATE flag is set if the Collate check box is checked. If your application does not support multiple copies or simulated collation, set the PD_USEDEVMODECOPIESANDCOLLATE flag in the Flags member of the PRINTDLG structure. This disables the Collate check box and the Number of Copies edit control unless the printer driver supports multiple copies and collation.

The Print To File check box indicates whether the user wants to send output to a file rather than to a printer. You can set the PD_PRINTTOFILE flag so the check box is initially checked. To hide the check box, set the PD_HIDEPRINTTOFILE flag. To disable it, set the PD_DISABLEPRINTTOFILE flag. If the user selects the Print To File option, PrintDlg sets the PD_PRINTTOFILE flag and returns "FILE:" at the offset indicated by the wOutputOffset member of the DEVNAMES structure. When you call the StartDoc function to start the printing operation, specify this "FILE:" string in the lpszOutput member of the DOCINFO structure. Specifying this string causes the print subsystem to query the user for the name of the output file.

By default, the Print dialog box initially displays information about the current default printer. You can direct it to display information for another installed printer by initializing a DEVMODE or DEVNAMES structure and assigning the global memory handle for the structure to the hDevMode or hDevNames member. The device name you specify in the dmDeviceName member of the DEVMODE structure or in the wDriverOffset member of the DEVNAMES structure must identify a printer device that is also listed in the [Devices] section of the WIN.INI file. If the device is not listed, PrintDlg returns an error.

You can direct PrintDlg to create a device context or information context for the printer by setting the PD_RETURNDC or PD_RETURNIC flag in the Flags member of the PRINTDLG structure. The function returns the handle of the device context or information context in the hDC member. If you use the PD_RETURNDC flag, you can use the device context to generate output for the printer.

To retrieve information about the default printer without displaying the Print dialog box, set the PD_RETURNDEFAULT flag. In this case, PrintDlg returns immediately after setting the hDevMode and hDevNames members to handles for structures containing the information.

By default, PrintDlg displays message boxes when errors occur. For example, the function displays an error message if no printers are installed. To prevent the function from displaying these warning messages, set the PD_NOWARNING flag.


Customizing the Print Dialog Box

You can provide a custom template for the Print dialog box, for example, if you want to include additional controls that are unique to your application. The PrintDlg function uses your custom template in place of the default template.

To provide a custom template for the Print dialog box
  1. Create the custom template by modifying the default template specified in the PRNSETUP.DLG file. The control identifiers used in the default Print dialog template are defined in the DLGS.H file.
  2. Use the PRINTDLG structure to enable the template as follows:
    • If your custom template is a resource in an application or dynamic-link library, set the PD_ENABLEPRINTTEMPLATE flag in the Flags member. Use the hInstance and lpPrintTemplateName members of the structure to identify the module and resource name.

      -Or-

    • If your custom template is already in memory, set the PD_ENABLEPRINTTEMPLATEHANDLE flag. Use the hPrintTemplate member to identify the memory object that contains the template.

You can provide a PrintHookProc hook procedure for the Print dialog box. The hook procedure can process messages sent to the dialog box. It can also send messages to the dialog box. If you use a custom template to define additional controls, you must provide a hook procedure to process input for your controls.

To enable a hook procedure for the Print dialog box
  1. Set the PD_ENABLEPRINTHOOK flag in the Flags member of the PRINTDLG structure.
  2. Specify the address of the hook procedure in the lpfnPrintHook member.

After processing its WM_INITDIALOG message, the dialog box procedure sends a WM_INITDIALOG message to the hook procedure. The lParam parameter of this message is a pointer to the PRINTDLG structure used to initialize the dialog box.


Print Setup Dialog Box

You can create and display a Print Setup dialog box by setting the PD_PRINTSETUP flag in a call to the PrintDlg function. However, the Print Setup dialog box has been superseded by the Page Setup dialog box and should not be used in new applications.

The following flags apply only to the Print Setup dialog box:

  • PD_ENABLESETUPHOOK
  • PD_ENABLESETUPTEMPLATE
  • PD_ENABLESETUPTEMPLATEHANDLE


Print Property Sheet

[This is preliminary documentation and subject to change.]

The Print property sheet is a standard user interface that enables the user to specify the properties of a particular print job. The PrintDlgEx function that creates the property sheet is available on Windows NT version 5.0 and later. The first page of a Print property sheet is the General page. The property sheet can also have additional application-specific and driver-specific property pages following the General page. The lower portion of the General page is a child dialog box template with controls similar to those of the Print common dialog box.

To create and display a Print property sheet, initialize a PRINTDLGEX structure and pass the structure to the PrintDlgEx function.

Most members of the PRINTDLGEX structure are identical to those of the PRINTDLG structure. For descriptions of how to use the common structure members to interact with the dialog box controls, see Print Dialog Box. The remainder of this topic describes the Print property sheet features that differ from the Print dialog box.

You can customize a Print property sheet by specifying a custom dialog box template for the lower portion of the General page and by specifying additional property pages to follow the General page. For more information, see Customizing the Print Property Sheet.

You can implement a callback object to receive notifications and messages from the PrintDlgEx function while the property sheet is displayed. Applications that provide custom templates or additional pages use the callback object to communicate with the property sheet. For more information, see Callback Object for the Print Property Sheet.

The Print property sheet provides support for specifying multiple, noncontiguous page ranges to print. The lpPageRanges member of the PRINTDLGEX structure specifies an array of PRINTPAGERANGE structures in which each structure specifies a page range.

The Print property sheet displays a Current Page radio button as part of the Page Range group of radio buttons. To control the Current Page radio button, use the PD_CURRENTPAGE and PD_NOCURRENTPAGE flags in the Flags member of the PRINTDLGEX structure.


Customizing the Print Property Sheet

[This is preliminary documentation and subject to change.]

You can customize the Print property sheet in the following ways:

  • Provide a custom template for the lower portion of the General page. This allows you to include additional controls that are unique to your application. The PrintDlgEx function uses your custom template in place of the default template.
  • Provide additional property pages to follow the General page.
  • Provide a callback object. For more information, see Callback Object for the Print Property Sheet.

You cannot change the upper portion of the General page. You cannot change property pages provided by the printer driver.

To provide a custom template for the General page
  1. Create a custom template for the lower portion of the General page by modifying the PRINTDLGEXORD template specified in the PRNSETUP.DLG file. The custom template must be the same size as the default template. The control identifiers used in the default Print dialog template are defined in the DLGS.H file.
  2. Use the PRINTDLGEX structure to enable the template as follows:
    • If your custom template is a resource in an application or dynamic-link library, set the PD_ENABLEPRINTTEMPLATE flag in the Flags member. Use the hInstance and lpPrintTemplateName members of the structure to identify the module and resource name.

      -Or-

    • If your custom template is already in memory, set the PD_ENABLEPRINTTEMPLATEHANDLE flag. Use the hInstance member to identify the memory object that contains the template.
  3. If you use a custom template to define additional controls, you must provide a callback object to process input for your controls. The callback object implements a IPrintDialogCallback::HandleMessage method which receives messages sent to the custom dialog box.
To provide additional property pages
  1. Use the CreatePropertySheetPage function to create the additional pages.
  2. Use the lphPropertyPages member of the PRINTDLGEX structure to specify an array of handles to the additional pages.

    The dialog box procedures specified when you created each page process messages sent to the pages.

  3. You might want to provide a callback object that implements the IObjectWithSite interface. The PrintDlgEx function uses this interface to pass to the application a pointer to an IPrintDialogServices interface. The dialog box procedures for the additional property pages can use this interface to retrieve information about the currently selected printer.


Callback Object for the Print Property Sheet

[This is preliminary documentation and subject to change.]

An application that displays a Print property sheet can implement a callback object to receive notifications and messages from the PrintDlgEx function while the property sheet is displayed. To provide a callback object, specify a pointer to the object in the lpCallback member of the PRINTDLGEX structure.

The callback object must implement the IPrintDialogCallback interface. The PrintDlgEx function calls IPrintDialogCallback methods in the following situations:

  • When the dialog box has been initialized.
  • When the user selects a different printer from the list of installed printers displayed by the property sheet.
  • When it receives messages for the child dialog box in the lower portion of the property sheet's General page.

The callback object should also implement the IObjectWithSite interface. The PrintDlgEx function calls the IObjectWithSite::SetSite method to pass a pointer to an IPrintDialogServices interface to an application. The IPrintDialogCallback methods can use the IPrintDialogServices interface to retrieve information about the currently selected printer. The IPrintDialogServices interface is also useful for applications that create additional pages to follow the General page of the Print property sheet. The dialog box procedures for the additional pages can call IPrintDialogServices methods.


Page Setup Dialog Box

The Page Setup dialog box lets the user set the following attributes of the printed page:

  • The paper type (envelope, legal, letter, and so on)
  • The paper source (manual feed, tractor feed, sheet feeder, and so on)
  • The page orientation (portrait or landscape)
  • The width of the page margins

The attributes presented in the dialog box vary, depending on the capabilities of the printer.

You create and display a Page Setup dialog box by initializing a PAGESETUPDLG structure and passing the structure to the PageSetupDlg function.

The following illustration shows a typical Page Setup dialog box.

If the user clicks the OK button, PageSetupDlg returns TRUE after setting various members in the PAGESETUPDLG structure to specify the user's selections. The ptPaperSize and rtMargin members contain the values specified by the user. The hDevMode and hDevNames members contain global memory handles for the DEVMODE and DEVNAMES structures. These structures contain additional page information as well as information about the printer. You can use this information to prepare the output to be sent to the selected printer.

If the user cancels the Page Setup dialog box or an error occurs, PageSetupDlg returns FALSE. To determine the cause of the error, call the CommDlgExtendedError function to retrieve the extended error value.


Initializing the Page Setup Dialog Box

By default, the Page Setup dialog box displays information about the current default printer. To direct the dialog box to display information about a specific printer, set the members of a DEVMODE or DEVNAMES structure and assign the global memory handles of these structures to the corresponding member in PAGESETUPDLG. If you specify the name of a printer that is not currently installed, the dialog box displays an error message. To prevent the dialog box from displaying error messages, use the PSD_NOWARNING value. To retrieve information about the default printer without displaying the Page Setup dialog box, use the PSD_RETURNDEFAULT value.

If the default measurement system is inches, the dialog box uses thousandths of inches as the default unit of measurement. If the default measurement system is metric, the dialog box uses hundredths of millimeters as the default unit of measurement. To override the default unit of measurement, set the PSD_INHUNDREDTHSOFMILLIMETERS or PSD_INTHOUSANDTHSOFINCHES flag in the Flags member of the PAGESETUPDLG structure.

The initial values for the margins are one inch, by default. If you set the PSD_MARGINS flag, the dialog box displays the initial margin values specified in the rtMargin member. The default minimum values that the user can specify for the margins are the minimum margins allowed by the printer. If you set the PSD_MINMARGINS flag, the dialog box enforces the minimum margins specified in the rtMinMargin member.

To prevent users from selecting certain options, set any combination of the following flags to disable the corresponding controls.

Flag | Meaning
PSD_DISABLEMARGINS | Disables the edit controls in which the user types the margins.
PSD_DISABLEORIENTATION | Disables the Portrait and Landscape radio buttons.
PSD_DISABLEPAPER | Disables the controls for selecting the paper size and paper source.
PSD_DISABLEPRINTER | Disables the Printer push button.


Customizing the Page Setup Dialog Box

You can provide a custom template for the Page Setup dialog box, for example, if you want to include additional controls that are unique to your application. The PageSetupDlg function uses your custom template in place of the default template.

To provide a custom template for the Page Setup dialog box
  1. Create the custom template by modifying the default template specified in the PRNSETUP.DLG file. The control identifiers used in the default Page Setup dialog template are defined in the DLGS.H file.
  2. Use the PAGESETUPDLG structure to enable the template as follows:
    • If your custom template is a resource in an application or dynamic-link library, set the PSD_ENABLEPAGESETUPTEMPLATE flag in the Flags member. Use the hInstance and lpPageSetupTemplateName members of the structure to identify the module and resource name.

      -Or-

    • If your custom template is already in memory, set the PSD_ENABLEPAGESETUPTEMPLATEHANDLE flag. Use the hPageSetupTemplate member to identify the memory object that contains the template.

To filter messages sent to the dialog box procedure, you can provide a PageSetupHook hook procedure. If you use a custom template to define additional controls, you must provide a PageSetupHook hook procedure to process input for your controls. In addition, you can provide a PagePaintHook hook procedure to customize the contents of the sample page displayed by the Page Setup dialog box. For more information about the PagePaintHook hook procedure, see Customizing the Sample Page.

To enable a PageSetupHook hook procedure
  1. Set the PSD_ENABLEPAGESETUPHOOK flag in the Flags member of the PAGESETUPDLG structure.
  2. Specify the address of the hook procedure in the lpfnPageSetupHook member.

After processing its WM_INITDIALOG message, the dialog box procedure sends a WM_INITDIALOG message to the PageSetupHook hook procedure. The lParam parameter of this message is a pointer to the PAGESETUPDLG structure used to initialize the dialog box.


Customizing the Sample Page

The Page Setup dialog box includes an image of a sample page that shows how the user's selections affect the appearance of the printed output. The image consists of a rectangle that represents the selected paper or envelope type, with a dotted-line rectangle representing the current margins, and partial (greek text) characters to show how text looks on the printed page.

When you call the PageSetupDlg function, you can provide a PagePaintHook hook procedure to customize the appearance of the sample page.

To enable a PagePaintHook hook procedure
  1. Set the PSD_ENABLEPAGEPAINTHOOK flag in the Flags member of the PAGESETUPDLG structure.
  2. Specify the address of the hook procedure in the lpfnPagePaintHook member.

Whenever the dialog box is about to draw the contents of the sample page, the hook procedure receives the following messages in the order in which they are listed.

Message | Meaning
WM_PSD_PAGESETUPDLG | The dialog box is about to draw the sample page. The hook procedure can use this message to prepare to draw the contents of the sample page.
WM_PSD_FULLPAGERECT | The dialog box is about to draw the sample page. This message specifies the bounding rectangle of the sample page.
WM_PSD_MINMARGINRECT | The dialog box is about to draw the sample page. This message specifies the margin rectangle.
WM_PSD_MARGINRECT | The dialog box is about to draw the margin rectangle.
WM_PSD_GREEKTEXTRECT | The dialog box is about to draw the Greek text inside the margin rectangle.
WM_PSD_ENVSTAMPRECT | The dialog box is about to draw in the envelope-stamp rectangle of an envelope sample page. This message is sent for envelopes only.
WM_PSD_YAFULLPAGERECT | The dialog box is about to draw the return address portion of an envelope sample page. This message is sent for envelopes and other paper sizes.

If the hook procedure returns TRUE for any of the first three messages of a drawing sequence (WM_PSD_PAGESETUPDLG, WM_PSD_FULLPAGERECT, or WM_PSD_MINMARGINRECT) the dialog box sends no more messages and does not draw in the sample page until the next time the system needs to redraw the sample page. If the hook procedure returns FALSE for all three messages, the dialog box sends the remaining messages of the drawing sequence.

If the hook procedure returns TRUE for any of the remaining messages in a drawing sequence, the dialog box does not draw the corresponding portion of the sample page. If the hook procedure returns FALSE for any of these messages, the dialog box draws that portion of the sample page.

To prevent the dialog box from drawing the contents of the sample page, you can set the PSD_DISABLEPAGEPAINTING flag. This flag does not affect your PagePaintHook hook procedure, which still receives all the WM_PSD_* messages and can draw the sample page contents.


Find and Replace Dialog Boxes

The Find dialog box lets the user specify a string to search for, as well as options to use when searching for text in a document. The Replace dialog box lets the user specify a string to search for and a replacement string, as well as options to control the operation.

You create and display a Find dialog box by initializing a FINDREPLACE structure and passing the structure to the FindText function. You create and display a Replace dialog box by initializing a FINDREPLACE structure and passing the structure to the ReplaceText function.

The following illustration shows a typical Find dialog box.

The following illustration shows a typical Replace dialog box.

Unlike other common dialog boxes, the Find and Replace dialog boxes are modeless. A modeless dialog box allows the user to switch between the dialog box and the window that created it. This is useful for letting the user search for a string, switch to the application window to work on the string, and switch back to the dialog box to search for another string without repeating the command needed to open the dialog box.

If the FindText or ReplaceText function successfully creates the dialog box, it returns the handle of the dialog box. You can use this handle to move and communicate with the dialog box. If the function cannot create the dialog box, it returns NULL. You can determine the cause of an error by calling the CommDlgExtendedError function to retrieve the extended error value.


The FINDMSGSTRING Registered Message

Before creating a Find or Replace dialog box, you must call the RegisterWindowMessage function to get a message identifier for the FINDMSGSTRING registered message. You can then use the identifier to detect and process messages sent from the dialog box. When the user clicks the Find Next, Replace, or Replace All button in a dialog box, the dialog box procedure sends a FINDMSGSTRING message to the window procedure of the owner window. When you create the dialog box, the hwndOwner member of the FINDREPLACE structure identifies the owner window.

The lParam parameter of a FINDMSGSTRING message is a pointer to the FINDREPLACE structure that you specified when you created the dialog box. Before sending the message, the dialog box sets the members of this structure with the latest user input, including the string to search for, the replacement string (if any), and options for the find-and-replace operation.

In a FINDMSGSTRING message, the Flags member of the FINDREPLACE structure includes one of the following flags to indicate the event that caused the message.

Flag | Meaning
FR_DIALOGTERM | The dialog box is closing. After the owner window processes this message, the handle of the dialog box is no longer valid.
FR_FINDNEXT | The user clicked the Find Next button in a Find or Replace dialog box. The lpstrFindWhat member specifies the string to search for.
FR_REPLACE | The user clicked the Replace button in a Replace dialog box. The lpstrFindWhat member specifies the string to replace and the lpstrReplaceWith member specifies the replacement string.
FR_REPLACEALL | The user clicked the Replace All button in a Replace dialog box. The lpstrFindWhat member specifies the string to replace and the lpstrReplaceWith member specifies the replacement string.

For a Find Next or Replace All message, the Flags member can include any combination of the following flags to indicate the search options.

Flag | Meaning
FR_DOWN | If set, the Down button of the direction radio buttons is selected, indicating that user wants to search from the current location to the end of the document. If FR_DOWN is not set, the Up button is selected so the user wants to search to the beginning of the document.
FR_MATCHCASE | If set, the Match Case check box is checked, indicating that the user wants the search to be case sensitive. If FR_MATCHCASE is not set, the check box is unchecked so the search should be case insensitive.
FR_WHOLEWORD | If set, the Match Whole Word Only check box is checked, indicating that the user wants to search only for whole words that match the search string. If FR_WHOLEWORD is not set, the check box is unchecked so you should also search for word fragments that match the search string.


Customizing the Find or Replace Dialog Box

To customize a Find or Replace dialog box, you can use any of the following methods:

  • Specify values in the FINDREPLACE structure when you create the dialog box
  • Provide a custom template
  • Provide a hook procedure

When you create a Find or Replace dialog box, you can set flags in the Flags member of the FINDREPLACE structure to hide or disable any of the search option controls. For example, you can set the FR_NOMATCHCASE flag to disable the Match Case check box or set the FR_HIDEMATCHCASE flag to hide it.

You can provide a custom template for a Find or Replace dialog box, for example, if you want to include additional controls that are unique to your application. The FindText and ReplaceText functions use your custom template in place of the default template.

To provide a custom template for a Find or Replace dialog box
  1. Create the custom template by modifying the default template specified in the FINDTEXT.DLG file. The control identifiers used in the default Find or Replace dialog template are defined in the DLGS.H file.
  2. Use the FINDREPLACE structure to enable the template as follows:
    • If your custom template is a resource in an application or dynamic-link library, set the FR_ENABLETEMPLATE flag in the Flags member. Use the hInstance and lpTemplateName members of the structure to identify the module and resource name.

      -Or-

    • If your custom template is already in memory, set the FR_ENABLETEMPLATEHANDLE flag. Use the hInstance member to identify the memory object that contains the template.

You can provide an FRHookProc hook procedure for a Find or Replace dialog box. The hook procedure can process messages sent to the dialog box. If you use a custom template to define additional controls, you must provide a hook procedure to process input for your controls.

To enable a hook procedure for a Find or Replace dialog box
  1. Set the FR_ENABLEHOOK flag in the Flags member of the FINDREPLACE structure.
  2. Specify the address of the hook procedure in the lpfnHook member.

After processing its WM_INITDIALOG message, the dialog box procedure sends a WM_INITDIALOG message to the hook procedure. The lParam parameter of this message is a pointer to the FINDREPLACE structure used to initialize the dialog box.

If the hook procedure returns FALSE in response to the WM_INITDIALOG message, the dialog box will not be shown unless the hook procedure displays it. To do this, first perform any other paint operations, and then call the ShowWindow and UpdateWindow functions. The following code provides an example:

// We've returned FALSE in response to WM_INITDIALOG.
// We've performed any other paint operations.
// Now we display the dialog box.
ShowWindow(hDlg, SW_SHOWNORMAL);
UpdateWindow(hDlg);


Using Common Dialog Boxes

  • Choosing a color
  • Choosing a font
  • Opening a file
  • Displaying the Print dialog box
  • Using the Print Property Sheet
  • Setting up the printed page
  • Finding text


Choosing a Color

This topic describes sample code that displays a Color dialog box so a user can select a color. The sample code first initializes a CHOOSECOLOR structure, and then calls the ChooseColor function to display the dialog box. If the function returns TRUE, indicating that the user selected a color, the sample code uses the selected color to create a new solid brush.

This example uses the CHOOSECOLOR structure to initialize the dialog box as follows:

  • Initializes the lpCustColors member with a pointer to a static COLORREF array. The colors in the array are initially black, but the static array preserves custom colors created by the user for subsequent ChooseColor calls.
  • Sets the CC_RGBINIT flag and initializes the rgbResult member to specify the color that is initially selected when the dialog box opens. If not specified, the initial selection is black. The example uses the rgbCurrent static variable to preserve the selected value between calls to ChooseColor.
  • Sets the CC_FULLOPEN flag so the custom colors extension of the dialog box is always displayed.
CHOOSECOLOR cc;                 // common dialog box structure
static COLORREF acrCustClr[16]; // array of custom colors
HWND hwnd;                      // owner window
HBRUSH hbrush;                  // brush handle
static DWORD rgbCurrent;        // initial color selection

// Initialize CHOOSECOLOR
ZeroMemory(&cc, sizeof(CHOOSECOLOR));
cc.lStructSize = sizeof(CHOOSECOLOR);
cc.hwndOwner = hwnd;
cc.lpCustColors = (LPDWORD) acrCustClr;
cc.rgbResult = rgbCurrent;
cc.Flags = CC_FULLOPEN | CC_RGBINIT;

if (ChooseColor(&cc)==TRUE) {
    hbrush = CreateSolidBrush(cc.rgbResult);
    rgbCurrent = cc.rgbResult;
}


Choosing a Font

This topic describes sample code that displays a Font dialog box so a user can choose the attributes of a font. The sample code first initializes a CHOOSEFONT structure, and then calls the ChooseFont function to display the dialog box.

This example sets the CF_SCREENFONTS flag to specify that the dialog box should display only screen fonts. It sets the CF_EFFECTS flag to display controls that allow the user to select strikeout, underline, and color options.

If ChooseFont returns TRUE, indicating that the user clicked the OK button, the LOGFONT structure pointed to by the lpLogFont member of the CHOOSEFONT structure contains information that describes the font and font attributes selected by the user. The rgbColors member contains the selected text color. The sample code uses this information to set the font and text color for the device context associated with the owner window.

HWND hwnd;                // owner window
HDC hdc;                  // display device context of owner window

CHOOSEFONT cf;            // common dialog box structure
static LOGFONT lf;        // logical font structure
static DWORD rgbCurrent;   // current text color
HFONT hfont, hfontPrev;
DWORD rgbPrev;

// Initialize CHOOSEFONT
ZeroMemory(&cf, sizeof(CHOOSEFONT));
cf.lStructSize = sizeof (CHOOSEFONT);
cf.hwndOwner = hwnd;
cf.lpLogFont = &lf;
cf.rgbColors = rgbCurrent;
cf.Flags = CF_SCREENFONTS | CF_EFFECTS;

if (ChooseFont(&cf)==TRUE) {
    hfont = CreateFontIndirect(cf.lpLogFont);
    hfontPrev = SelectObject(hdc, hfont);
    rgbCurrent= cf.rgbColors;
    rgbPrev = SetTextColor(hdc, rgbCurrent);
 .
 .
 .
}


Opening a File

This topic describes sample code that displays an Open dialog box so a user can specify the drive, directory, and name of a file to open. The sample code first initializes an OPENFILENAME structure, and then calls the GetOpenFileName function to display the dialog box.

In this example, the lpstrFilter member points to a buffer that specifies two filename filters that the user can select to limit the filenames that are displayed. The buffer contains a double-null terminated array of strings in which each pair of strings specifies a filter. The nFilterIndex member specifies that the first pattern is used when the dialog box is created.

This example sets the OFN_PATHMUSTEXIST and OFN_FILEMUSTEXIST flags in the Flags member. These flags cause the dialog box to verify, before returning, that the path and filename specified by the user actually exist.

The GetOpenFileName function returns TRUE if the user clicks the OK button and the specified path and filename exist. In this case, the buffer pointed to by the lpstrFile member contains the path and filename. The sample code uses this information in a call to the CreateFile function to open the file.

Although this example does not set the OFN_EXPLORER flag, it still displays the default Explorer-style Open dialog box. However, if you want to provide a hook procedure or a custom template and you want the Explorer user interface, you must set the OFN_EXPLORER flag.

OPENFILENAME ofn;       // common dialog box structure
char szFile[260];       // buffer for filename
HWND hwnd;              // owner window
HANDLE hf;              // file handle

// Initialize OPENFILENAME
ZeroMemory(&ofn, sizeof(OPENFILENAME));
ofn.lStructSize = sizeof(OPENFILENAME);
ofn.hwndOwner = hwnd;
ofn.lpstrFile = szFile;
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = "All\0*.*\0Text\0*.TXT\0";
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;

// Display the Open dialog box.

if (GetOpenFileName(&ofn)==TRUE)
    hf = CreateFile(ofn.lpstrFile, GENERIC_READ,
        0, (LPSECURITY_ATTRIBUTES) NULL,
        OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
        (HANDLE) NULL);


Displaying the Print Dialog Box

This topic describes sample code that displays a Print dialog box so a user can select options for printing a document. The sample code first initializes a PRINTDLG structure, and then calls the PrintDlg function to display the dialog box.

This example sets the PD_RETURNDC flag in the Flags member of the PRINTDLG structure. This causes PrintDlg to return a device context handle for the selected printer in the hDC member. You can use the handle to render output on the printer.

On input, the sample code sets the hDevMode and hDevNames members to NULL. If the function returns TRUE, these members return handles to DEVMODE and DEVNAMES structures containing the user's input and information about the printer. You can use this information to prepare the output to be sent to the selected printer.

PRINTDLG pd;
HWND hwnd;

// Initialize PRINTDLG
ZeroMemory(&pd, sizeof(PRINTDLG));
pd.lStructSize = sizeof(PRINTDLG);
pd.hwndOwner   = hwnd;
pd.hDevMode    = NULL;      // Don't forget to free or store hDevMode.
pd.hDevNames   = NULL;      // Don't forget to free or store hDevNames.
pd.Flags       = PD_USEDEVMODECOPIESANDCOLLATE | PD_RETURNDC;
pd.nCopies     = 1;
pd.nFromPage   = 0xFFFF;
pd.nToPage     = 0xFFFF;
pd.nMinPage    = 1;
pd.nMaxPage    = 0xFFFF;

if (PrintDlg(&pd)==TRUE) {

    // GDI calls to render output.

    // Delete DC when done.
    DeleteDC(pd.hDC);
}


Using the Print Property Sheet

[This is preliminary documentation and subject to change.]

This topic describes sample code that displays a Print property sheet so a user can select options for printing a document. The sample code first allocates and initializes a PRINTDLGEX structure, then calls the PrintDlgEx function to display the property sheet.

The sample code sets the PD_RETURNDC flag in the Flags member of the PRINTDLG structure. This causes the PrintDlgEx function to return a device context handle for the selected printer in the hDC member. You can use the handle in functions such as DrawText that render output sent to the printer.

On input, the sample code sets the hDevMode and hDevNames members to NULL. If the function returns S_OK, these members return handles to DEVMODE and DEVNAMES structures containing the user's input and information about the printer. You can use this information to prepare the output to be sent to the selected printer.

After the printing operation has been completed, the sample code frees the DEVMODE and DEVNAMES buffers and calls the DeleteDC function to delete the device context.

HRESULT DisplayPrintPropertySheet(
    HWND hWnd  // Window that owns the property sheet
)
{
HRESULT hResult;
LPPRINTDLGEX pPDX = NULL;
LPPRINTPAGERANGE pPageRanges = NULL;

// Allocate the PRINTDLGEX structure.

pPDX = (LPPRINTDLGEX)GlobalAlloc(GPTR, sizeof(PRINTDLGEX));
if (!pPDX)
    return E_OUTOFMEMORY;

// Allocate an array of PRINTPAGERANGE structures.

pPageRanges = (LPPRINTPAGERANGE) GlobalAlloc(GPTR,
                   10 * sizeof(PRINTPAGERANGE));
if (!pPageRanges)
    return E_OUTOFMEMORY;

//  Initialize the PRINTDLGEX structure.

pPDX->lStructSize = sizeof(PRINTDLGEX);
pPDX->hwndOwner = hWnd;
pPDX->hDevMode = NULL;
pPDX->hDevNames = NULL;
pPDX->hDC = NULL;
pPDX->Flags = PD_RETURNDC | PD_COLLATE;
pPDX->Flags2 = 0;
pPDX->ExclusionFlags = 0;
pPDX->nPageRanges = 0;
pPDX->nMaxPageRanges = 10;
pPDX->lpPageRanges = pPageRanges;
pPDX->nMinPage = 1;
pPDX->nMaxPage = 1000;
pPDX->nCopies = 1;
pPDX->hInstance = 0;
pPDX->lpPrintTemplateName = NULL;
pPDX->lpCallback = NULL;
pPDX->nPropertyPages = 0;
pPDX->lphPropertyPages = NULL;
pPDX->nStartPage = START_PAGE_GENERAL;
pPDX->dwResultAction = 0;

//  Invoke the Print property sheet.

hResult = PrintDlgEx(pPDX);

if ( (hResult == S_OK) &&
           pPDX->dwResultAction == PD_RESULT_PRINT) {

    // User clicked the Print button, so
    // use the DC and other information returned in the
    // PRINTDLGEX structure to print the document

}

if (pPDX->hDC != NULL)
    DeleteDC(pPDX->hDC);
if (pPDX->hDevMode != NULL)
    GlobalFree(pPDX->hDevMode);
if (pPDX->hDevNames != NULL)
    GlobalFree(pPDX->hDevNames);

return hResult;
}


Setting Up the Printed Page

This topic describes sample code that displays a Page Setup dialog box so a user can select the attributes of the printed page, such as the paper type, paper source, page orientation, and page margins. The sample code first initializes a PAGESETUPDLG structure, and then calls the PageSetupDlg function to display the dialog box.

This example sets the PSD_MARGINS flag in the Flags member and uses the rtMargin member to specify the initial margin values. It sets the PSD_INTHOUSANDTHSOFINCHES flag to ensure that the dialog box expresses margin dimensions in thousandths of an inch.

On input, the sample code sets the hDevMode and hDevNames members to NULL. If the function returns TRUE, the function uses these members to return handles to DEVMODE and DEVNAMES structures containing the user's input and information about the printer. You can use this information to prepare the output to be sent to the selected printer.

The example also enables a PagePaintHook hook procedure to customize drawing of the contents of the sample page.

PAGESETUPDLG psd;    // common dialog box structure
HWND hwnd;           // owner window

// Initialize PAGESETUPDLG
ZeroMemory(&psd, sizeof(PAGESETUPDLG));
psd.lStructSize = sizeof(PAGESETUPDLG);
psd.hwndOwner   = hwnd;
psd.hDevMode    = NULL; // Don't forget to free or store hDevMode.
psd.hDevNames   = NULL; // Don't forget to free or store
                  hDevNames.
psd.Flags       = PSD_INTHOUSANDTHSOFINCHES | PSD_MARGINS |
                  PSD_ENABLEPAGEPAINTHOOK;
psd.rtMargin.top = 1000;
psd.rtMargin.left = 1250;
psd.rtMargin.right = 1250;
psd.rtMargin.bottom = 1000;
psd.lpfnPagePaintHook = PaintHook;

if (PageSetupDlg(&psd)==TRUE) {
    // check paper size and margin values here
}

The following example shows a sample PagePaintHook hook procedure that draws the margin rectangle in the sample page area:

BOOL CALLBACK PaintHook(HWND hwndDlg, UINT uMsg, WPARAM wParam,
    LPARAM lParam)
{
    LPRECT lprc;
    COLORREF crMargRect;
    HDC hdc, hdcOld;

    switch (uMsg) {

        // Drawing the margin rectangle.
        case WM_PSD_MARGINRECT:
            hdc = (HDC) wParam;
            lprc = (LPRECT) lParam;

            // Get the system highlight color.
            crMargRect = GetSysColor(COLOR_HIGHLIGHT);

            // Create a dash-dot pen of the system highlight color and
            // select it into the DC of the sample page.
            hdcOld = SelectObject(hdc, CreatePen(PS_DASHDOT, .5,
                crMargRect));

            // Draw the margin rectangle.
            Rectangle(hdc, lprc->left, lprc->top, lprc->right,
                lprc->bottom);

            // Restore the previous pen to the DC.
            SelectObject(hdc, hdcOld);
            return TRUE;

        default:
            return FALSE;
    }
    return TRUE;
}


Finding Text

This topic describes sample code that displays and manages a Find dialog box so the user can specify the parameters of a search operation. The dialog box sends messages to your window procedure so you can perform the search operation.

The code for displaying and managing a Replace dialog box is similar, except that it uses the ReplaceText function to display the dialog box. The Replace dialog box also sends messages in response to user clicks on the Replace and Replace All buttons.

To use the Find or Replace dialog box, you must perform three separate tasks:

  1. Get a message identifier for the FINDMSGSTRING registered message.
  2. Display the dialog box.
  3. Process FINDMSGSTRING messages when the dialog box is open.

When you initialize your application, call the RegisterWindowMessage function to get a message identifier for the FINDMSGSTRING registered message.

UINT uFindReplaceMsg;  // message identifier for FINDMSGSTRING

uFindReplaceMsg = RegisterWindowMessage(FINDMSGSTRING);

To display a Find dialog box, first initialize a FINDREPLACE structure and then call the FindText function. Note that the FINDREPLACE structure and the buffer for the search string should be a global or static variable so it does not go out of scope before the dialog box closes. You must set the hwndOwner member to specify the window that receives the registered messages. After you create the dialog box, you can move or manipulate it by using the returned handle.

FINDREPLACE fr;       // common dialog box structure
HWND hwnd;            // owner window
CHAR szFindWhat[80];  // buffer receiving string
HWND hdlg = NULL;     // handle of Find dialog box

// Initialize FINDREPLACE
ZeroMemory(&fr, sizeof(FINDREPLACE));
fr.lStructSize = sizeof(FINDREPLACE);
fr.hwndOwner = hwnd;
fr.lpstrFindWhat = szFindWhat;
fr.wFindWhatLen = 80;
fr.Flags = 0;

hdlg = FindText(&fr);

When the dialog box is open, your main message loop must include a call to the IsDialogMessage function. Pass the window handle of the dialog box as a parameter in the IsDialogMessage call. This ensures that the dialog box correctly processes keyboard messages.

To monitor messages sent from the dialog box, your window procedure must check for the FINDMSGSTRING registered message and process the values passed in the FINDREPLACE structure as in the following example:

LPFINDREPLACE lpfr;

if (message == uFindReplaceMsg){

    // Get pointer to FINDREPLACE structure from lParam.

    lpfr = (LPFINDREPLACE)lParam;

    // If the FR_DIALOGTERM flag is set,
    // invalidate the handle identifying the dialog box.

    if (lpfr->Flags & FR_DIALOGTERM){
        hdlg = NULL;
        return 0;
        }

    // If the FR_FINDNEXT flag is set,
    // call the application-defined search routine
    // to search for the requested string.

    if (lpfr->Flags & FR_FINDNEXT)
        SearchFile(lpfr->lpstrFindWhat,
                   (BOOL) (lpfr->Flags & FR_DOWN),
                   (BOOL) (lpfr->Flags & FR_MATCHCASE));

    return 0;

}


Common Dialog Box Reference

The following elements are used with common dialog boxes.

  • Common Dialog Box Functions
  • Common Dialog Box Structures
  • Common Dialog Box Messages
  • Common Dialog Box Interfaces


Common Dialog Box Functions

The following functions are used with common dialog boxes.

ChooseColor
ChooseFont
CommDlgExtendedError
FindText
GetFileTitle
GetOpenFileName
GetSaveFileName
PageSetupDlg
PrintDlg
PrintDlgEx
ReplaceText

The following application-defined hook procedures are used with common dialog boxes.

CCHookProc
CFHookProc
FRHookProc
OFNHookProc
OFNHookProcOldStyle
PagePaintHook
PageSetupHook
PrintHookProc
SetupHookProc


CCHookProc

The CCHookProc hook procedure is an application-defined or library-defined callback function that is used with the ChooseColor function. The hook procedure receives messages or notifications intended for the default dialog box procedure of the Color common dialog box.

The LPCCHOOKPROC type defines a pointer to this callback function. CCHookProc is a placeholder for the application-defined function name.

UINT CALLBACK CCHookProc(
  HWND hdlg,      // handle to the dialog box window
  UINT uiMsg,     // message identifier
  WPARAM wParam,  // message parameter
  LPARAM lParam   // message parameter
);

Parameters

hdlg
Handle to the Color dialog box window for which the message is intended.
uiMsg
Identifies the message being received.
wParam
Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.
lParam
Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.

If the uiMsg parameter indicates the WM_INITDIALOG message, lParam is a pointer to a CHOOSECOLOR structure containing the values specified when the dialog was created.

Return Values

If the hook procedure returns zero, the default dialog box procedure processes the message.

If the hook procedure returns a nonzero value, the default dialog box procedure ignores the message.

Remarks

When you use the ChooseColor function to create a Color dialog box, you can provide a CCHookProc hook procedure to process messages or notifications intended for the dialog box procedure. To enable the hook procedure, use the CHOOSECOLOR structure that you passed to the dialog creation function. Specify the address of the hook procedure in the lpfnHook member and specify the CC_ENABLEHOOK flag in the Flags member.

The default dialog box procedure processes the WM_INITDIALOG message before passing it to the hook procedure. For all other messages, the hook procedure receives the message first. Then, the return value of the hook procedure determines whether the default dialog procedure processes the message or ignores it.

If the hook procedure processes the WM_CTLCOLORDLG message, it must return a valid brush handle for painting the background of the dialog box. In general, if the hook procedure processes any WM_CTLCOLOR* message, it must return a valid brush handle for painting the background of the specified control.

Do not call the EndDialog function from the hook procedure. Instead, the hook procedure can call the PostMessage function to post a WM_COMMAND message with the IDABORT value to the dialog box procedure. Posting IDABORT closes the dialog box and causes the dialog box function to return FALSE. If you need to know why the hook procedure closed the dialog box, you must provide your own communication mechanism between the hook procedure and your application.

You can subclass the standard controls of the common dialog box. However, the common dialog box procedure may also subclass the controls. Because of this, you should subclass controls when your hook procedure processes the WM_INITDIALOG message. This ensures that your subclass procedure receives the control-specific messages before the subclass procedure set by the dialog box procedure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in commdlg.h.
Import Library: User-defined.

See Also

Common Dialog Box Library Overview, Common Dialog Box Functions, ChooseColor, CHOOSECOLOR, EndDialog, PostMessage, WM_INITDIALOG, WM_CTLCOLORDLG


CFHookProc

A CFHookProc hook procedure is an application-defined or library-defined callback procedure that is used with the ChooseFont function. The hook procedure receives messages or notifications intended for the default dialog box procedure of the Font common dialog box.

The LPCFHOOKPROC type defines a pointer to this callback function. CFHookProc is a placeholder for the application-defined function name.

UINT CALLBACK CFHookProc(
  HWND hdlg,      // handle to the dialog box window
  UINT uiMsg,     // message identifier
  WPARAM wParam,  // message parameter
  LPARAM lParam   // message parameter
);

Parameters

hdlg
Handle to the Font dialog box window for which the message is intended.
uiMsg
Identifies the message being received.
wParam
Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.
lParam
Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.

If the uiMsg parameter indicates the WM_INITDIALOG message, lParam is a pointer to a CHOOSEFONT structure containing the values specified when the common dialog box was created.

Return Values

If the hook procedure returns zero, the default dialog box procedure processes the message.

If the hook procedure returns a nonzero value, the default dialog box procedure ignores the message.

Remarks

When you use the ChooseFont function to create a Font dialog box, you can provide a CFHookProc hook procedure to process messages or notifications intended for the dialog box procedure. To enable the hook procedure, use the CHOOSEFONT structure that you passed to the dialog creation function. Specify the address of the hook procedure in the lpfnHook member and specify the CF_ENABLEHOOK flag in the Flags member.

The default dialog box procedure processes the WM_INITDIALOG message before passing it to the hook procedure. For all other messages, the hook procedure receives the message first. Then, the return value of the hook procedure determines whether the default dialog procedure processes the message or ignores it.

If the hook procedure processes the WM_CTLCOLORDLG message, it must return a valid brush handle for painting the background of the dialog box. In general, if the hook procedure processes any WM_CTLCOLOR* message, it must return a valid brush handle for painting the background of the specified control.

Do not call the EndDialog function from the hook procedure. Instead, the hook procedure can call the PostMessage function to post a WM_COMMAND message with the IDABORT value to the dialog box procedure. Posting IDABORT closes the dialog box and causes the dialog box function to return FALSE. If you need to know why the hook procedure closed the dialog box, you must provide your own communication mechanism between the hook procedure and your application.

You can subclass the standard controls of the common dialog box. However, the common dialog box procedure may also subclass the controls. Because of this, you should subclass controls when your hook procedure processes the WM_INITDIALOG message. This ensures that your subclass procedure receives the control-specific messages before the subclass procedure set by the dialog box procedure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.
Import Library: User-defined.

See Also

Common Dialog Box Library Overview, Common Dialog Box Functions, ChooseFont, CHOOSEFONT, EndDialog, PostMessage, WM_INITDIALOG, WM_CTLCOLORDLG


ChooseColor

The ChooseColor function creates a Color common dialog box that enables the user to select a color.

BOOL ChooseColor(
  LPCHOOSECOLOR lpcc   // pointer to structure with initialization
                       // data
);

Parameters

lpcc
Pointer to a CHOOSECOLOR structure that contains information used to initialize the dialog box. When ChooseColor returns, this structure contains information about the user's color selection.

Return Values

If the user clicks the OK button of the dialog box, the return value is nonzero. The rgbResult member of the CHOOSECOLOR structure contains the RGB color value of the color selected by the user.

If the user cancels or closes the Color dialog box or an error occurs, the return value is zero. To get extended error information, call the CommDlgExtendedError function, which can return one of the following values:

CDERR_FINDRESFAILURE | CDERR_MEMLOCKFAILURE
CDERR_INITIALIZATION | CDERR_NOHINSTANCE
CDERR_LOCKRESFAILURE | CDERR_NOHOOK
CDERR_LOADRESFAILURE | CDERR_NOTEMPLATE
CDERR_LOADSTRFAILURE | CDERR_STRUCTSIZE
CDERR_MEMALLOCFAILURE |

Remarks

The Color dialog box does not support palettes. The color choices offered by the dialog box are limited to the system colors and dithered versions of those colors.

You can provide a CCHookProc hook procedure for a Color dialog box. The hook procedure can process messages sent to the dialog box. To enable a hook procedure, set the CC_ENABLEHOOK flag in the Flags member of the CHOOSECOLOR structure and specify the address of the hook procedure in the lpfnHook member.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in commdlg.h.
Import Library: Use comdlg32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Common Dialog Box Library Overview, Common Dialog Box Functions, CCHookProc, CHOOSECOLOR, CommDlgExtendedError


ChooseFont

The ChooseFont function creates a Font common dialog box that enables the user to choose attributes for a logical font. These attributes include a typeface name, style (bold, italic, or regular), point size, effects (underline, strikeout, and text color), and a script (or character set).

BOOL ChooseFont(
  LPCHOOSEFONT lpcf   // pointer to structure with initialization
                      // data
);

Parameters

lpcf
Pointer to a CHOOSEFONT structure that contains information used to initialize the dialog box. When ChooseFont returns, this structure contains information about the user's font selection.

Return Values

If the user clicks the OK button of the dialog box, the return value is nonzero. The members of the CHOOSEFONT structure indicate the user's selections.

If the user cancels or closes the Font dialog box or an error occurs, the return value is zero. To get extended error information, call the CommDlgExtendedError function, which can return one of the following values:

CDERR_FINDRESFAILURE | CDERR_NOHINSTANCE
CDERR_INITIALIZATION | CDERR_NOHOOK
CDERR_LOCKRESFAILURE | CDERR_NOTEMPLATE
CDERR_LOADRESFAILURE | CDERR_STRUCTSIZE
CDERR_LOADSTRFAILURE | CFERR_MAXLESSTHANMIN
CDERR_MEMALLOCFAILURE | CFERR_NOFONTS
CDERR_MEMLOCKFAILURE |

Remarks

You can provide a CFHookProc hook procedure for a Font dialog box. The hook procedure can process messages sent to the dialog box. To enable a hook procedure, set the CF_ENABLEHOOK flag in the Flags member of the CHOOSEFONT structure and specify the address of the hook procedure in the lpfnHook member.

The hook procedure can send the WM_CHOOSEFONT_GETLOGFONT, WM_CHOOSEFONT_SETFLAGS, and WM_CHOOSEFONT_SETLOGFONT messages to the dialog box to get and set the current values and flags of the dialog box.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.
Import Library: Use comdlg32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Common Dialog Box Library Overview, Common Dialog Box Functions, CFHookProc, CHOOSEFONT, CommDlgExtendedError, LOGFONT, WM_CHOOSEFONT_GETLOGFONT, WM_CHOOSEFONT_SETFLAGS, WM_CHOOSEFONT_SETLOGFONT


CommDlgExtendedError

The CommDlgExtendedError function returns a common dialog box error code. This code indicates the most recent error to occur during the execution of one of the following common dialog box functions:

ChooseColor | GetOpenFileName
ChooseFont | GetSaveFileName
FindText | PrintDlg
ReplaceText | PageSetupDlg

DWORD CommDlgExtendedError(VOID)

Parameters

This function has no parameters.

Return Values

If the most recent call to a common dialog box function succeeded, the return value is undefined.

If the common dialog box function returned FALSE because the user closed or canceled the dialog box, the return value is zero. Otherwise, the return value is a nonzero error code. For more information, see the following Remarks section.

Remarks

The CommDlgExtendedError function can return general error codes for any of the common dialog box functions. In addition, there are error codes that are returned only for a specific common dialog box. The error codes returned by CommDlgExtendedError are defined in the CDERR.H file.

The following general error codes can be returned for any of the common dialog box functions:

Value | Meaning
CDERR_DIALOGFAILURE | The dialog box could not be created. The common dialog box function's call to the DialogBox function failed. For example, this error occurs if the common dialog box call specifies an invalid window handle.
CDERR_FINDRESFAILURE | The common dialog box function failed to find a specified resource.
CDERR_INITIALIZATION | The common dialog box function failed during initialization. This error often occurs when sufficient memory is not available.
CDERR_LOADRESFAILURE | The common dialog box function failed to load a specified resource.
CDERR_LOADSTRFAILURE | The common dialog box function failed to load a specified string.
CDERR_LOCKRESFAILURE | The common dialog box function failed to lock a specified resource.
CDERR_MEMALLOCFAILURE | The common dialog box function was unable to allocate memory for internal structures.
CDERR_MEMLOCKFAILURE | The common dialog box function was unable to lock the memory associated with a handle.
CDERR_NOHINSTANCE | The ENABLETEMPLATE flag was set in the Flags member of the initialization structure for the corresponding common dialog box, but you failed to provide a corresponding instance handle.
CDERR_NOHOOK | The ENABLEHOOK flag was set in the Flags member of the initialization structure for the corresponding common dialog box, but you failed to provide a pointer to a corresponding hook procedure.
CDERR_NOTEMPLATE | The ENABLETEMPLATE flag was set in the Flags member of the initialization structure for the corresponding common dialog box, but you failed to provide a corresponding template.
CDERR_REGISTERMSGFAIL | The RegisterWindowMessage function returned an error code when it was called by the common dialog box function.
CDERR_STRUCTSIZE | The lStructSize member of the initialization structure for the corresponding common dialog box is invalid.

The following error codes can be returned for the PrintDlg function:

Value | Meaning
PDERR_CREATEICFAILURE | The PrintDlg function failed when it attempted to create an information context.
PDERR_DEFAULTDIFFERENT | You called the PrintDlg function with the DN_DEFAULTPRN flag specified in the wDefault member of the DEVNAMES structure, but the printer described by the other structure members did not match the current default printer. (This error occurs when you store the DEVNAMES structure and the user changes the default printer by using the Control Panel.)
To use the printer described by the DEVNAMES structure, clear the DN_DEFAULTPRN flag and call PrintDlg again.

To use the default printer, replace the DEVNAMES structure (and the DEVMODE structure, if one exists) with NULL; and call PrintDlg again.

PDERR_DNDMMISMATCH | The data in the DEVMODE and DEVNAMES structures describes two different printers.
PDERR_GETDEVMODEFAIL | The printer driver failed to initialize a DEVMODE structure. (This error code applies only to printer drivers written for Windows version 3.0 and later.)
PDERR_INITFAILURE | The PrintDlg function failed during initialization, and there is no more specific extended error code to describe the failure. This is the generic default error code for the function.
PDERR_LOADDRVFAILURE | The PrintDlg function failed to load the device driver for the specified printer.
PDERR_NODEFAULTPRN | A default printer does not exist.
PDERR_NODEVICES | No printer drivers were found.
PDERR_PARSEFAILURE | The PrintDlg function failed to parse the strings in the [devices] section of the WIN.INI file.
PDERR_PRINTERNOTFOUND | The [devices] section of the WIN.INI file did not contain an entry for the requested printer.
PDERR_RETDEFFAILURE | The PD_RETURNDEFAULT flag was specified in the Flags member of the PRINTDLG structure, but the hDevMode or hDevNames member was not NULL.
PDERR_SETUPFAILURE | The PrintDlg function failed to load the required resources.

The following error codes can be returned for the ChooseFont function:

Value | Meaning
CFERR_MAXLESSTHANMIN | The size specified in the nSizeMax member of the CHOOSEFONT structure is less than the size specified in the nSizeMin member.
CFERR_NOFONTS | No fonts exist.

The following error codes can be returned for the GetOpenFileName and GetSaveFileName functions:

Value | Meaning
FNERR_BUFFERTOOSMALL | The buffer pointed to by the lpstrFile member of the OPENFILENAME structure is too small for the filename specified by the user. The first two bytes of the lpstrFile buffer contain an integer value specifying the size, in bytes (ANSI version) or 16-bit characters (Unicode version), required to receive the full name.
FNERR_INVALIDFILENAME | A filename is invalid.
FNERR_SUBCLASSFAILURE | An attempt to subclass a list box failed because sufficient memory was not available.

The following error code can be returned for the FindText and ReplaceText functions:

Value | Meaning
FRERR_BUFFERLENGTHZERO | A member of the FINDREPLACE structure points to an invalid buffer.

Windows CE: Windows CE supports four additional return values:

CDERR_REGISTRYFAILURE
The common dialog box function was unable to read from registry.

The following return values apply only to the PrintDlg function:

PDERR_NOPORTS
No ports are registered.
PDERR_NOPRINTERS
No printers are registered.
PDERR_CREATEDCFAILURE
The call to CreateDC failed.

Windows CE does not support the CDERR_LOADSTRFAILURE, CDERR_MEMLOCKFAILURE, or CDERR_REGISTERMSGFAIL return values.

Windows CE does not support any of the PDERR_ error values.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in commdlg.h.
Import Library: Use comdlg32.lib.

See Also

Common Dialog Box Library Overview, Common Dialog Box Functions, ChooseColor, CHOOSECOLOR, ChooseFont, CHOOSEFONT, DEVMODE, DEVNAMES, DialogBox, FINDREPLACE, FindText, GetOpenFileName, GetSaveFileName, OPENFILENAME, PageSetupDlg, PAGESETUPDLG, PrintDlg, PRINTDLG, RegisterWindowMessage, ReplaceText


FindText

The FindText function creates a system-defined modeless Find dialog box that lets the user specify a string to search for and options to use when searching for text in a document.

HWND FindText(
  LPFINDREPLACE lpfr   // pointer to structure with initialization
                       // data
);

Parameters

lpfr
Pointer to a FINDREPLACE structure that contains information used to initialize the dialog box. The dialog box uses this structure to send information about the user's input to your application. For more information, see the following Remarks section.

Return Values

If the function succeeds, the return value is the window handle to the dialog box. You can use the window handle to communicate with or to close the dialog box.

If the function fails, the return value is NULL. To get extended error information, call the CommDlgExtendedError function. CommDlgExtendedError may return one of the following error codes:

CDERR_FINDRESFAILURE | CDERR_MEMLOCKFAILURE
CDERR_INITIALIZATION | CDERR_NOHINSTANCE
CDERR_LOCKRESFAILURE | CDERR_NOHOOK
CDERR_LOADRESFAILURE | CDERR_NOTEMPLATE
CDERR_LOADSTRFAILURE | CDERR_STRUCTSIZE
CDERR_MEMALLOCFAILURE | FRERR_BUFFERLENGTHZERO

Remarks

The FindText function does not perform a search operation. Instead, the dialog box sends FINDMSGSTRING registered messages to the window procedure of the owner window of the dialog box. When you create the dialog box, the hwndOwner member of the FINDREPLACE structure identifies the owner window.

Before calling FindText, you must call the RegisterWindowMessage function to get the identifier for the FINDMSGSTRING message. The dialog box procedure uses this identifier to send messages when the user clicks the Find Next button, or when the dialog box is closing. The lParam parameter of the FINDMSGSTRING message contains a pointer to a FINDREPLACE structure. The Flags member of this structure indicates the event that caused the message. Other members of the structure indicate the user's input.

If you create a Find dialog box, you must also use the IsDialogMessage function in the main message loop of your application to ensure that the dialog box correctly processes keyboard input, such as the tab and esc keys. IsDialogMessage returns a value that indicates whether the Find dialog box processed the message.

You can provide an FRHookProc hook procedure for a Find dialog box. The hook procedure can process messages sent to the dialog box. To enable a hook procedure, set the FR_ENABLEHOOK flag in the Flags member of the FINDREPLACE structure and specify the address of the hook procedure in the lpfnHook member.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.
Import Library: Use comdlg32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Common Dialog Box Library Overview, Common Dialog Box Functions, CommDlgExtendedError, FINDMSGSTRING, FINDREPLACE, FRHookProc, IsDialogMessage, RegisterWindowMessage, ReplaceText


FRHookProc

The FRHookProc hook procedure is an application-defined or library-defined callback function that is used with the FindText or ReplaceText function. The hook procedure receives messages or notifications intended for the default dialog box procedure of the Find or Replace common dialog box.

The LPFRHOOKPROC type defines a pointer to this callback function. FRHookProc is a placeholder for the application-defined function name.

UINT CALLBACK FRHookProc(
  HWND hdlg,      // handle to the dialog box window
  UINT uiMsg      // message identifier
  WPARAM wParam,  // message parameter
  LPARAM lParam   // message parameter
);

Parameters

hdlg
Handle to the Find or Replace common dialog box window for which the message is intended.
uiMsg
Identifies the message being received.
wParam
Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.
lParam
Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.

If the uiMsg parameter indicates the WM_INITDIALOG message, lParam is a pointer to a FINDREPLACE structure containing the values specified when the common dialog box was created.

Return Values

If the hook procedure returns zero, the default dialog box procedure processes the message.

If the hook procedure returns a nonzero value, the default dialog box procedure ignores the message.

Remarks

When you use the FindText or ReplaceText functions to create a Find or Replace common dialog box, you can provide an FRHookProc hook procedure to process messages or notifications intended for the dialog box procedure. To enable the hook procedure, use the FINDREPLACE structure that you passed to the dialog creation function. Specify the address of the hook procedure in the lpfnHook member and specify the FR_ENABLEHOOK flag in the Flags member.

The default dialog box procedure processes the WM_INITDIALOG message before passing it to the hook procedure. For all other messages, the hook procedure receives the message first. Then, the return value of the hook procedure determines whether the default dialog procedure processes the message or ignores it.

If the hook procedure processes the WM_CTLCOLORDLG message, it must return a valid brush handle for painting the background of the dialog box. In general, if the hook procedure processes any WM_CTLCOLOR* message, it must return a valid brush handle for painting the background of the specified control.

Do not call the EndDialog function from the hook procedure. Instead, the hook procedure can call the PostMessage function to post a WM_COMMAND message with the IDABORT value to the dialog box procedure. Posting IDABORT closes the dialog box and causes the dialog box function to return FALSE. If you need to know why the hook procedure closed the dialog box, you must provide your own communication mechanism between the hook procedure and your application.

You can subclass the standard controls of the common dialog box. However, the common dialog box procedure may also subclass the controls. Because of this, you should subclass controls when your hook procedure processes the WM_INITDIALOG message. This ensures that your subclass procedure receives the control-specific messages before the subclass procedure set by the dialog box procedure.

FRHookProc is a placeholder for the application-defined or library-defined function name. The LPFRHOOKPROC type is a pointer to an FRHookProc hook procedure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.
Import Library: User-defined.

See Also

Common Dialog Box Library Overview, Common Dialog Box Functions, EndDialog, FINDREPLACE, FindText, PostMessage, ReplaceText, WM_INITDIALOG, WM_CTLCOLORDLG


GetFileTitle

The GetFileTitle function returns the name of the file identified by the lpszFile parameter.

short GetFileTitle(
  LPCTSTR lpszFile,  // pointer to full path and filename for file
  LPTSTR lpszTitle,  // pointer to buffer that receives filename
  WORD cbBuf         // length of buffer
);

Parameters

lpszFile
Pointer to the name and location of a file.
lpszTitle
Pointer to a buffer into which the function is to copy the name of the file.
cbBuf
Specifies the length, in characters, of the buffer pointed to by the lpszTitle parameter.

Return Values

If the function succeeds, the return value is zero.

If the filename is invalid, the return value is a negative number.

If the buffer pointed to by the lpszTitle parameter is too small, the return value is a positive integer that specifies the required buffer size, in bytes (ANSI version) or 16-bit characters (Unicode version). The required buffer size includes the terminating null character.

Remarks

The GetFileTitle function returns an error value if the buffer pointed to by the lpszFile parameter contains any of the following elements:

  • An empty string
  • A string containing a wildcard (*), opening bracket ([), or closing bracket (])
  • A string that ends with a colon (:), slash mark (/), or backslash (\)
  • A string whose length exceeded the length of the buffer
  • An invalid character (for example, a space or an unprintable character)

To get the buffer size needed for the name of a file, call the function with lpszTitle set to NULL and cbBuf set to zero. The function will return the required size.

GetFileTitle returns the string that the system would use to display the filename to the user. The display name includes an extension only if that is the user's preference for displaying filenames. This means that the returned string may not accurately identify the file if it is used in calls to file system functions.

If the lpszTitle buffer is too small, GetFileTitle returns the size required to hold the display name. There is no guaranteed connection between the required size and the characters originally specified in the lpszFile buffer. In porting 16-bit Windows-based applications to Win32, you will need to update any code that relies on such behavior in previous versions of the system. The most common case is code that deliberately calls GetFileTitle with lpszTitle set to NULL and cbBuf set to zero, and then uses the return value as an index into the lpszFile string. This technique is no longer supported. You can usually achieve similar results (and superior performance) with run-time library functions such as strrchr, wcsrchr, and _mbsrchr.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.
Import Library: Use comdlg32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Common Dialog Box Library Overview, Common Dialog Box Functions, GetOpenFileName, GetSaveFileName


GetOpenFileName

The GetOpenFileName function creates an Open common dialog box that lets the user specify the drive, directory, and the name of a file or set of files to open.

BOOL GetOpenFileName(
  LPOPENFILENAME lpofn   // address of structure with initialization
                         // data
);

Parameters

lpofn
Pointer to an OPENFILENAME structure that contains information used to initialize the dialog box. When GetOpenFileName returns, this structure contains information about the user's file selection.

Return Values

If the user specifies a filename and clicks the OK button, the return value is nonzero. The buffer pointed to by the lpstrFile member of the OPENFILENAME structure contains the full path and filename specified by the user.

If the user cancels or closes the Open dialog box or an error occurs, the return value is zero. To get extended error information, call the CommDlgExtendedError function, which can return one of the following values:

CDERR_FINDRESFAILURE | CDERR_NOHINSTANCE
CDERR_INITIALIZATION | CDERR_NOHOOK
CDERR_LOCKRESFAILURE | CDERR_NOTEMPLATE
CDERR_LOADRESFAILURE | CDERR_STRUCTSIZE
CDERR_LOADSTRFAILURE | FNERR_BUFFERTOOSMALL
CDERR_MEMALLOCFAILURE | FNERR_INVALIDFILENAME
CDERR_MEMLOCKFAILURE | FNERR_SUBCLASSFAILURE

Remarks

Beginning with Windows 95 and Windows NT version 4.0, the default Open dialog box provides user-interface features that are similar to the Windows Explorer. You can provide an OFNHookProc hook procedure for an Explorer-style Open dialog box. To enable the hook procedure, set the OFN_EXPLORER and OFN_ENABLEHOOK flags in the Flags member of the OPENFILENAME structure and specify the address of the hook procedure in the lpfnHook member.

Windows 95 and Windows NT continue to support the old-style Open dialog box for applications that want to maintain a user-interface consistent with the Windows 3.1 or Windows NT 3.51 user-interface. To display the old-style Open dialog box, enable an OFNHookProcOldStyle hook procedure and ensure that the OFN_EXPLORER flag is not set.

To display a dialog box that allows the user to select a directory instead of a file, call the SHBrowseForFolder function.

Windows CE: Not all members of the OPENFILENAME structure are defined in Windows CE. For information about the defined members, see the reference topic for the OPENFILENAME structure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in commdlg.h.
Import Library: Use comdlg32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Common Dialog Box Library Overview, Common Dialog Box Functions, CommDlgExtendedError, GetSaveFileName, OFNHookProc , OFNHookProcOldStyle, OPENFILENAME, SHBrowseForFolder


GetSaveFileName

The GetSaveFileName function creates a Save common dialog box that lets the user specify the drive, directory, and name of a file to save.

BOOL GetSaveFileName(
  LPOPENFILENAME lpofn   // address of structure with initialization
                         // data
);

Parameters

lpofn
Pointer to an OPENFILENAME structure that contains information used to initialize the dialog box. When GetSaveFileName returns, this structure contains information about the user's file selection.

Return Values

If the user specifies a filename and clicks the OK button, the return value is nonzero. The buffer pointed to by the lpstrFile member of the OPENFILENAME structure contains the full path and filename specified by the user.

If the user cancels or closes the Save dialog box or an error occurs, the return value is zero. To get extended error information, call the CommDlgExtendedError function, which can return one of the following values:

CDERR_FINDRESFAILURE | CDERR_NOHINSTANCE
CDERR_INITIALIZATION | CDERR_NOHOOK
CDERR_LOCKRESFAILURE | CDERR_NOTEMPLATE
CDERR_LOADRESFAILURE | CDERR_STRUCTSIZE
CDERR_LOADSTRFAILURE | FNERR_BUFFERTOOSMALL
CDERR_MEMALLOCFAILURE | FNERR_INVALIDFILENAME
CDERR_MEMLOCKFAILURE | FNERR_SUBCLASSFAILURE

Remarks

By default, Windows 95 and Windows NT version 4.0 display a new version of the Save dialog box that provides user-interface features that are similar to the Windows Explorer. You can provide an OFNHookProc hook procedure for an Explorer-style Save dialog box. To enable the hook procedure, set the OFN_EXPLORER and OFN_ENABLEHOOK flags in the Flags member of the OPENFILENAME structure and specify the address of the hook procedure in the lpfnHook member.

Windows 95 and Windows NT 4.0 continue to support the old-style Save dialog box for applications that want to maintain a user-interface consistent with the Windows 3.1 or Windows NT 3.51 user-interface. To display the old-style Save dialog box, enable an OFNHookProcOldStyle hook procedure and ensure that the OFN_EXPLORER flag is not set.

Windows CE: Not all members of the OPENFILENAME structure are defined in Windows CE. For information about the defined members, see the reference topic for the OPENFILENAME structure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in commdlg.h.
Import Library: Use comdlg32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Common Dialog Box Library Overview, Common Dialog Box Functions, CommDlgExtendedError, GetOpenFilename, OFNHookProc, OFNHookProcOldStyle, OPENFILENAME


OFNHookProc

The OFNHookProc hook procedure is an application-defined or library-defined callback function that is used with the Explorer-style Open and Save As common dialog boxes. The function receives notification messages sent from the common dialog box. The function also receives messages for any additional controls that you defined by specifying a child dialog template.

The LPOFNHOOKPROC type defines a pointer to this callback function. OFNHookProc is a placeholder for the application-defined or library-defined function name.

If you do not specify the OFN_EXPLORER flag when you create an Open or Save As common dialog box, and you want a hook procedure, you must use an old-style OFNHookProcOldStyle hook procedure. In this case, the dialog box will have the old-style user interface.

UINT CALLBACK OFNHookProc(
  HWND hdlg,      // handle to child dialog window
  UINT uiMsg,     // message identifier
  WPARAM wParam,  // message parameter
  LPARAM lParam   // message parameter
);

Parameters

hdlg
Handle to the child dialog box of the Open or Save As dialog box. Use the GetParent function to get the handle to the Open or Save As dialog box window.
uiMsg
Identifies the message being received.
wParam
Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.
lParam
Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.

If the uiMsg parameter indicates the WM_INITDIALOG message, lParam is a pointer to an OPENFILENAME structure containing the values specified when the dialog box was created.

Return Values

If the hook procedure returns zero, the default dialog box procedure processes the message.

If the hook procedure returns a nonzero value, the default dialog box procedure ignores the message.

For the CDN_SHAREVIOLATION and CDN_FILEOK notification messages, the hook procedure should return a nonzero value to indicate that it has used the SetWindowLong function to set a nonzero DWL_MSGRESULT value.

Remarks

When you use the GetOpenFileName or GetSaveFileName functions to create an Explorer-style Open or Save As common dialog box, you can provide an OFNHookProc hook procedure. To enable the hook procedure, use the OPENFILENAME structure that you passed to the dialog creation function. Specify the pointer to the hook procedure in the lpfnHook member and specify the OFN_ENABLEHOOK flag in the Flags member.

If you provide a hook procedure for an Explorer-style common dialog box, the system creates a dialog box that is a child of the default dialog box. The hook procedure acts as the dialog procedure for the child dialog. This child dialog is based on the template you specified in the OPENFILENAME structure, or it is a default child dialog if no template is specified. The child dialog is created when the default dialog procedure is processing its WM_INITDIALOG message. After the child dialog processes its own WM_INITDIALOG message, the default dialog procedure moves the standard controls, if necessary, to make room for any additional controls of the child dialog. The system then sends the CDN_INITDONE notification message to the hook procedure.

The hook procedure does not receive messages intended for the standard controls of the default dialog box. You can subclass the standard controls, but this is discouraged because it may make your application incompatible with future versions of the common dialog box. However, the Explorer-style common dialogs provide a set of messages that the hook procedure can use to monitor and control the dialog. These include a set of notification messages sent from the dialog, as well as messages that you can send to retrieve information from the dialog. For a complete list of these messages, see Explorer-Style Hook Procedures.

If the hook procedure processes the WM_CTLCOLORDLG message, it must return a valid brush handle for painting the background of the dialog box. In general, if it processes any WM_CTLCOLOR* message, it must return a valid brush handle for painting the background of the specified control.

Do not call the EndDialog function from the hook procedure. Instead, the hook procedure can call the PostMessage function to post a WM_COMMAND message with the IDABORT value to the dialog box procedure. Posting IDABORT closes the dialog box and causes the dialog box function to return FALSE. If you need to know why the hook procedure closed the dialog box, you must provide your own communication mechanism between the hook procedure and your application.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.
Import Library: User-defined.

See Also

Common Dialog Box Library Overview, Common Dialog Box Functions, GetOpenFileName, GetSaveFileName, OFNHookProcOldStyle, OPENFILENAME


OFNHookProcOldStyle

The OFNHookProcOldStyle hook procedure is an application-defined or library-defined callback function that is used with the Open and Save As common dialog boxes. The function receives messages or notifications intended for the dialog box procedure.

The LPOFNHOOKPROC type defines a pointer to this callback function. OFNHookProcOldStyle is a placeholder for the application-defined or library-defined function name.

If you specify the OFN_EXPLORER flag when you create an Open or Save As common dialog box, and you want a hook procedure, you must use an Explorer-style OFNHookProc hook procedure.

UINT CALLBACK OFNHookProcOldStyle(
  HWND hdlg,      // handle to the dialog box window
  UINT uiMsg      // message identifier
  WPARAM wParam,  // message parameter
  LPARAM lParam   // message parameter
);

Parameters

hdlg
Handle to the Open or Save As dialog box window for which the message is intended.
uiMsg
Identifies the message being received.
wParam
Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.
lParam
Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.

If the uiMsg parameter indicates the WM_INITDIALOG message, lParam is a pointer to an OPENFILENAME structure containing the values specified when the common dialog box was created.

Return Values

If the hook procedure returns zero, the default dialog box procedure processes the message.

If the hook procedure returns a nonzero value, the default dialog box procedure ignores the message.

Remarks

When you use the GetOpenFileName or GetSaveFileName functions to create an old-style Open or Save As dialog box, you can provide an OFNHookProcOldStyle hook procedure. To enable the hook procedure, use the OPENFILENAME structure that you passed to the dialog creation function. Specify the pointer to the hook procedure in the lpfnHook member and specify the OFN_ENABLEHOOK flag in the Flags member.

The default dialog box procedure processes the WM_INITDIALOG message before passing it to the hook procedure. For all other messages, the hook procedure receives the message first. Then, the return value of the hook procedure determines whether the default dialog procedure processes the message or ignores it.

If the hook procedure processes the WM_CTLCOLORDLG message, it must return a valid brush handle for painting the background of the dialog box. In general, if the hook procedure processes any WM_CTLCOLOR* message, it must return a valid brush handle for painting the background of the specified control.

Do not call the EndDialog function from the hook procedure. Instead, the hook procedure can call the PostMessage function to post a WM_COMMAND message with the IDABORT value to the dialog box procedure. Posting IDABORT closes the dialog box and causes the dialog box function to return FALSE. If you need to know why the hook procedure closed the dialog box, you must provide your own communication mechanism between the hook procedure and your application.

You can subclass the standard controls of the common dialog box. However, the common dialog box procedure may also subclass the controls. Because of this, you should subclass controls when your hook procedure processes the WM_INITDIALOG message. This ensures that your subclass procedure receives the control-specific messages before the subclass procedure set by the dialog box procedure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.
Import Library: User-defined.

See Also

Common Dialog Box Library Overview, Common Dialog Box Functions, GetOpenFileName, GetSaveFileName, OFNHookProc, OPENFILENAME, WM_INITDIALOG


PagePaintHook

The PagePaintHook hook procedure is an application-defined or library-defined callback function used with the PageSetupDlg function. This function receives messages that allow you to customize drawing of the sample page in the Page Setup dialog box.

The LPPAGEPAINTHOOK type defines a pointer to this callback function. PagePaintHook is a placeholder for the application-defined or library-defined function name.

UINT CALLBACK PagePaintHook(
  HWND hdlg,      // handle to the dialog box window
  UINT uiMsg,     // message identifier
  WPARAM wParam,  // message parameter
  LPARAM lParam   // message parameter
);

Parameters

hdlg
Handle to the Page Setup dialog box window.
uiMsg
Identifies the message being received.
wParam
Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.
lParam
Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.

Return Values

If the hook procedure returns TRUE for any of the first three messages of a drawing sequence (WM_PSD_PAGESETUPDLG, WM_PSD_FULLPAGERECT, or WM_PSD_MINMARGINRECT), the dialog box sends no more messages and does not draw in the sample page until the next time the system needs to redraw the sample page. If the hook procedure returns FALSE for all three messages, the dialog box sends the remaining messages of the drawing sequence.

If the hook procedure returns TRUE for any of the remaining messages in a drawing sequence, the dialog box does not draw the corresponding portion of the sample page. If the hook procedure returns FALSE for any of these messages, the dialog box draws that portion of the sample page.

Remarks

The Page Setup dialog box includes an image of a sample page that shows how the user's selections affect the appearance of the printed output. The image consists of a rectangle that represents the selected paper or envelope type, with a dotted-line rectangle representing the current margins, and partial (Greek text) characters to show how text looks on the printed page. When you use the PageSetupDlg function to create a Page Setup dialog box, you can provide a PagePaintHook hook procedure to customize the appearance of the sample page.

To enable the hook procedure, use the PAGESETUPDLG structure that you passed to the dialog creation function. Specify the pointer to the hook procedure in the lpfnPagePaintHook member and specify the PSD_ENABLEPAGEPAINTHOOK flag in the Flags member.

Whenever the dialog box is about to draw the contents of the sample page, the hook procedure receives the following messages in the order in which they are listed:

Message | Meaning
WM_PSD_PAGESETUPDLG | The dialog box is about to draw the sample page. The hook procedure can use this message to prepare to draw the contents of the sample page.
WM_PSD_FULLPAGERECT | The dialog box is about to draw the sample page. This message specifies the bounding rectangle of the sample page.
WM_PSD_MINMARGINRECT | The dialog box is about to draw the sample page. This message specifies the margin rectangle.
WM_PSD_MARGINRECT | The dialog box is about to draw the margin rectangle.
WM_PSD_GREEKTEXTRECT | The dialog box is about to draw the Greek text inside the margin rectangle.
WM_PSD_ENVSTAMPRECT | The dialog box is about to draw in the envelope-stamp rectangle of an envelope sample page. This message is sent for envelopes only.
WM_PSD_YAFULLPAGERECT | The dialog box is about to draw the return address portion of an envelope sample page. This message is sent for envelopes and other paper sizes.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.
Import Library: User-defined.

See Also

Common Dialog Box Library Overview, Common Dialog Box Functions, PageSetupDlg, PAGESETUPDLG


PageSetupDlg

The PageSetupDlg function creates a Page Setup dialog box that enables the user to specify the attributes of a printed page. These attributes include the paper size and source, the page orientation (portrait or landscape), and the width of the page margins.

BOOL PageSetupDlg(
  LPPAGESETUPDLG lppsd  pointer to a structure
);

Parameters

lppsd
Pointer to a PAGESETUPDLG structure that contains information used to initialize the dialog box. The structure receives information about the user's selections when the function returns.

Return Values

If the user clicks the OK button, the return value is nonzero. The members of the PAGESETUPDLG structure pointed to by the lppsd parameter indicate the user's selections.

If the user cancels or closes the Page Setup dialog box or an error occurs, the return value is zero. To get extended error information, use the CommDlgExtendedError function

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.
Import Library: Use commdlg32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Common Dialog Box Library Overview, Common Dialog Box Functions, CommDlgExtendedError, PagePaintHook, PAGESETUPDLG, PageSetupHook


PageSetupHook

The PageSetupHook hook procedure is an application-defined or library-defined callback function used with the PageSetupDlg function. The function receives messages or notifications intended for the default dialog box procedure of the Page Setup common dialog box.

The LPPAGESETUPHOOK type defines a pointer to this callback function. PageSetupHook is a placeholder for the application-defined or library-defined function name.

UINT CALLBACK PageSetupHook(
  HWND hdlg,      // handle to the dialog box window
  UINT uiMsg,     // message identifier
  WPARAM wParam,  // message parameter
  LPARAM lParam   // message parameter
);

Parameters

hdlg
Handle to the Page Setup dialog box window for which the message is intended.
uiMsg
Identifies the message being received.
wParam
Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.
lParam
Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.

If the uiMsg parameter indicates the WM_INITDIALOG message, lParam is a pointer to a PAGESETUPDLG structure containing the values specified when the common dialog box was created.

Return Values

If the hook procedure returns zero, the default dialog box procedure processes the message.

If the hook procedure returns a nonzero value, the default dialog box procedure ignores the message.

Remarks

When you use the PageSetupDlg function to create a Page Setup common dialog box, you can provide a PageSetupHook hook procedure to process messages or notifications intended for the dialog box procedure. To enable the hook procedure, use the PAGESETUPDLG structure that you passed to the dialog creation function. Specify the pointer to the hook procedure in the lpfnPageSetupHook member and specify the PSD_ENABLEPAGESETUPHOOK flag in the Flags member.

The default dialog box procedure processes the WM_INITDIALOG message before passing it to the hook procedure. For all other messages, the hook procedure receives the message first. Then, the return value of the hook procedure determines whether the default dialog procedure processes the message or ignores it.

If the hook procedure processes the WM_CTLCOLORDLG message, it must return a valid brush handle for painting the background of the dialog box. In general, if the hook procedure processes any WM_CTLCOLOR* message, it must return a valid brush handle for painting the background of the specified control.

Do not call the EndDialog function from the hook procedure. Instead, the hook procedure can call the PostMessage function to post a WM_COMMAND message with the IDABORT value to the dialog box procedure. Posting IDABORT closes the dialog box and causes the dialog box function to return FALSE. If you need to know why the hook procedure closed the dialog box, you must provide your own communication mechanism between the hook procedure and your application.

You can subclass the standard controls of the common dialog box. However, the common dialog box procedure may also subclass the controls. Because of this, you should subclass controls when your hook procedure processes the WM_INITDIALOG message. This ensures that your subclass procedure receives the control-specific messages before the subclass procedure set by the dialog box procedure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.
Import Library: User-defined.

See Also

Common Dialog Box Library Overview, Common Dialog Box Functions, EndDialog, PageSetupDlg, PAGESETUPDLG, PostMessage, WM_INITDIALOG, WM_CTLCOLORDLG


PrintDlg

The PrintDlg function displays a Print dialog box or a Print Setup dialog box. The Print dialog box enables the user to specify the properties of a particular print job.

The Print Setup dialog box should not be used in new applications. It has been superseded by the Page Setup common dialog box created by the PageSetupDlg function.

BOOL PrintDlg(
  LPPRINTDLG lppd   // pointer to structure with initialization data
);

Parameters

lppd
Pointer to a PRINTDLG structure that contains information used to initialize the dialog box. When PrintDlg returns, this structure contains information about the user's selections.

Return Values

If the user clicks the OK button, the return value is nonzero. The members of the PRINTDLG structure pointed to by the lppd parameter indicate the user's selections.

If the user canceled or closed the Print or Printer Setup dialog box or an error occurred, the return value is zero. To get extended error information, use the CommDlgExtendedError function. If the user canceled or closed the dialog box, CommDlgExtendedError returns zero; otherwise, it returns one of the following values:

CDERR_FINDRESFAILURE | PDERR_CREATEICFAILURE
CDERR_INITIALIZATION | PDERR_DEFAULTDIFFERENT
CDERR_LOADRESFAILURE | PDERR_DNDMMISMATCH
CDERR_LOADSTRFAILURE | PDERR_GETDEVMODEFAIL
CDERR_LOCKRESFAILURE | PDERR_INITFAILURE
CDERR_MEMALLOCFAILURE | PDERR_LOADDRVFAILURE
CDERR_MEMLOCKFAILURE | PDERR_NODEFAULTPRN
CDERR_NOHINSTANCE | PDERR_NODEVICES
CDERR_NOHOOK | PDERR_PARSEFAILURE
CDERR_NOTEMPLATE | PDERR_PRINTERNOTFOUND
CDERR_STRUCTSIZE | PDERR_RETDEFFAILURE

Remarks

If the hook procedure (pointed to by the lpfnPrintHook or lpfnSetupHook member of the PRINTDLG structure) processes the WM_CTLCOLORDLG message, the hook procedure must return a handle for the brush that should be used to paint the control background.

Windows NT 5.0 and later: You can use the PrintDlgEx function to display a Print property sheet, which has a General page containing controls similar to the Print common dialog box.

Windows CE: The PRINTDLG structure contains different members in Windows CE than it does in Windows desktop platforms.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in commdlg.h.
Import Library: Use comdlg32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Common Dialog Box Library Overview, Common Dialog Box Functions, CommDlgExtendedError, CreateDC, DOCINFO, PRINTDLG, PrintHookProc, SetupHookProc, StartDoc, WM_CTLCOLORDLG


PrintDlgEx

[This is preliminary documentation and subject to change.]

The PrintDlgEx function displays a Print property sheet that enables the user to specify the properties of a particular print job. A Print property sheet has a General page containing controls similar to the Print common dialog box. The property sheet can also have additional application-specific and driver-specific property pages following the General page.

HRESULT PrintDlgEx(
  LPPRINTDLGEX lppd   // pointer to structure with initialization data
);

Parameters

lppd
Pointer to a PRINTDLGEX structure that contains information used to initialize the property sheet. When PrintDlgEx returns, this structure contains information about the user's selections.

Return Values

If the function succeeds, the return value is S_OK and the dwResultAction member of the PRINTDLGEX structure contains one of the following values.

Value | Meaning
PD_RESULT_APPLY | The user clicked the Apply button and later clicked the Cancel button. This indicates that the user wants to apply the changes made in the property sheet, but does not yet want to print. The PRINTDLGEX structure contains the information specified by the user at the time the Apply button was clicked.
PD_RESULT_CANCEL | The user clicked the Cancel button. The information in the PRINTDLGEX structure is unchanged.
PD_RESULT_PRINT | The user clicked the Print button. The PRINTDLGEX structure contains the information specified by the user.

If the function fails, the return value may be one of the following COM error codes. For more information, see Error Handling.

Value | Meaning
E_OUTOFMEMORY | Insufficient memory.
E_INVALIDARG | One or more arguments are invalid.
E_POINTER | Invalid pointer.
E_HANDLE | Invalid handle.
E_FAIL | Unspecified error.

Remarks

For more information, see Print Property Sheet.

QuickInfo

Windows NT: Requires version 5.0 or later.
Windows: Unsupported.
Windows CE: Unsupported.
Header: Declared in commdlg.h.
Import Library: Use comdlg32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Common Dialog Box Library Overview, Common Dialog Box Functions, CreatePropertySheetPage, PrintDlg, PRINTDLGEX


PrintHookProc

The PrintHookProc hook procedure is an application-defined or library-defined callback function that is used with the PrintDlg function. The function receives messages or notifications intended for the default dialog box procedure of the Print common dialog box.

The LPPRINTHOOKPROC type defines a pointer to this callback function. PrintHookProc is a placeholder for the application-defined or library-defined function name.

UINT CALLBACK PrintHookProc(
  HWND hdlg,      // handle to the dialog box window
  UINT uiMsg,     // message identifier
  WPARAM wParam,  // message parameter
  LPARAM lParam   // message parameter
);

Parameters

hdlg
Handle to the Print common dialog box window for which the message is intended.
uiMsg
Identifies the message being received.
wParam
Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.
lParam
Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.

If the uiMsg parameter indicates the WM_INITDIALOG message, lParam is a pointer to a PRINTDLG structure containing the values specified when the common dialog box was created.

Return Values

If the hook procedure returns zero, the default dialog box procedure processes the message.

If the hook procedure returns a nonzero value, the default dialog box procedure ignores the message.

Remarks

When you use the PrintDlg function to create a Print common dialog box, you can provide a PrintHookProc hook procedure to process messages or notifications intended for the dialog box procedure. To enable the hook procedure, use the PRINTDLG structure that you passed to the dialog creation function. Specify the address of the hook procedure in the lpfnPrintHook member and specify the PD_ENABLEPRINTHOOK flag in the Flags member.

The default dialog box procedure processes the WM_INITDIALOG message before passing it to the hook procedure. For all other messages, the hook procedure receives the message first. Then, the return value of the hook procedure determines whether the default dialog procedure processes the message or ignores it.

If the hook procedure processes the WM_CTLCOLORDLG message, it must return a valid brush handle for painting the background of the dialog box. In general, if the hook procedure processes any WM_CTLCOLOR* message, it must return a valid brush handle for painting the background of the specified control.

Do not call the EndDialog function from the hook procedure. Instead, the hook procedure can call the PostMessage function to post a WM_COMMAND message with the IDABORT value to the dialog box procedure. Posting IDABORT closes the dialog box and causes the dialog box function to return FALSE. If you need to know why the hook procedure closed the dialog box, you must provide your own communication mechanism between the hook procedure and your application.

You can subclass the standard controls of the common dialog box. However, the common dialog box procedure may also subclass the controls. Because of this, you should subclass controls when your hook procedure processes the WM_INITDIALOG message. This ensures that your subclass procedure receives the control-specific messages before the subclass procedure set by the dialog box procedure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in commdlg.h.
Import Library: User-defined.

See Also

Common Dialog Box Library Overview, Common Dialog Box Functions, EndDialog, PostMessage, PrintDlg, PRINTDLG, WM_INITDIALOG, WM_CTLCOLORDLG


ReplaceText

The ReplaceText function creates a system-defined modeless dialog box that lets the user specify a string to search for and a replacement string, as well as options to control the find and replace operations.

HWND ReplaceText(
  LPFINDREPLACE lpfr   // pointer to structure with initialization
                       // data
);

Parameters

lpfr
Pointer to a FINDREPLACE structure that contains information used to initialize the dialog box. The dialog box uses this structure to send information about the user's input to your application. For more information, see the following Remarks section.

Return Values

If the function succeeds, the return value is the window handle to the dialog box. You can use the window handle to communicate with the dialog box or close it.

If the function fails, the return value is NULL. To get extended error information, call the CommDlgExtendedError function, which can return one of the following error codes:

CDERR_FINDRESFAILURE | CDERR_MEMLOCKFAILURE
CDERR_INITIALIZATION | CDERR_NOHINSTANCE
CDERR_LOADRESFAILURE | CDERR_NOHOOK
CDERR_LOADSTRFAILURE | CDERR_NOTEMPLATE
CDERR_LOCKRESFAILURE | CDERR_STRUCTSIZE
CDERR_MEMALLOCFAILURE | FRERR_BUFFERLENGTHZERO

Remarks

The ReplaceText function does not perform a text replacement operation. Instead, the dialog box sends FINDMSGSTRING registered messages to the window procedure of the owner window of the dialog box. When you create the dialog box, the hwndOwner member of the FINDREPLACE structure identifies the owner window.

Before calling ReplaceText, you must call the RegisterWindowMessage function to get the identifier for the FINDMSGSTRING message. The dialog box procedure uses this identifier to send messages when the user clicks the Find Next, Replace, or Replace All buttons, or when the dialog box is closing. The lParam parameter of a FINDMSGSTRING message contains a pointer to the FINDREPLACE structure. The Flags member of this structure indicates the event that caused the message. Other members of the structure indicate the user's input.

If you create a Replace dialog box, you must also use the IsDialogMessage function in the main message loop of your application to ensure that the dialog box correctly processes keyboard input, such as the tab and esc keys. The IsDialogMessage function returns a value that indicates whether the Replace dialog box processed the message.

You can provide an FRHookProc hook procedure for a Replace dialog box. The hook procedure can process messages sent to the dialog box. To enable a hook procedure, set the FR_ENABLEHOOK flag in the Flags member of the FINDREPLACE structure and specify the address of the hook procedure in the lpfnHook member.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.
Import Library: Use comdlg32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Common Dialog Box Library Overview, Common Dialog Box Functions, CommDlgExtendedError, FINDREPLACE, FRHookProc, IsDialogMessage, RegisterWindowMessage, WM_CTLCOLORDLG


SetupHookProc

The SetupHookProc hook procedure is an application-defined or library-defined callback function used with the PrintDlg function. The hook procedure receives messages or notifications intended for the default dialog box procedure of the Print Setup common dialog box.

The LPSETUPHOOKPROC type defines a pointer to this callback function. SetupHookProc is a placeholder for the application-defined or library-defined function name.

UINT CALLBACK SetupHookProc(
  HWND hdlg,      // handle to the dialog box window
  UINT uiMsg,     // message identifier
  WPARAM wParam,  // message parameter
  LPARAM lParam   // message parameter
);

Parameters

hdlg
Handle to the Print Setup common dialog box window for which the message is intended.
uiMsg
Identifies the message being received.
wParam
Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.
lParam
Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.

Return Values

If the hook procedure returns zero, the default dialog box procedure processes the message.

If the hook procedure returns a nonzero value, the default dialog box procedure ignores the message.

Remarks

The Print Setup dialog box has been superseded by the Page Setup dialog box, which should be used by new applications. However, for compatibility, the PrintDlg function continues to support display of the Print Setup dialog box. You can provide a SetupHookProc hook procedure for the Print Setup dialog box to process messages or notifications intended for the dialog box procedure.

To enable the hook procedure, use the PRINTDLG structure that you passed to the dialog creation function. Specify the address of the hook procedure in the lpfnSetupHook member and specify the PD_ENABLESETUPHOOK flag in the Flags member.

The default dialog box procedure processes the WM_INITDIALOG message before passing it to the hook procedure. For all other messages, the hook procedure receives the message first. Then, the return value of the hook procedure determines whether the default dialog procedure processes the message or ignores it.

If the hook procedure processes the WM_CTLCOLORDLG message, it must return a valid brush handle for painting the background of the dialog box. In general, if the hook procedure processes any WM_CTLCOLOR* message, it must return a valid brush handle for painting the background of the specified control.

Do not call the EndDialog function from the hook procedure. Instead, the hook procedure can call the PostMessage function to post a WM_COMMAND message with the IDABORT value to the dialog box procedure. Posting IDABORT closes the dialog box and causes the dialog box function to return FALSE. If you need to know why the hook procedure closed the dialog box, you must provide your own communication mechanism between the hook procedure and your application.

You can subclass the standard controls of the common dialog box. However, the common dialog box procedure may also subclass the controls. Because of this, you should subclass controls when your hook procedure processes the WM_INITDIALOG message. This ensures that your subclass procedure receives the control-specific messages before the subclass procedure set by the dialog box procedure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.
Import Library: User-defined.

See Also

Common Dialog Box Library Overview, Common Dialog Box Functions, EndDialog, PrintDlg, PRINTDLG, PostMessage, WM_INITDIALOG, WM_CTLCOLORDLG


Common Dialog Box Structures

The following structures are used with common dialog boxes.

CHOOSECOLOR
CHOOSEFONT
DEVNAMES
FINDREPLACE
OPENFILENAME
OFNOTIFY
PAGESETUPDLG
PRINTDLG
PRINTDLGEX
PRINTPAGERANGE


CHOOSECOLOR

The CHOOSECOLOR structure contains information the ChooseColor function uses to initialize the Color common dialog box. After the user closes the dialog box, the system returns information about the user's selection in this structure.

typedef struct {   // cc
    DWORD        lStructSize;
    HWND         hwndOwner;
    HWND         hInstance;
    COLORREF     rgbResult;
    COLORREF*    lpCustColors;
    DWORD        Flags;
    LPARAM       lCustData;
    LPCCHOOKPROC lpfnHook;
    LPCTSTR      lpTemplateName;
} CHOOSECOLOR;

Members

lStructSize
Specifies the length, in bytes, of the structure.
hwndOwner
Identifies the window that owns the dialog box. This member can be any valid window handle, or it can be NULL if the dialog box has no owner.
hInstance
If the CC_ENABLETEMPLATEHANDLE flag is set in the Flags member, hInstance is the handle of a memory object containing a dialog box template. If the CC_ENABLETEMPLATE flag is set, hInstance identifies a module that contains a dialog box template named by the lpTemplateName member. If neither CC_ENABLETEMPLATEHANDLE nor CC_ENABLETEMPLATE is set, this member is ignored.
rgbResult
If the CC_RGBINIT flag is set, rgbResult specifies the color initially selected when the dialog box is created. If the specified color value is not among the available colors, the system selects the nearest solid color available. If rgbResult is zero or CC_RGBINIT is not set, the initially selected color is black. If the user clicks the OK button, rgbResult specifies the user's color selection.
lpCustColors
Pointer to an array of 16 COLORREF values that contain red, green, blue (RGB) values for the custom color boxes in the dialog box. If the user modifies these colors, the system updates the array with the new RGB values. To preserve new custom colors between calls to the ChooseColor function, you should allocate static memory for the array.
Flags
A set of bit flags that you can use to initialize the Color common dialog box. When the dialog box returns, it sets these flags to indicate the user's input. This member can be a combination of the following flags:
Flag | Meaning
CC_ANYCOLOR | Causes the dialog box to display all available colors in the set of basic colors.
CC_ENABLEHOOK | Enables the hook procedure specified in the lpfnHook member of this structure. This flag is used only to initialize the dialog box.
CC_ENABLETEMPLATE | Indicates that the hInstance and lpTemplateName members specify a dialog box template to use in place of the default template. This flag is used only to initialize the dialog box.
CC_ENABLETEMPLATEHANDLE | Indicates that the hInstance member identifies a data block that contains a preloaded dialog box template. The system ignores the lpTemplateName member if this flag is specified. This flag is used only to initialize the dialog box.
CC_FULLOPEN | Causes the dialog box to display the additional controls that allow the user to create custom colors. If this flag is not set, the user must click the Define Custom Color button to display the custom color controls.
CC_PREVENTFULLOPEN | Disables the Define Custom Colors button.
CC_RGBINIT | Causes the dialog box to use the color specified in the rgbResult member as the initial color selection.
CC_SHOWHELP | Causes the dialog box to display the Help button. The hwndOwner member must specify the window to receive the HELPMSGSTRING registered messages that the dialog box sends when the user clicks the Help button.
CC_SOLIDCOLOR | Causes the dialog box to display only solid colors in the set of basic colors.

lCustData
Specifies application-defined data that the system passes to the hook procedure identified by the lpfnHook member. When the system sends the WM_INITDIALOG message to the hook procedure, the message's lParam parameter is a pointer to the CHOOSECOLOR structure specified when the dialog was created. The hook procedure can use this pointer to get the lCustData value.
lpfnHook
Pointer to a CCHookProc hook procedure that can process messages intended for the dialog box. This member is ignored unless the CC_ENABLEHOOK flag is set in the Flags member.
lpTemplateName
Pointer to a null-terminated string that names the dialog box template resource in the module identified by the hInstance member. This template is substituted for the standard dialog box template. For numbered dialog box resources, lpTemplateName can be a value returned by the MAKEINTRESOURCE macro. This member is ignored unless the CC_ENABLETEMPLATE flag is set in the Flags member.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in commdlg.h.
Unicode: Defined as Unicode and ANSI structures.

See Also

Common Dialog Box Library Overview, Common Dialog Box Structures, CCHookProc, ChooseColor, MAKEINTRESOURCE, WM_INITDIALOG


CHOOSEFONT

The CHOOSEFONT structure contains information that the ChooseFont function uses to initialize the Font common dialog box. After the user closes the dialog box, the system returns information about the user's selection in this structure.

typedef struct {    // cf
    DWORD        lStructSize;
    HWND         hwndOwner;
    HDC          hDC;
    LPLOGFONT    lpLogFont;
    INT          iPointSize;
    DWORD        Flags;
    DWORD        rgbColors;
    LPARAM       lCustData;
    LPCFHOOKPROC lpfnHook;
    LPCTSTR      lpTemplateName;
    HINSTANCE    hInstance;
    LPTSTR       lpszStyle;
    WORD         nFontType;
    WORD         ___MISSING_ALIGNMENT__;
    INT          nSizeMin;
    INT          nSizeMax;
} CHOOSEFONT;

Members

lStructSize
Specifies the length, in bytes, of the structure.
hwndOwner
Identifies the window that owns the dialog box. This member can be any valid window handle, or it can be NULL if the dialog box has no owner.
hDC
Identifies the device context (or information context) of the printer whose fonts will be listed in the dialog box. This member is used only if the Flags member specifies the CF_PRINTERFONTS or CF_BOTH flag; otherwise, this member is ignored.
lpLogFont
Pointer to a LOGFONT structure. If you set the CF_INITTOLOGFONTSTRUCT flag in the Flags member and initialize the LOGFONT members, the ChooseFont function initializes the dialog box with a font that is the closest possible match. If the user clicks the OK button, ChooseFont sets the members of the LOGFONT structure based on the user's selections.
iPointSize
Specifies the size of the selected font, in units of 1/10 of a point. The ChooseFont function sets this value after the user closes the dialog box.
Flags
A set of bit flags that you can use to initialize the Font common dialog box. When the dialog box returns, it sets these flags to indicate the user's input. This member can be a combination of the following flags:
Flag | Meaning
CF_APPLY | Causes the dialog box to display the Apply button. You should provide a hook procedure to process WM_COMMAND messages for the Apply button. The hook procedure can send the WM_CHOOSEFONT_GETLOGFONT message to the dialog box to retrieve the address of the LOGFONT structure that contains the current selections for the font.
CF_ANSIONLY | This flag is obsolete. To limit font selections to all scripts except those that use the OEM or Symbol character sets, use CF_SCRIPTSONLY. To get the Windows 3.1 CF_ANSIONLY behavior, use CF_SELECTSCRIPT and specify ANSI_CHARSET in the lfCharSet member of the LOGFONT structure pointed to by lpLogFont.
CF_BOTH | Causes the dialog box to list the available printer and screen fonts. The hDC member identifies the device context (or information context) associated with the printer. This flag is a combination of the CF_SCREENFONTS and CF_PRINTERFONTS flags.
CF_TTONLY | Specifies that ChooseFont should only enumerate and allow the selection of TrueType fonts.
CF_EFFECTS | Causes the dialog box to display the controls that allow the user to specify strikeout, underline, and text color options. If this flag is set, you can use the rgbColors member to specify the initial text color. You can use the lfStrikeOut and lfUnderline members of the LOGFONT structure pointed to by lpLogFont to specify the initial settings of the strikeout and underline check boxes. ChooseFont can use these members to return the user's selections.
CF_ENABLEHOOK | Enables the hook procedure specified in the lpfnHook member of this structure.
CF_ENABLETEMPLATE | Indicates that the hInstance and lpTemplateName members specify a dialog box template to use in place of the default template.
CF_ENABLETEMPLATEHANDLE | Indicates that the hInstance member identifies a data block that contains a preloaded dialog box template. The system ignores the lpTemplateName member if this flag is specified.
CF_FIXEDPITCHONLY | Specifies that ChooseFont should select only fixed-pitch fonts.
CF_FORCEFONTEXIST | Specifies that ChooseFont should indicate an error condition if the user attempts to select a font or style that does not exist.
CF_INITTOLOGFONTSTRUCT | Specifies that ChooseFont should use the LOGFONT structure pointed to by the lpLogFont member to initialize the dialog box controls.
CF_LIMITSIZE | Specifies that ChooseFont should select only font sizes within the range specified by the nSizeMin and nSizeMax members.
CF_NOOEMFONTS | Same as the CF_NOVECTORFONTS flag.
CF_NOFACESEL | When using a LOGFONT structure to initialize the dialog box controls, use this flag to selectively prevent the dialog box from displaying an initial selection for the font name combo box. This is useful when there is no single font name that applies to the text selection.
CF_NOSCRIPTSEL | Disables the Script combo box. When this flag is set, the lfCharSet member of the LOGFONT structure is set to DEFAULT_CHARSET when ChooseFont returns. This flag is used only to initialize the dialog box.
CF_NOSTYLESEL | When using a LOGFONT structure to initialize the dialog box controls, use this flag to selectively prevent the dialog box from displaying an initial selection for the font style combo box. This is useful when there is no single font style that applies to the text selection.
CF_NOSIZESEL | When using a LOGFONT structure to initialize the dialog box controls, use this flag to selectively prevent the dialog box from displaying an initial selection for the font size combo box. This is useful when there is no single font size that applies to the text selection.
CF_NOSIMULATIONS | Specifies that ChooseFont should not allow graphics device interface (GDI) font simulations.
CF_NOVECTORFONTS | Specifies that ChooseFont should not allow vector font selections.
CF_NOVERTFONTS | Causes the Font dialog box to list only horizontally oriented fonts.
CF_PRINTERFONTS | Causes the dialog box to list only the fonts supported by the printer associated with the device context (or information context) identified by the hDC member.
CF_SCALABLEONLY | Specifies that ChooseFont should allow only the selection of scalable fonts. (Scalable fonts include vector fonts, scalable printer fonts, TrueType fonts, and fonts scaled by other technologies.)
CF_SCREENFONTS | Causes the dialog box to list only the screen fonts supported by the system.
CF_SCRIPTSONLY | Specifies that ChooseFont should allow selection of fonts for all non-OEM and Symbol character sets, as well as the ANSI character set. This supersedes the CF_ANSIONLY value.
CF_SELECTSCRIPT | When specified on input, only fonts with the character set identified in the lfCharSet member of the LOGFONT structure are displayed. The user will not be allowed to change the character set specified in the Scripts combo box.
CF_SHOWHELP | Causes the dialog box to display the Help button. The hwndOwner member must specify the window to receive the HELPMSGSTRING registered messages that the dialog box sends when the user clicks the Help button.
CF_USESTYLE | Specifies that the lpszStyle member points to a buffer that contains style data that ChooseFont should use to initialize the Font Style combo box. When the user closes the dialog box, ChooseFont copies style data for the user's selection to this buffer.
CF_WYSIWYG | Specifies that ChooseFont should allow only the selection of fonts available on both the printer and the display. If this flag is specified, the CF_BOTH and CF_SCALABLEONLY flags should also be specified.

rgbColors
If the CF_EFFECTS flag is set, rgbColors specifies the initial text color. When ChooseFont returns successfully, this member contains the RGB value of the text color the user selected.
lCustData
Specifies application-defined data that the system passes to the hook procedure identified by the lpfnHook member. When the system sends the WM_INITDIALOG message to the hook procedure, the message's lParam parameter is a pointer to the CHOOSEFONT structure specified when the dialog was created. The hook procedure can use this pointer to get the lCustData value.
lpfnHook
Pointer to a CFHookProc hook procedure that can process messages intended for the dialog box. This member is ignored unless the CF_ENABLEHOOK flag is set in the Flags member.
lpTemplateName
Pointer to a null-terminated string that names the dialog box template resource in the module identified by the hInstance member. This template is substituted for the standard dialog box template. For numbered dialog box resources, lpTemplateName can be a value returned by the MAKEINTRESOURCE macro. This member is ignored unless the CF_ENABLETEMPLATE flag is set in the Flags member.
hInstance
If the CF_ENABLETEMPLATEHANDLE flag is set in the Flags member, hInstance is the handle of a memory object containing a dialog box template. If the CF_ENABLETEMPLATE flag is set, hInstance identifies a module that contains a dialog box template named by the lpTemplateName member. If neither CF_ENABLETEMPLATEHANDLE nor CF_ENABLETEMPLATE is set, this member is ignored.
lpszStyle
Pointer to a buffer that contains style data. If the CF_USESTYLE flag is specified, ChooseFont uses the data in this buffer to initialize the font style combo box. When the user closes the dialog box, ChooseFont copies the string in the font style combo box into this buffer.
nFontType
Specifies the type of the selected font when ChooseFont returns. This member can be a combination of the following values:
Value | Meaning
BOLD_FONTTYPE | The font weight is bold. This information is duplicated in the lfWeight member of the LOGFONT structure and is equivalent to FW_BOLD.
ITALIC_FONTTYPE | The italic font attribute is set. This information is duplicated in the lfItalic member of the LOGFONT structure.
PRINTER_FONTTYPE | The font is a printer font.
REGULAR_FONTTYPE | The font weight is normal. This information is duplicated in the lfWeight member of the LOGFONT structure and is equivalent to FW_REGULAR.
SCREEN_FONTTYPE | The font is a screen font.
SIMULATED_FONTTYPE | The font is simulated by the graphics device interface (GDI).

nSizeMin
Specifies the minimum point size a user can select. ChooseFont recognizes this member only if the CF_LIMITSIZE flag is specified.
nSizeMax
Specifies the maximum point size a user can select. ChooseFont recognizes this member only if the CF_LIMITSIZE flag is specified.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.
Unicode: Defined as Unicode and ANSI structures.

See Also

Common Dialog Box Library Overview, Common Dialog Box Structures, ChooseFont, LOGFONT, MAKEINTRESOURCE


DEVNAMES

The DEVNAMES structure contains strings that identify the driver, device, and output port names for a printer. The PrintDlg function uses these strings to initialize members in the system-defined Print dialog box. When the user closes the dialog box, information about the selected printer is returned in this structure.

typedef struct tagDEVNAMES { // dvnm
    WORD wDriverOffset;
    WORD wDeviceOffset;
    WORD wOutputOffset;
    WORD wDefault;
    // driver, device, and port name strings follow wDefault
} DEVNAMES;

Members

wDriverOffset
(Input/Output) Specifies the offset in characters from the beginning of this structure to a null-terminated string that contains the filename (without the extension) of the device driver. On input, this string is used to determine the printer to display initially in the dialog box.
wDeviceOffset
(Input/Output) Specifies the offset in characters from the beginning of this structure to the null-terminated string (maximum of 32 bytes including the null) that contains the name of the device. This string must be identical to the dmDeviceName member of the DEVMODE structure.
wOutputOffset
(Input/Output) Specifies the offset in characters from the beginning of this structure to the null-terminated string that contains the device name for the physical output medium (output port).
wDefault
Specifies whether the strings contained in the DEVNAMES structure identify the default printer. This string is used to verify that the default printer has not changed since the last print operation. If any of the strings do not match, a warning message is displayed informing the user that the document may need to be reformatted.

On output, the wDefault member is changed only if the Print Setup dialog box was displayed and the user chose the OK button. The DN_DEFAULTPRN flag is used if the default printer was selected. If a specific printer is selected, the flag is not used. All other flags in this member are reserved for internal use by the Print Dialog dialog box procedure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Structures, DEVMODE, PrintDlg


FINDREPLACE

The FINDREPLACE structure contains information that the FindText and ReplaceText functions use to initialize the Find and Replace common dialog boxes. The FINDMSGSTRING registered message uses this structure to pass the user's search or replacement input to the owner window of a Find or Replace common dialog box.

typedef struct {    // fr
    DWORD        lStructSize;
    HWND         hwndOwner;
    HINSTANCE    hInstance;
    DWORD        Flags;
    LPTSTR        lpstrFindWhat;
    LPTSTR        lpstrReplaceWith;
    WORD         wFindWhatLen;
    WORD         wReplaceWithLen;
    LPARAM        lCustData;
    LPFRHOOKPROC lpfnHook;
    LPCTSTR       lpTemplateName;
} FINDREPLACE;

Members

lStructSize
Specifies the length, in bytes, of the structure.
hwndOwner
Identifies the window that owns the dialog box. The window procedure of the specified window receives FINDMSGSTRING messages from the dialog box. This member can be any valid window handle, but it must not be NULL.
hInstance
If the FR_ENABLETEMPLATEHANDLE flag is set in the Flags member, hInstance is the handle of a memory object containing a dialog box template. If the FR_ENABLETEMPLATE flag is set, hInstance identifies a module that contains a dialog box template named by the lpTemplateName member. If neither flag is set, this member is ignored.
Flags
A set of bit flags that you can use to initialize the dialog box. The dialog box sets these flags when it sends the FINDMSGSTRING registered message to indicate the user's input. This member can be a combination of the following flags:
Flag Meaning
FR_DIALOGTERM
If set in a FINDMSGSTRING message, indicates that the dialog box is closing. When you receive a message with this flag set, the dialog box window handle returned by the FindText or ReplaceText function is no longer valid.
FR_DOWN
If set, the Down button of the direction radio buttons in a Find dialog box is selected indicating that you should search from the current location to the end of the document. If not set, the Up button is selected so you should search to the beginning of the document. You can set this flag to initialize the dialog box. If set in a FINDMSGSTRING message, indicates the user's selection.
FR_ENABLEHOOK
Enables the hook function specified in the lpfnHook member. This flag is used only to initialize the dialog box.
FR_ENABLETEMPLATE
Indicates that the hInstance and lpTemplateName members specify a dialog box template to use in place of the default template. This flag is used only to initialize the dialog box.
FR_ENABLETEMPLATEHANDLE
Indicates that the hInstance member identifies a data block that contains a preloaded dialog box template. The system ignores the lpTemplateName member if this flag is specified.
FR_FINDNEXT
If set in a FINDMSGSTRING message, indicates that the user clicked the Find Next button in a Find or Replace dialog box. The lpstrFindWhat member specifies the string to search for.
FR_HIDEUPDOWN
If set when initializing a Find dialog box, hides the search direction radio buttons.
FR_HIDEMATCHCASE
If set when initializing a Find or Replace dialog box, hides the Match Case check box.
FR_HIDEWHOLEWORD
If set when initializing a Find or Replace dialog box, hides the Match Whole Word Only check box.
FR_MATCHCASE
If set, the Match Case check box is checked indicating that the search should be case-sensitive. If not set, the check box is unchecked so the search should be case-insensitive. You can set this flag to initialize the dialog box. If set in a FINDMSGSTRING message, indicates the user's selection.
FR_NOMATCHCASE
If set when initializing a Find or Replace dialog box, disables the Match Case check box.
FR_NOUPDOWN
If set when initializing a Find dialog box, disables the search direction radio buttons.
FR_NOWHOLEWORD
If set when initializing a Find or Replace dialog box, disables the Whole Word check box.
FR_REPLACE
If set in a FINDMSGSTRING message, indicates that the user clicked the Replace button in a Replace dialog box. The lpstrFindWhat member specifies the string to be replaced and the lpstrReplaceWith member specifies the replacement string.
FR_REPLACEALL
If set in a FINDMSGSTRING message, indicates that the user clicked the Replace All button in a Replace dialog box. The lpstrFindWhat member specifies the string to be replaced and the lpstrReplaceWith member specifies the replacement string.
FR_SHOWHELP
Causes the dialog box to display the Help button. The hwndOwner member must specify the window to receive the HELPMSGSTRING registered messages that the dialog box sends when the user clicks the Help button.
FR_WHOLEWORD
If set, the Match Whole Word Only check box is checked indicating that you should search only for whole words that match the search string. If not set, the check box is unchecked so you should also search for word fragments that match the search string. You can set this flag to initialize the dialog box. If set in a FINDMSGSTRING message, indicates the user's selection.

lpstrFindWhat
Pointer to a buffer that a FINDMSGSTRING message uses to pass the null terminated search string that the user typed in the Find What edit control. You must dynamically allocate the buffer or use a global or static array so it does not go out of scope before the dialog box closes. The buffer should be at least 80 characters long. If the buffer contains a string when you initialize the dialog box, the string is displayed in the Find What edit control.

If a FINDMSGSTRING message specifies the FR_FINDNEXT flag, lpstrFindWhat contains the string to search for. The FR_DOWN, FR_WHOLEWORD, and FR_MATCHCASE flags indicate the direction and type of search. If a FINDMSGSTRING message specifies the FR_REPLACE or FR_REPLACE flags, lpstrFindWhat contains the string to be replaced.

lpstrReplaceWith
Pointer to a buffer that a FINDMSGSTRING message uses to pass the null terminated replacement string that the user typed in the Replace With edit control. You must dynamically allocate the buffer or use a global or static array so it does not go out of scope before the dialog box closes. If the buffer contains a string when you initialize the dialog box, the string is displayed in the Replace With edit control.

If a FINDMSGSTRING message specifies the FR_REPLACE or FR_REPLACEALL flags, lpstrReplaceWith contains the replacement string .

The FindText function ignores this member.

wFindWhatLen
Specifies the length, in bytes, of the buffer pointed to by the lpstrFindWhat member.
wReplaceWithLen
Specifies the length, in bytes, of the buffer pointed to by the lpstrReplaceWith member.
lCustData
Specifies application-defined data that the system passes to the hook procedure identified by the lpfnHook member. When the system sends the WM_INITDIALOG message to the hook procedure, the message's lParam parameter is a pointer to the FINDREPLACE structure specified when the dialog was created. The hook procedure can use this pointer to get the lCustData value.
lpfnHook
Pointer to an FRHookProc hook procedure that can process messages intended for the dialog box. This member is ignored unless the FR_ENABLEHOOK flag is set in the Flags member.

If the hook procedure returns FALSE in response to the WM_INITDIALOG message, the hook procedure must display the dialog box or else the dialog box will not be shown. To do this, first perform any other paint operations, and then call the ShowWindow and UpdateWindow functions.

lpTemplateName
Pointer to a null-terminated string that names the dialog box template resource in the module identified by the hInstance member. This template is substituted for the standard dialog box template. For numbered dialog box resources, this can be a value returned by the MAKEINTRESOURCE macro. This member is ignored unless the FR_ENABLETEMPLATE flag is set in the Flags member.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.
Unicode: Defined as Unicode and ANSI structures.

See Also

Common Dialog Box Library Overview, Common Dialog Box Structures, FindText, FRHookProc, MAKEINTRESOURCE, ReplaceText, ShowWindow, UpdateWindow, WM_INITDIALOG


OFNOTIFY

The OFNOTIFY structure contains information about the WM_NOTIFY message sent to a hook procedure from an Explorer-style Open or Save As dialog box. The address of the OFNOTIFY structure is passed as the lParam parameter of the WM_NOTIFY message.

typedef struct _OFNOTIFY {  // on
    NMHDR          hdr;
    LPOPENFILENAME lpOFN;
    LPTSTR         pszFile;
} OFNOTIFY, FAR *LPOFNOTIFY;

Members

hdr
Specifies an NMHDR structure. The code member of the NMHDR structure can be one of the following notification codes that identify the message being sent: CDN_FILEOK, CDN_FOLDERCHANGE, CDN_HELP, CDN_INITDONE, CDN_SELCHANGE, CDN_SHAREVIOLATION, CDN_TYPECHANGE.
lpOFN
Pointer to the OPENFILENAME structure that was specified when the Open or Save As dialog box was created. For some of the notification messages, this structure contains additional information about the event that caused the notification.
pszFile
Pointer to the filename for which a network sharing violation has occurred. This member is valid only with the CDN_SHAREVIOLATION notification message.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in commdlg.h.
Unicode: Defined as Unicode and ANSI structures.

See Also

Common Dialog Box Library Overview, Common Dialog Box Structures, CDN_FILEOK, CDN_FOLDERCHANGE, CDN_HELP, CDN_INITDONE, CDN_SELCHANGE, CDN_SHAREVIOLATION, CDN_TYPECHANGE, NMHDR, OPENFILENAME


OPENFILENAME

The OPENFILENAME structure contains information that the GetOpenFileName and GetSaveFileName functions use to initialize an Open or Save As common dialog box. After the user closes the dialog box, the system returns information about the user's selection in this structure.

typedef struct tagOFN { // ofn
    DWORD         lStructSize;
    HWND          hwndOwner;
    HINSTANCE     hInstance;
    LPCTSTR       lpstrFilter;
    LPTSTR        lpstrCustomFilter;
    DWORD         nMaxCustFilter;
    DWORD         nFilterIndex;
    LPTSTR        lpstrFile;
    DWORD         nMaxFile;
    LPTSTR        lpstrFileTitle;
    DWORD         nMaxFileTitle;
    LPCTSTR       lpstrInitialDir;
    LPCTSTR       lpstrTitle;
    DWORD         Flags;
    WORD          nFileOffset;
    WORD          nFileExtension;
    LPCTSTR       lpstrDefExt;
    DWORD         lCustData;
    LPOFNHOOKPROC lpfnHook;
    LPCTSTR       lpTemplateName;
} OPENFILENAME;

Members

lStructSize
Specifies the length, in bytes, of the structure.
hwndOwner
Identifies the window that owns the dialog box. This member can be any valid window handle, or it can be NULL if the dialog box has no owner.
hInstance
If the OFN_ENABLETEMPLATEHANDLE flag is set in the Flags member, hInstance is the handle of a memory object containing a dialog box template. If the OFN_ENABLETEMPLATE flag is set, hInstance identifies a module that contains a dialog box template named by the lpTemplateName member. If neither flag is set, this member is ignored.

If the OFN_EXPLORER flag is set, the system uses the specified template to create a dialog box that is a child of the default Explorer-style dialog box. If the OFN_EXPLORER flag is not set, the system uses the template to create an old-style dialog box that replaces the default dialog box.

lpstrFilter
Pointer to a buffer containing pairs of null-terminated filter strings. The last string in the buffer must be terminated by two NULL characters.

The first string in each pair is a display string that describes the filter (for example, "Text Files"), and the second string specifies the filter pattern (for example, "*.TXT"). To specify multiple filter patterns for a single display string, use a semicolon to separate the patterns (for example, "*.TXT;*.DOC;*.BAK"). A pattern string can be a combination of valid filename characters and the asterisk (*) wildcard character. Do not include spaces in the pattern string.

The system does not change the order of the filters. It displays them in the File Types combo box in the order specified in lpstrFilter.

If lpstrFilter is NULL, the dialog box does not display any filters.

lpstrCustomFilter
Pointer to a static buffer that contains a pair of null-terminated filter strings for preserving the filter pattern chosen by the user. The first string is your display string that describes the custom filter, and the second string is the filter pattern selected by the user. The first time your application creates the dialog box, you specify the first string, which can be any nonempty string. When the user selects a file, the dialog box copies the current filter pattern to the second string. The preserved filter pattern can be one of the patterns specified in the lpstrFilter buffer, or it can be a filter pattern typed by the user. The system uses the strings to initialize the user-defined file filter the next time the dialog box is created. If the nFilterIndex member is zero, the dialog box uses the custom filter.

If this member is NULL, the dialog box does not preserve user-defined filter patterns.

If this member is not NULL, the value of the nMaxCustFilter member must specify the size, in bytes (ANSI version) or 16-bit characters (Unicode version), of the lpstrCustomFilter buffer.

nMaxCustFilter
Specifies the size, in bytes or characters, of the buffer identified by lpstrCustomFilter. This buffer should be at least 40 characters long. This member is ignored if lpstrCustomFilter is NULL or points to a NULL string.
nFilterIndex
Specifies the index of the currently selected filter in the File Types control. The buffer pointed to by lpstrFilter contains pairs of strings that define the filters. The first pair of strings has an index value of 1, the second pair 2, and so on. An index of zero indicates the custom filter specified by lpstrCustomFilter. You can specify an index on input to indicate the initial filter description and filter pattern for the dialog box. When the user selects a file, nFilterIndex returns the index of the currently displayed filter.

If nFilterIndex is zero and lpstrCustomFilter is NULL, the system uses the first filter in the lpstrFilter buffer. If all three members are zero or NULL, the system does not use any filters and does not show any files in the file list control of the dialog box.

lpstrFile
Pointer to a buffer that contains a filename used to initialize the File Name edit control. The first character of this buffer must be NULL if initialization is not necessary. When the GetOpenFileName or GetSaveFileName function returns successfully, this buffer contains the drive designator, path, filename, and extension of the selected file.

If the OFN_ALLOWMULTISELECT flag is set and the user selects multiple files, the buffer contains the current directory followed by the filenames of the selected files. For Explorer-style dialog boxes, the directory and filename strings are NULL separated, with an extra NULL character after the last filename. For old-style dialog boxes, the strings are space separated and the function uses short filenames for filenames with spaces. You can use the FindFirstFile function to convert between long and short filenames.

If the buffer is too small, the function returns FALSE and the CommDlgExtendedError function returns FNERR_BUFFERTOOSMALL. In this case, the first two bytes of the lpstrFile buffer contain the required size, in bytes or characters.

nMaxFile
Specifies the size, in bytes (ANSI version) or 16-bit characters (Unicode version), of the buffer pointed to by lpstrFile. The GetOpenFileName and GetSaveFileName functions return FALSE if the buffer is too small to contain the file information. The buffer should be at least 256 characters long.
lpstrFileTitle
Pointer to a buffer that receives the filename and extension (without path information) of the selected file. This member can be NULL.
nMaxFileTitle
Specifies the size, in bytes (ANSI version) or 16-bit characters (Unicode version), of the buffer pointed to by lpstrFileTitle. This member is ignored if lpstrFileTitle is NULL.
lpstrInitialDir
Pointer to a string that specifies the initial file directory.

Windows NT 5.0 and later; Windows 98 and later:

If lpstrInitalDir is NULL and the current directory contains any files of the specified filter types, the initial directory is the current directory.

If lpstrInitalDir is NULL and the current directory does not contain any files of the specified filter types, the initial directory is the personal files directory of the current user. To specify the current user's personal files directory as the initial directory, set lpstrInitialDir to the path returned by calling the SHGetSpecialFolderLocation function with the CSIDL_PERSONAL flag.

Earlier versions of Windows and Windows NT:

If lpstrInitalDir is NULL, the initial directory is the current directory.

lpstrTitle
Pointer to a string to be placed in the title bar of the dialog box. If this member is NULL, the system uses the default title (that is, Save As or Open).
Flags
A set of bit flags you can use to initialize the dialog box. When the dialog box returns, it sets these flags to indicate the user's input. This member can be a combination of the following flags:
Flag Meaning
OFN_ALLOWMULTISELECT
Specifies that the File Name list box allows multiple selections. If you also set the OFN_EXPLORER flag, the dialog box uses the Explorer-style user interface; otherwise, it uses the old-style user interface.

If the user selects more than one file, the lpstrFile buffer returns the path to the current directory followed by the filenames of the selected files. The nFileOffset member is the offset, in bytes or characters, to the first filename, and the nFileExtension member is not used. For Explorer-style dialog boxes, the directory and filename strings are NULL separated, with an extra NULL character after the last filename. This format enables the Explorer-style dialogs to return long filenames that include spaces. For old-style dialog boxes, the directory and filename strings are separated by spaces and the function uses short filenames for filenames with spaces. You can use the FindFirstFile function to convert between long and short filenames.

If you specify a custom template for an old-style dialog box, the definition of the File Name list box must contain the LBS_EXTENDEDSEL value.

OFN_CREATEPROMPT
If the user specifies a file that does not exist, this flag causes the dialog box to prompt the user for permission to create the file. If the user chooses to create the file, the dialog box closes and the function returns the specified name; otherwise, the dialog box remains open. If you use this flag with the OFN_ALLOWMULTISELECT flag, the dialog box allows the user to specify only one nonexistent file.
OFN_ENABLEHOOK
Enables the hook function specified in the lpfnHook member.
OFN_ENABLESIZING
Windows NT 5.0, Windows 98: Enables the Explorer-style dialog box to be resized using either the mouse or the keyboard. By default, the Explorer-style Open and Save As dialog boxes allow the dialog box to be resized regardless of whether this flag is set. This flag is necessary only if you provide a hook procedure or custom template. The old-style dialog box does not permit resizing.
OFN_ENABLETEMPLATE
Indicates that the lpTemplateName member points to the name of a dialog template resource in the module identified by the hInstance member.

If the OFN_EXPLORER flag is set, the system uses the specified template to create a dialog box that is a child of the default Explorer-style dialog box. If the OFN_EXPLORER flag is not set, the system uses the template to create an old-style dialog box that replaces the default dialog box.
OFN_ENABLETEMPLATEHANDLE
Indicates that the hInstance member identifies a data block that contains a preloaded dialog box template. The system ignores the lpTemplateName if this flag is specified.

If the OFN_EXPLORER flag is set, the system uses the specified template to create a dialog box that is a child of the default Explorer-style dialog box. If the OFN_EXPLORER flag is not set, the system uses the template to create an old-style dialog box that replaces the default dialog box.
OFN_EXPLORER
Indicates that any customizations made to the Open or Save As dialog box use the new Explorer-style customization methods. For more information, see Explorer-Style Hook Procedures and Explorer-Style Custom Templates.

By default, the Open and Save As dialog boxes use the Explorer-style user interface regardless of whether this flag is set. This flag is necessary only if you provide a hook procedure or custom template, or set the OFN_ALLOWMULTISELECT flag.

If you want the old-style user interface, omit the OFN_EXPLORER flag and provide a replacement old-style template or hook procedure. If you want the old style but do not need a custom template or hook procedure, simply provide a hook procedure that always returns FALSE.
OFN_EXTENSIONDIFFERENT
Specifies that the user typed a filename extension that differs from the extension specified by lpstrDefExt. The function does not use this flag if lpstrDefExt is NULL.
OFN_FILEMUSTEXIST
Specifies that the user can type only names of existing files in the File Name entry field. If this flag is specified and the user enters an invalid name, the dialog box procedure displays a warning in a message box. If this flag is specified, the OFN_PATHMUSTEXIST flag is also used.
OFN_HIDEREADONLY
Hides the Read Only check box.
OFN_LONGNAMES
For old-style dialog boxes, this flag causes the dialog box to use long filenames. If this flag is not specified, or if the OFN_ALLOWMULTISELECT flag is also set, old-style dialog boxes use short filenames (8.3 format) for filenames with spaces.

Explorer-style dialog boxes ignore this flag and always display long filenames.
OFN_NOCHANGEDIR
Restores the current directory to its original value if the user changed the directory while searching for files.
OFN_NODEREFERENCELINKS
Directs the dialog box to return the path and filename of the selected shortcut (.LNK) file. If this value is not given, the dialog box returns the path and filename of the file referenced by the shortcut
OFN_NOLONGNAMES
For old-style dialog boxes, this flag causes the dialog box to use short filenames (8.3 format).

Explorer-style dialog boxes ignore this flag and always display long filenames.
OFN_NONETWORKBUTTON
Hides and disables the Network button.
OFN_NOREADONLYRETURN
Specifies that the returned file does not have the Read Only check box checked and is not in a write-protected directory.
OFN_NOTESTFILECREATE
Specifies that the file is not created before the dialog box is closed. This flag should be specified if the application saves the file on a create-nonmodify network share. When an application specifies this flag, the library does not check for write protection, a full disk, an open drive door, or network protection. Applications using this flag must perform file operations carefully, because a file cannot be reopened once it is closed.
OFN_NOVALIDATE
Specifies that the common dialog boxes allow invalid characters in the returned filename. Typically, the calling application uses a hook procedure that checks the filename by using the FILEOKSTRING message. If the text box in the edit control is empty or contains nothing but spaces, the lists of files and directories are updated. If the text box in the edit control contains anything else, nFileOffset and nFileExtension are set to values generated by parsing the text. No default extension is added to the text, nor is text copied to the buffer specified by lpstrFileTitle.
If the value specified by nFileOffset is less than zero, the filename is invalid. Otherwise, the filename is valid, and nFileExtension and nFileOffset can be used as if the OFN_NOVALIDATE flag had not been specified.
OFN_OVERWRITEPROMPT
Causes the Save As dialog box to generate a message box if the selected file already exists. The user must confirm whether to overwrite the file.
OFN_PATHMUSTEXIST
Specifies that the user can type only valid paths and filenames. If this flag is used and the user types an invalid path and filename in the File Name entry field, the dialog box function displays a warning in a message box.
OFN_READONLY
Causes the Read Only check box to be checked initially when the dialog box is created. This flag indicates the state of the Read Only check box when the dialog box is closed.
OFN_SHAREAWARE
Specifies that if a call to the OpenFile function fails because of a network sharing violation, the error is ignored and the dialog box returns the selected filename.

If this flag is not set, the dialog box notifies your hook procedure when a network sharing violation occurs for the filename specified by the user. If you set the OFN_EXPLORER flag, the dialog box sends the CDN_SHAREVIOLATION message to the hook procedure. If you do not set OFN_EXPLORER, the dialog box sends the SHAREVISTRING registered message to the hook procedure.

OFN_SHOWHELP
Causes the dialog box to display the Help button. The hwndOwner member must specify the window to receive the HELPMSGSTRING registered messages that the dialog box sends when the user clicks the Help button.

An Explorer-style dialog box sends a CDN_HELP notification message to your hook procedure when the user clicks the Help button.

nFileOffset
Specifies the zero-based offset, in bytes (ANSI version) or 16-bit characters (Unicode version), from the beginning of the path to the filename in the string pointed to by lpstrFile. For example, if lpstrFile points to the following string, "c:\dir1\dir2\file.ext", this member contains the value 13 to indicate the offset of the "file.ext" string.

If the user selects more than one file, nFileOffset is the offset to the first filename.

nFileExtension
Specifies the zero-based offset, in bytes (ANSI version) or 16-bit characters (Unicode version), from the beginning of the path to the filename extension in the string pointed to by lpstrFile. For example, if lpstrFile points to the following string, "c:\dir1\dir2\file.ext", this member contains the value 18. If the user did not type an extension and lpstrDefExt is NULL, this member specifies an offset to the terminating null character. If the user typed "." as the last character in the filename, this member specifies zero.
lpstrDefExt
Points to a buffer that contains the default extension. GetOpenFileName and GetSaveFileName append this extension to the filename if the user fails to type an extension. This string can be any length, but only the first three characters are appended. The string should not contain a period (.). If this member is NULL and the user fails to type an extension, no extension is appended.
lCustData
Specifies application-defined data that the system passes to the hook procedure identified by the lpfnHook member. When the system sends the WM_INITDIALOG message to the hook procedure, the message's lParam parameter is a pointer to the OPENFILENAME structure specified when the dialog box was created. The hook procedure can use this pointer to get the lCustData value.
lpfnHook
Pointer to a hook procedure. This member is ignored unless the Flags member includes the OFN_ENABLEHOOK flag.

If the OFN_EXPLORER flag is not set in the Flags member, lpfnHook is a pointer to an OFNHookProcOldStyle hook procedure that receives messages intended for the dialog box. The hook procedure returns FALSE to pass a message to the default dialog box procedure or TRUE to discard the message.

If OFN_EXPLORER is set, lpfnHook is a pointer to an OFNHookProc hook procedure. The hook procedure receives notification messages sent from the dialog box. The hook procedure also receives messages for any additional controls that you defined by specifying a child dialog template. The hook procedure does not receive messages intended for the standard controls of the default dialog box.

lpTemplateName
Pointer to a null-terminated string that names a dialog template resource in the module identified by the hInstance member. For numbered dialog box resources, this can be a value returned by the MAKEINTRESOURCE macro. This member is ignored unless the OFN_ENABLETEMPLATE flag is set in the Flags member.

If the OFN_EXPLORER flag is set, the system uses the specified template to create a dialog box that is a child of the default Explorer-style dialog box. If the OFN_EXPLORER flag is not set, the system uses the template to create an old-style dialog box that replaces the default dialog box.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in commdlg.h.
Unicode: Defined as Unicode and ANSI structures.

See Also

Common Dialog Box Library Overview, Common Dialog Box Structures, GetOpenFileName, GetSaveFileName, SHGetSpecialFolderLocation


PAGESETUPDLG

The PAGESETUPDLG structure contains information the PageSetupDlg function uses to initialize the Page Setup common dialog box. After the user closes the dialog box, the system returns information about the user-defined page parameters in this structure.

typedef struct tagPSD {  // psd
    DWORD           lStructSize;
    HWND            hwndOwner;
    HGLOBAL         hDevMode;
    HGLOBAL         hDevNames;
    DWORD           Flags;
    POINT           ptPaperSize;
    RECT            rtMinMargin;
    RECT            rtMargin;
    HINSTANCE       hInstance;
    LPARAM          lCustData;
    LPPAGESETUPHOOK lpfnPageSetupHook;
    LPPAGEPAINTHOOK lpfnPagePaintHook;
    LPCTSTR         lpPageSetupTemplateName;
    HGLOBAL         hPageSetupTemplate;
} PAGESETUPDLG, * LPPAGESETUPDLG;

Members

lStructSize
Specifies the size, in bytes, of this structure.
hwndOwner
Identifies the window that owns the dialog box. This member can be any valid window handle, or it can be NULL if the dialog box has no owner.
hDevMode
Handle to a global memory object that contains a DEVMODE structure. On input, if a handle is given, the values in the corresponding DEVMODE structure are used to initialize the controls in the dialog box. On output, the dialog box sets hDevMode to a global memory handle for a DEVMODE structure that contains values specifying the user's selections. If the user's selections are not available, the dialog box sets hDevMode to NULL.
hDevNames
Handle to a global memory object that contains a DEVNAMES structure. This structure contains three strings that specify the driver name, the printer name, and the output port name. On input, if a handle is given, the strings in the corresponding DEVNAMES structure are used to initialize controls in the dialog box. On output, the dialog box sets hDevNames to a global memory handle for a DEVNAMES structure that contains strings specifying the user's selections. If the user's selections are not available, the dialog box sets hDevNames to NULL.
Flags
A set of bit flags that you can use to initialize the Page Setup common dialog box. When the dialog box returns, it sets these flags to indicate the user's input. This member can be a combination of the following flags:
PSD_DEFAULTMINMARGINS
Sets the minimum values that the user can specify for the page margins to be the minimum margins allowed by the printer. This is the default. This flag is ignored if the PSD_MARGINS and PSD_MINMARGINS flags are also specified.
PSD_DISABLEMARGINS
Disables the margin controls, preventing the user from setting the margins.
PSD_DISABLEORIENTATION
Disables the orientation controls, preventing the user from setting the page orientation.
PSD_DISABLEPAGEPAINTING
Prevents the dialog box from drawing the contents of the sample page. If you enable a PagePaintHook hook procedure, you can still draw the contents of the sample page.
PSD_DISABLEPAPER
Disables the paper controls, preventing the user from setting page parameters such as the paper size and source.
PSD_DISABLEPRINTER
Disables the Printer button, preventing the user from invoking a dialog box that contains additional printer setup information.
PSD_ENABLEPAGEPAINTHOOK
Enables the hook procedure specified in the lpfnPagePaintHook member.
PSD_ENABLEPAGESETUPHOOK
Enables the hook procedure specified in the lpfnPageSetupHook member.
PSD_ENABLEPAGESETUPTEMPLATE
Indicates that the hInstance and lpPageSetupTemplateName members specify a dialog box template to use in place of the default template.
PSD_ENABLEPAGESETUPTEMPLATEHANDLE
Indicates that the hPageSetupTemplate member identifies a data block that contains a preloaded dialog box template. The system ignores the lpPageSetupTemplateName member if this flag is specified.
PSD_INHUNDREDTHSOFMILLIMETERS
Indicates that hundredths of millimeters are the unit of measurement for margins and paper size. The values in the rtMargin, rtMinMargin, and ptPaperSize members are in hundredths of millimeters. You can set this flag on input to override the default unit of measurement for the user's locale. When the function returns, the dialog box sets this flag to indicate the units used.
PSD_INTHOUSANDTHSOFINCHES
Indicates that thousandths of inches are the unit of measurement for margins and paper size. The values in the rtMargin, rtMinMargin, and ptPaperSize members are in thousandths of inches. You can set this flag on input to override the default unit of measurement for the user's locale. When the function returns, the dialog box sets this flag to indicate the units used.
PSD_INWININIINTLMEASURE
Not implemented.
PSD_MARGINS
Causes the system to use the values specified in the rtMargin member as the initial widths for the left, top, right, and bottom margins. If PSD_MARGINS is not set, the system sets the initial widths to one inch for all margins.
PSD_MINMARGINS
Causes the system to use the values specified in the rtMinMargin member as the minimum allowable widths for the left, top, right, and bottom margins. The system prevents the user from entering a width that is less than the specified minimum. If PSD_MINMARGINS is not specified, the system sets the minimum allowable widths to those allowed by the printer.
PSD_NONETWORKBUTTON
Hides and disables the Network button.
PSD_NOWARNING
Prevents the system from displaying a warning message when there is no default printer.
PSD_RETURNDEFAULT
PageSetupDlg does not display the dialog box. Instead, it sets the hDevNames and hDevMode members to handles to DEVMODE and DEVNAMES structures that are initialized for the system default printer. PageSetupDlg returns an error if either hDevNames or hDevMode is not NULL.
PSD_SHOWHELP
Causes the dialog box to display the Help button. The hwndOwner member must specify the window to receive the HELPMSGSTRING registered messages that the dialog box sends when the user clicks the Help button.

ptPaperSize
Specifies the dimensions of the paper selected by the user. The PSD_INTHOUSANDTHSOFINCHES or PSD_INHUNDREDTHSOFMILLIMETERS flag indicates the units of measurement.
rtMinMargin
Specifies the minimum allowable widths for the left, top, right, and bottom margins. The system ignores this member if the PSD_MINMARGINS flag is not set. These values must be less than or equal to the values specified in the rtMargin member. The PSD_INTHOUSANDTHSOFINCHES or PSD_INHUNDREDTHSOFMILLIMETERS flag indicates the units of measurement.
rtMargin
Specifies the widths of the left, top, right, and bottom margins. If you set the PSD_MARGINS flag, rtMargin specifies the initial margin values. When PageSetupDlg returns, rtMargin contains the margin widths selected by the user. The PSD_INHUNDREDTHSOFMILLIMETERS or PSD_INTHOUSANDTHSOFINCHES flag indicates the units of measurement.
hInstance
If the PSD_ENABLEPAGESETUPTEMPLATE flag is set in the Flags member, hInstance is the handle of the application or module instance that contains the dialog box template named by the lpPageSetupTemplateName member.
lCustData
Specifies application-defined data that the system passes to the hook procedure identified by the lpfnPageSetupHook member. When the system sends the WM_INITDIALOG message to the hook procedure, the message's lParam parameter is a pointer to the PAGESETUPDLG structure specified when the dialog was created. The hook procedure can use this pointer to get the lCustData value.
lpfnPageSetupHook
Pointer to a PageSetupHook hook procedure that can process messages intended for the dialog box. This member is ignored unless the PSD_ENABLEPAGESETUPHOOK flag is set in the Flags member.
lpfnPagePaintHook
Pointer to a PagePaintHook hook procedure that receives WM_PSD_* messages from the dialog box whenever the sample page is redrawn. By processing the messages, the hook procedure can customize the appearance of the sample page. This member is ignored unless the PSD_ENABLEPAGEPAINTHOOK flag is set in the Flags member.
lpPageSetupTemplateName
Pointer to a null-terminated string that names the dialog box template resource in the module identified by the hInstance member. This template is substituted for the standard dialog box template. For numbered dialog box resources, lpPageSetupTemplateName can be a value returned by the MAKEINTRESOURCE macro. This member is ignored unless the PSD_ENABLEPAGESETUPTEMPLATE flag is set in the Flags member.
hPageSetupTemplate
If the PSD_ENABLEPAGESETUPTEMPLATEHANDLE flag is set in the Flags member, hPageSetupTemplate is the handle of a memory object containing a dialog box template.

Remarks

If the PSD_INHUNDREDTHSOFMILLIMETERS and PSD_INTHOUSANDTHSOFINCHES flags are not specified, the system queries the LOCALE_IMEASURE value of the default user locale to determine the unit of measure (either hundredths of millimeters or thousandths of inches) for the margin widths and paper size.

If both hDevNames and hDevMode have valid handles and the printer name specified by the wDeviceOffset member of the DEVNAMES structure is not the same as the name specified by the dmDeviceName member of the DEVMODE structure, the system uses the name specified by wDeviceOffset by default.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.
Unicode: Defined as Unicode and ANSI structures.

See Also

Common Dialog Box Library Overview, Common Dialog Box Structures, DEVMODE, DEVNAMES, MAKEINTRESOURCE, PagePaintHook, PageSetupDlg, PageSetupHook, WM_INITDIALOG


PRINTDLG

The PRINTDLG structure contains information that the PrintDlg function uses to initialize the Print dialog box. After the user closes the dialog box, the system uses this structure to return information about the user's selections.

typedef struct tagPD {  // pd
    DWORD     lStructSize;
    HWND      hwndOwner;
    HANDLE    hDevMode;
    HANDLE    hDevNames;
    HDC       hDC;
    DWORD     Flags;
    WORD      nFromPage;
    WORD      nToPage;
    WORD      nMinPage;
    WORD      nMaxPage;
    WORD      nCopies;
    HINSTANCE hInstance;
    DWORD     lCustData;
    LPPRINTHOOKPROC lpfnPrintHook;
    LPSETUPHOOKPROC lpfnSetupHook;
    LPCTSTR    lpPrintTemplateName;
    LPCTSTR    lpSetupTemplateName;
    HANDLE    hPrintTemplate;
    HANDLE    hSetupTemplate;
} PRINTDLG;

Members

lStructSize
Specifies the structure size, in bytes.
hwndOwner
Identifies the window that owns the dialog box. This member can be any valid window handle, or it can be NULL if the dialog box has no owner.
hDevMode
Handle to a movable global memory object that contains a DEVMODE structure. If hDevMode is not NULL on input, you must allocate a movable block of memory for the DEVMODE structure and initialize its members. The PrintDlg function uses the input datato initialize the controls in the dialog box. When PrintDlg returns, the DEVMODE members indicate the user's input.

If hDevMode is NULL on input, PrintDlg allocates memory for the DEVMODE structure, initializes its members to indicate the user's input, and returns a handle that identifies it.

If the device driver for the specified printer does not support extended device modes, hDevMode is NULL when PrintDlg returns.

If the device name (specified by the dmDeviceName member of the DEVMODE structure) does not appear in the [devices] section of WIN.INI, PrintDlg returns an error.

For more information about the hDevMode and hDevNames members, see the Remarks section at the end of this topic.

hDevNames
Handle to a movable global memory object that contains a DEVNAMES structure. If hDevNames is not NULL on input, you must allocate a movable block of memory for the DEVNAMES structure and initialize its members. The PrintDlg function uses the input datato initialize the controls in the dialog box. When PrintDlg returns, the DEVNAMES members contain information for the printer chosen by the user. You can use this information to create a device context or an information context.

The hDevNames member can be NULL, in which case, PrintDlg allocates memory for the DEVNAMES structure, initializes its members to indicate the user's input, and returns a handle that identifies it.

For more information about the hDevMode and hDevNames members, see the Remarks section at the end of this topic.

hDC
Identifies a device context or an information context, depending on whether the Flags member specifies the PD_RETURNDC or PC_RETURNIC flag. If neither flag is specified, the value of this member is undefined. If both flags are specified, PD_RETURNDC has priority.
Flags
A set of bit flags that you can use to initialize the Print common dialog box. When the dialog box returns, it sets these flags to indicate the user's input. This member can be a combination of the following flags:
PD_ALLPAGES
The default flag that indicates that the All radio button is initially selected. This flag is used as a placeholder to indicate that the PD_PAGENUMS and PD_SELECTION flags are not specified.
PD_COLLATE
If this flag is set, the Collate check box is checked.

If this flag is set when the PrintDlg function returns, the application must simulate collation of multiple copies. For more information, see the description of the PD_USEDEVMODECOPIESANDCOLLATE flag.

PD_DISABLEPRINTTOFILE
Disables the Print to File check box.
PD_ENABLEPRINTHOOK
Enables the hook procedure specified in the lpfnPrintHook member. This enables the hook procedure for the Print dialog box.
PD_ENABLEPRINTTEMPLATE
Indicates that the hInstance and lpPrintTemplateName members specify a replacement for the default Print dialog box template.
PD_ENABLEPRINTTEMPLATEHANDLE
Indicates that the hPrintTemplate member identifies a data block that contains a preloaded dialog box template. This template replaces the default template for the Print dialog box. The system ignores the lpPrintTemplateName member if this flag is specified.
PD_ENABLESETUPHOOK
Enables the hook procedure specified in the lpfnSetupHook member. This enables the hook procedure for the Print Setup dialog box.
PD_ENABLESETUPTEMPLATE
Indicates that the hInstance and lpSetupTemplateName members specify a replacement for the default Print Setup dialog box template.
PD_ENABLESETUPTEMPLATEHANDLE
Indicates that the hSetupTemplate member identifies a data block that contains a preloaded dialog box template. This template replaces the default template for the Print Setup dialog box. The system ignores the lpSetupTemplateName member if this flag is specified.
PD_HIDEPRINTTOFILE
Hides the Print to File check box.
PD_NONETWORKBUTTON
Hides and disables the Network button.
PD_NOPAGENUMS
Disables the Pages radio button and the associated edit controls.
PD_NOSELECTION
Disables the Selection radio button.
PD_NOWARNING
Prevents the warning message from being displayed when there is no default printer.
PD_PAGENUMS
If this flag is set, the Pages radio button is selected.

If this flag is set when the PrintDlg function returns, the nFromPage and nFromPage members indicate the starting and ending pages specified by the user.
PD_PRINTSETUP
Causes the system to display the Print Setup dialog box rather than the Print dialog box.
PD_PRINTTOFILE
If this flag is set, the Print to File check box is selected.

If this flag is set when the PrintDlg function returns, the offset indicated by the wOutputOffset member of the DEVNAMES structure contains the string "FILE:". When you call the StartDoc function to start the printing operation, specify this "FILE:" string in the lpszOutput member of the DOCINFO structure. Specifying this string causes the print subsystem to query the user for the name of the output file.

PD_RETURNDC
Causes PrintDlg to return a device context matching the selections the user made in the dialog box. The device context is returned in hDC.
PD_RETURNDEFAULT
If this flag is set, the PrintDlg function does not display the dialog box. Instead, it sets the hDevNames and hDevMode members to handles to DEVMODE and DEVNAMES structures that are initialized for the system default printer. Both hDevNames and hDevMode must be NULL, or PrintDlg returns an error.

If the system default printer is supported by an old printer driver (earlier than Windows version 3.0), only hDevNames is returned; hDevMode is NULL.
PD_RETURNIC
Similar to the PD_RETURNDC flag, except this flag returns an information context rather than a device context. If neither PD_RETURNDC nor PD_RETURNIC is specified, hDC is undefined on output.
PD_SELECTION
If this flag is set, the Selection radio button is selected.

If neither PD_PAGENUMS nor PD_SELECTION is set, the All radio button is selected.

PD_SHOWHELP
Causes the dialog box to display the Help button. The hwndOwner member must specify the window to receive the HELPMSGSTRING registered messages that the dialog box sends when the user clicks the Help button.
PD_USEDEVMODECOPIES
Same as PD_USEDEVMODECOPIESANDCOLLATE
PD_USEDEVMODECOPIESANDCOLLATE
This flag indicates whether your application supports multiple copies and collation. Set this flag on input to indicate that your application does not support multiple copies and collation. In this case, the nCopies member of the PRINTDLG structure always returns 1, and PD_COLLATE is never set in the Flags member.

If this flag is not set, the application is responsible for printing and collating multiple copies. In this case, the nCopies member of the PRINTDLG structure indicates the number of copies the user wants to print, and the PD_COLLATE flag in the Flags member indicates whether the user wants collation.

Regardless of whether this flag is set, an application can determine from nCopies and PD_COLLATE how many copies to render and whether to print them collated.

If this flag is set and the printer driver does not support multiple copies, the Copies edit control is disabled. Similarly, if this flag is set and the printer driver does not support collation, the Collate checkbox is disabled.

The dmCopies and dmCollate members of the DEVMODE structure contain the copies and collate information used by the printer driver. If this flag is set and the printer driver supports multiple copies, the dmCopies member indicates the number of copies requested by the user. If this flag is set and the printer driver supports collation, the dmCollate member of the DEVMODE structure indicates whether the user wants collation. If this flag is not set, the dmCopies member always returns 1, and the dmCollate member is always zero.

nFromPage
Specifies the initial value for the starting page edit control.

When PrintDlg returns, nFromPage is the starting page specified by the user. If the Pages radio button is selected when the user clicks the Okay button, PrintDlg sets the PD_PAGENUMS flag and does not return until the user enters a starting page value that is within the minimum to maximum page range.

Windows 95: If the input value for either nFromPage or nToPage is outside the range specified by nMinPage and nMaxPage, PrintDlg returns an error.

Windows NT: If the input value for either nFromPage or nToPage is outside the minimum/maximum range, PrintDlg returns an error only if the PD_PAGENUMS flag is specified; otherwise, it displays the dialog box but changes the out-of-range value to the minimum or maximum value.

nToPage
Specifies the initial value for the ending page edit control.

When PrintDlg returns, nToPage is the ending page specified by the user. If the Pages radio button is selected when the use clicks the Okay button, PrintDlg sets the PD_PAGENUMS flag and does not return until the user enters an ending page value that is within the minimum to maximum page range.

nMinPage
Specifies the minimum value for the page range specified in the From and To page edit controls. If nMinPage equals nMaxPage, the Pages radio button and the starting and ending page edit controls are disabled.
nMaxPage
Specifies the maximum value for the page range specified in the From and To page edit controls.
nCopies
Contains the initial number of copies for the Copies edit control if hDevMode is NULL; otherwise, the dmCopies member of the DEVMODE structure contains the initial value. When PrintDlg returns, nCopies contains the actual number of copies to print. This value depends on whether the application or the printer driver is responsible for printing multiple copies. If the PD_USEDEVMODECOPIESANDCOLLATE flag is set in the Flags member, nCopies is always 1 on return, and the printer driver is responsible for printing multiple copies. If the flag is not set, the application is responsible for printing the number of copies specified by nCopies. For more information, see the description of the PD_USEDEVMODECOPIESANDCOLLATE flag.
hInstance
If the PD_ENABLEPRINTTEMPLATE or PD_ENABLESETUPTEMPLATE flag is set in the Flags member, hInstance is the handle of the application or module instance that contains the dialog box template named by the lpPrintTemplateName or lpSetupTemplateName member.
lCustData
Specifies application-defined data that the system passes to the hook procedure identified by the lpfnPrintHook or lpfnSetupHook member. When the system sends the WM_INITDIALOG message to the hook procedure, the message's lParam parameter is a pointer to the PRINTDLG structure specified when the dialog was created. The hook procedure can use this pointer to get the lCustData value.
lpfnPrintHook
Pointer to a PrintHookProc hook procedure that can process messages intended for the Print dialog box. This member is ignored unless the PD_ENABLEPRINTHOOK flag is set in the Flags member.
lpfnSetupHook
Pointer to a SetupHookProc hook procedure that can process messages intended for the Print Setup dialog box. This member is ignored unless the PD_ENABLESETUPHOOK flag is set in the Flags member.
lpPrintTemplateName
Pointer to a null-terminated string that names a dialog box template resource in the module identified by the hInstance member. This template replaces the default Print dialog box template. This member is ignored unless the PD_ENABLEPRINTTEMPLATE flag is set in the Flags member.
lpSetupTemplateName
Pointer to a null-terminated string that names a dialog box template resource in the module identified by the hInstance member. This template replaces the default Print Setup dialog box template. This member is ignored unless the PD_ENABLESETUPTEMPLATE flag is set in the Flags member.
hPrintTemplate
If the PD_ENABLEPRINTTEMPLATEHANDLE flag is set in the Flags member, hPrintTemplate is the handle of a memory object containing a dialog box template. This template replaces the default Print dialog box template.
hSetupTemplate
If the PD_ENABLESETUPTEMPLATEHANDLE flag is set in the Flags member, hSetupTemplate is the handle of a memory object containing a dialog box template. This template replaces the default Print Setup dialog box template.

Remarks

When you call the PrintDlg function, be sure that the wDeviceOffset member of the DEVNAMES structure is identical to the dmDeviceName member of the DEVMODE structure. If these members do not specify the same printer, PrintDlg initializes the dialog box using the printer specified by the wDeviceOffset member.

Typically, if both hDevMode and hDevNames are NULL, PrintDlg initializes the dialog box using the current default printer. However, if the PD_RETURNDEFAULT flag is set and both hDevMode and hDevNames are NULL, PrintDlg uses the hDevNames and hDevMode members to return information about the current default printer without displaying the dialog box.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winspool.h.
Unicode: Defined as Unicode and ANSI structures.

See Also

Common Dialog Box Library Overview, Common Dialog Box Structures, CreateDC, CreateIC, PrintDlg, DEVMODE, DEVNAMES, WM_INITDIALOG


PRINTDLGEX

[This is preliminary documentation and subject to change.]

The PRINTDLGEX structure contains information that the PrintDlgEx function uses to initialize the Print property sheet. After the user closes the property sheet, the system uses this structure to return information about the user's selections.

typedef  struct  tagPDEX  {
    DWORD              lStructSize;
    HWND               hwndOwner;
    HGLOBAL            hDevMode;
    HGLOBAL            hDevNames;
    HDC                hDC;
    DWORD              Flags;
    DWORD              Flags2;
    DWORD              ExclusionFlags;
    DWORD              nPageRanges;
    DWORD              nMaxPageRanges;
    LPPRINTPAGERANGE   lpPageRanges;
    DWORD              nMinPage;
    DWORD              nMaxPage;
    DWORD              nCopies;
    HINSTANCE          hInstance;
    LPCTSTR            lpPrintTemplateName;
    LPUNKNOWN          lpCallback;
    DWORD              nPropertyPages;
    HPROPSHEETPAGE    *lphPropertyPages;
    DWORD              nStartPage;
    DWORD              dwResultAction;
} PRINTDLGEX, *LPPRINTDLGEX;

Members

lStructSize
Specifies the structure size, in bytes.
hwndOwner
Handle to the window that owns the property sheet. This member must be a valid window handle; it cannot be NULL.
hDevMode
Handle to a movable global memory object that contains a DEVMODE structure. If hDevMode is not NULL on input, you must allocate a movable block of memory for the DEVMODE structure and initialize its members. The PrintDlgEx function uses the input datato initialize the controls in the property sheet. When PrintDlgEx returns, the DEVMODE members indicate the user's input.

If hDevMode is NULL on input, PrintDlgEx allocates memory for the DEVMODE structure, initializes its members to indicate the user's input, and returns a handle that identifies it.

For more information about the hDevMode and hDevNames members, see the Remarks section at the end of this topic.

hDevNames
Handle to a movable global memory object that contains a DEVNAMES structure. If hDevNames is not NULL on input, you must allocate a movable block of memory for the DEVNAMES structure and initialize its members. The PrintDlgEx function uses the input datato initialize the controls in the property sheet. When PrintDlgEx returns, the DEVNAMES members contain information for the printer chosen by the user. You can use this information to create a device context or an information context.

The hDevNames member can be NULL, in which case, PrintDlgEx allocates memory for the DEVNAMES structure, initializes its members to indicate the user's input, and returns a handle that identifies it.

For more information about the hDevMode and hDevNames members, see the Remarks section at the end of this topic.

hDC
Handle to a device context or an information context, depending on whether the Flags member specifies the PD_RETURNDC or PC_RETURNIC flag. If neither flag is specified, the value of this member is undefined. If both flags are specified, PD_RETURNDC has priority.
Flags
A set of bit flags that you can use to initialize the Print property sheet. When the PrintDlgEx function returns, it sets these flags to indicate the user's input. This member can be a combination of the following flags.
PD_ALLPAGES
The default flag that indicates that the All radio button is initially selected. This flag is used as a placeholder to indicate that the PD_PAGENUMS, PD_SELECTION, and PD_CURRENTPAGE flags are not specified.
PD_COLLATE
If this flag is set, the Collate check box is checked.

If this flag is set when the PrintDlgEx function returns, the application must simulate collation of multiple copies. For more information, see the description of the PD_USEDEVMODECOPIESANDCOLLATE flag.

PD_CURRENTPAGE
If this flag is set, the Current Page radio button is selected. If none of the PD_PAGENUMS, PD_SELECTION, or PD_CURRENTPAGE flags is set, the All radio button is selected.
PD_DISABLEPRINTTOFILE
Disables the Print to File check box.
PD_ENABLEPRINTTEMPLATE
Indicates that the hInstance and lpPrintTemplateName members specify a replacement for the default dialog box template in the lower portion of the General page. The default template contains controls similar to those of the Print dialog box. The system uses the specified template to create a window that is a child of the General page.
PD_ENABLEPRINTTEMPLATEHANDLE
Indicates that the hInstance member identifies a data block that contains a preloaded dialog box template. This template replaces the default dialog box template in the lower portion of the General page. The system uses the specified template to create a window that is a child of the General page. The system ignores the lpPrintTemplateName member if this flag is specified.
PD_EXCLUSIONFLAGS
Indicates that the ExclusionFlags member identifies items to be excluded from the printer driver property pages. If this flag is not set, items will be excluded by default from the printer driver property pages. The exclusions prevent the duplication of items among the General page, any application-specified pages, and the printer driver pages.
PD_HIDEPRINTTOFILE
Hides the Print to File check box.
PD_NOCURRENTPAGE
Disables the Current Page radio button.
PD_NOPAGENUMS
Disables the Pages radio button and the associated edit controls.
PD_NOSELECTION
Disables the Selection radio button.
PD_NOWARNING
Prevents the warning message from being displayed when an error occurs.
PD_PAGENUMS
If this flag is set, the Pages radio button is selected. If none of the PD_PAGENUMS, PD_SELECTION, or PD_CURRENTPAGE flags is set, the All radio button is selected.

If this flag is set when the PrintDlgEx function returns, the lpPageRanges member indicates the page ranges specified by the user.

PD_PRINTTOFILE
If this flag is set, the Print to File check box is selected.

If this flag is set when PrintDlgEx returns, the offset indicated by the wOutputOffset member of the DEVNAMES structure contains the string "FILE:". When you call the StartDoc function to start the printing operation, specify this "FILE:" string in the lpszOutput member of the DOCINFO structure. Specifying this string causes the print subsystem to query the user for the name of the output file.

PD_RETURNDC
Causes PrintDlgEx to return a device context matching the selections the user made in the property sheet. The device context is returned in hDC.
PD_RETURNDEFAULT
If this flag is set, the PrintDlgEx function does not display the property sheet. Instead, it sets the hDevNames and hDevMode members to handles to DEVMODE and DEVNAMES structures that are initialized for the system default printer. Both hDevNames and hDevMode must be NULL, or PrintDlgEx returns an error.
PD_RETURNIC
Similar to the PD_RETURNDC flag, except this flag returns an information context rather than a device context. If neither PD_RETURNDC nor PD_RETURNIC is specified, hDC is undefined on output.
PD_SELECTION
If this flag is set, the Selection radio button is selected.

If none of the PD_PAGENUMS, PD_SELECTION, or PD_CURRENTPAGE flags is set, the All radio button is selected.

PD_USEDEVMODECOPIES
Same as PD_USEDEVMODECOPIESANDCOLLATE
PD_USEDEVMODECOPIESANDCOLLATE
This flag indicates whether your application supports multiple copies and collation. Set this flag on input to indicate that your application does not support multiple copies and collation. In this case, the nCopies member of the PRINTDLGEX structure always returns 1, and PD_COLLATE is never set in the Flags member.

If this flag is not set, the application is responsible for printing and collating multiple copies. In this case, the nCopies member of the PRINTDLGEX structure indicates the number of copies the user wants to print, and the PD_COLLATE flag in the Flags member indicates whether the user wants collation.

Regardless of whether this flag is set, an application can determine from nCopies and PD_COLLATE how many copies to render and whether to print them collated.

If this flag is set and the printer driver does not support multiple copies, the Copies edit control is disabled. Similarly, if this flag is set and the printer driver does not support collation, the Collate checkbox is disabled.

The dmCopies and dmCollate members of the DEVMODE structure contain the copies and collate information used by the printer driver. If this flag is set and the printer driver supports multiple copies, the dmCopies member indicates the number of copies requested by the user. If this flag is set and the printer driver supports collation, the dmCollate member of the DEVMODE structure indicates whether the user wants collation. If this flag is not set, the dmCopies member always returns 1, and the dmCollate member is always zero.

Flags2
Reserved; must be zero.
ExclusionFlags
A set of bit flags that can exclude items from the printer driver property pages in the Print property sheet. This value is used only if the PD_EXCLUSIONFLAGS flag is set in the Flags member. Exclusion flags should be used only if the item to be excluded will be included on either the General page or on an application-defined page in the Print property sheet. This member can specify the following flag.
PD_EXCL_COPIESANDCOLLATE
Excludes the Copies and Collate controls from the printer driver property pages in a Print property sheet. This flag should always be set when the application uses the default Copies and Collate controls provided by the lower portion of the General page of the Print property sheet.

nPageRanges
On input, set this member to the initial number of page ranges specified in the lpPageRanges array. When the PrintDlgEx function returns, nPageRanges indicates the number of user-specified page ranges stored in the lpPageRanges array. If the PD_NOPAGENUMS flag is specified, this value is not valid.
nMaxPageRanges
Specifies the size, in array elements, of the lpPageRanges buffer. This value indicates the maximum number of page ranges that can be stored in the array. If the PD_NOPAGENUMS flag is specified, this value is not valid. If the PD_NOPAGENUMS flag is not specified, this value must be greater than zero.
lpPageRanges
Pointer to a buffer containing an array of PRINTPAGERANGE structures. On input, the array contains the initial page ranges to display in the Pages edit control. When the PrintDlgEx function returns, the array contains the page ranges specified by the user.

If the PD_NOPAGENUMS flag is specified, this value is not valid. If the PD_NOPAGENUMS flag is not specified, lpPageRanges must be non-NULL.

nMinPage
Specifies the minimum value for the page ranges specified in the Pages edit control. If the PD_NOPAGENUMS flag is specified, this value is not valid.
nMaxPage
Specifies the maximum value for the page ranges specified in the Pages edit control. If the PD_NOPAGENUMS flag is specified, this value is not valid.
nCopies
Contains the initial number of copies for the Copies edit control if hDevMode is NULL; otherwise, the dmCopies member of the DEVMODE structure contains the initial value.

When PrintDlgEx returns, nCopies contains the actual number of copies the application must print. This value depends on whether the application or the printer driver is responsible for printing multiple copies. If the PD_USEDEVMODECOPIESANDCOLLATE flag is set in the Flags member, nCopies is always 1 on return, and the printer driver is responsible for printing multiple copies. If the flag is not set, the application is responsible for printing the number of copies specified by nCopies. For more information, see the description of the PD_USEDEVMODECOPIESANDCOLLATE flag.

hInstance
If the PD_ENABLEPRINTTEMPLATE flag is set in the Flags member, hInstance is the handle of the application or module instance that contains the dialog box template named by the lpPrintTemplateName member. If the PD_ENABLEPRINTTEMPLATEHANDLE flag is set in the Flags member, hInstance is the handle of a memory object containing a dialog box template. If neither of the template flags is set in the Flags member, hInstance should be NULL.
lpPrintTemplateName
Pointer to a null-terminated string that names a dialog box template resource in the module identified by the hInstance member. This template replaces the default dialog box template in the lower portion of the General page. The default template contains controls similar to those of the Print dialog box. This member is ignored unless the PD_ENABLEPRINTTEMPLATE flag is set in the Flags member.
lpCallback
Pointer to an application-defined callback object.

The object should contain the IPrintDialogCallback class to receive messages for the child dialog box in the lower portion of the General page.

The callback object should also contain the IObjectWithSite class to receive a pointer to the IPrintDialogServices interface. The PrintDlgEx function calls QueryInterface on the callback object for both IID_IPrintDialogCallback and IID_IObjectWithSite to determine which interfaces are supported.

If you do not want to retrieve any of the callback information, set lpCallback to NULL.

nPropertyPages
Specifies the number of property page handles in the lphPropertyPages array.
lphPropertyPages
Contains an array of property page handles to add to the Print property sheet. The additional property pages follow the General page. Use the CreatePropertySheetPage function to create these additional pages. If nPropertyPages is zero, lphPropertyPages should be NULL.
nStartPage
Specifies the property page that is initially displayed. To display the General page, specify START_PAGE_GENERAL. Otherwise, specify the zero-based index of a property page in the array specified in the lphPropertyPages member. For consistency, it is recommended that the property sheet always be started on the General page.
dwResultAction
On input, set this member to zero. If the PrintDlgEx function returns S_OK, dwResultAction contains the outcome of the dialog. If PrintDlgEx returns an error, this member should be ignored. The dwResultAction member can be one of the following values.
Value | Meaning
PD_RESULT_APPLY | The user clicked the Apply button and later clicked the Cancel button. This indicates that the user wants to apply the changes made in the property sheet, but does not want to print yet. The PRINTDLGEX structure contains the information specified by the user at the time the Apply button was clicked.
PD_RESULT_CANCEL | The user clicked the Cancel button. The information in the PRINTDLGEX structure is unchanged.
PD_RESULT_PRINT | The user clicked the Print button. The PRINTDLGEX structure contains the information specified by the user.

Remarks

When you call the PrintDlgEx function, be sure that the wDeviceOffset member of the DEVNAMES structure is identical to the dmDeviceName member of the DEVMODE structure. If these members do not specify the same printer, PrintDlgEx initializes the property sheet using the printer specified by the wDeviceOffset member.

Typically, if both hDevMode and hDevNames are NULL, PrintDlgEx initializes the property sheet using the current default printer. However, if the PD_RETURNDEFAULT flag is set and both hDevMode and hDevNames are NULL, PrintDlgEx uses the hDevNames and hDevMode members to return information about the current default printer without displaying the property sheet.

During the execution of PrintDlgEx, the DEVMODE and DEVNAMES structures that you specified in the PRINTDLGEX structure may not always contain current data. For this reason, application-specific property pages as well as IPrintDialogCallback routines for the initial page should use the IPrintDialogServices interface to retrieve information about the state of the current printer.

QuickInfo

Windows NT: Requires version 5.0 or later.
Windows: Unsupported.
Windows CE: Unsupported.
Header: Declared in commdlg.h.
Import Library: Use comdlg32.lib.
Unicode: Defined as Unicode and ANSI structures.

See Also

Common Dialog Box Library Overview, Common Dialog Box Structures, CreateDC, CreateIC, CreatePropertySheetPage, DEVMODE, DEVNAMES, IObjectWithSite, IPrintDialogCallback, IPrintDialogServices, PrintDlgEx


PRINTPAGERANGE

[This is preliminary documentation and subject to change.]

The PRINTPAGERANGE structure specifies a range of pages in a print job. A print job can have more than one page range. This information is supplied in the PRINTDLGEX structure when calling the PrintDlgEx function.

typedef struct tagPRINTPAGERANGE {
    DWORD nFromPage;
    DWORD nToPage;
} PRINTPAGERANGE, *LPPRINTPAGERANGE;

Members

nFromPage
Specifies the first page of the range.
nToPage
Specifies the last page of the range.

QuickInfo

Windows NT: Requires version 5.0 or later.
Windows: Unsupported.
Windows CE: Unsupported.
Header: Declared in commdlg.h.
Import Library: Use comdlg32.lib.

See Also

Common Dialog Box Library Overview, Common Dialog Box Structures, PRINTDLGEX, PrintDlgEx


Common Dialog Box Messages

The following constants identify strings that you can use with the RegisterWindowMessage function to get a message identifier. You can use these message identifiers to send messages to or receive messages from common dialog boxes.

COLOROKSTRING
FILEOKSTRING
FINDMSGSTRING
HELPMSGSTRING
LBSELCHSTRING
SETRGBSTRING
SHAREVISTRING

The following are messages you can send to a Font dialog box.

WM_CHOOSEFONT_GETLOGFONT
WM_CHOOSEFONT_SETFLAGS
WM_CHOOSEFONT_SETLOGFONT

The following are messages that a Page Setup dialog box sends to an application-defined PagePaintHook hook procedure.

WM_PSD_ENVSTAMPRECT
WM_PSD_FULLPAGERECT
WM_PSD_GREEKTEXTRECT
WM_PSD_MARGINRECT
WM_PSD_MINMARGINRECT
WM_PSD_PAGESETUPDLG
WM_PSD_YAFULLPAGERECT

The following are messages that a hook procedure can send to an Explorer-style Open or Save As dialog box.

CDM_GETFILEPATH
CDM_GETFOLDERIDLIST
CDM_GETFOLDERPATH
CDM_GETSPEC
CDM_HIDECONTROL
CDM_SETCONTROLTEXT
CDM_SETDEFEXT

The following are notification messages that an Explorer-style Open or Save As dialog box can send to a hook procedure.

CDN_FILEOK
CDN_FOLDERCHANGE
CDN_HELP
CDN_INITDONE
CDN_SELCHANGE
CDN_SHAREVIOLATION
CDN_TYPECHANGE


CDM_GETFILEPATH

The CDM_GETFILEPATH message retrieves the path and filename of the selected file in an Explorer-style Open or Save As common dialog box. The dialog box must have been created with the OFN_EXPLORER flag; otherwise, the message fails.

CDM_GETFILEPATH
wParam = (WPARAM) cbmax;
lParam = (LPARAM) (LPTSTR) psz;

// Corresponding macro
int CommDlg_OpenSave_GetFilePath(hdlg, psz, cbmax);

Parameters

hdlg
Handle of the common dialog box window to receive the message.
psz
Pointer to the buffer that receives the filename and path.
cbmax
Size, in bytes (ANSI version) or 16-bit characters (Unicode version), of the psz buffer.

Return Values

If the message succeeds, the return value is the size, in bytes or characters, of the filename and path string, including the terminating NULL character. This is either the number of bytes or characters copied to the psz buffer, or the required buffer size if the buffer is too small.

If an error occurs, the return value is less than zero.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, GetOpenFileName, GetSaveFileName, OPENFILENAME


CDM_GETFOLDERIDLIST

The CDM_GETFOLDERIDLIST message retrieves the address of the item identifier list corresponding to the folder that an Explorer-style Open or Save As common dialog box currently has open. The dialog box must have been created with the OFN_EXPLORER flag; otherwise, the message fails.

CDM_GETFOLDERIDLIST
wParam = (WPARAM) cbmax;
lParam = (LPARAM) (LPVOID) pidl;

// Corresponding macro
int CommDlg_OpenSave_GetFolderIDList(hdlg, pidl, cbmax);

Parameters

hdlg
Handle of the common dialog box window to receive the message.
pidl
Pointer to the buffer that receives the list of item identifiers.
cbmax
Size, in bytes, of the pidl buffer.

Return Values

If the message succeeds, the return value is the size, in bytes, of the list of item identifiers. This is either the number of bytes copied to the pidl buffer, or the required buffer size if the buffer is too small.

If an error occurs, the return value is less than zero.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, GetOpenFileName, GetSaveFileName, OPENFILENAME


CDM_GETFOLDERPATH

The CDM_GETFOLDERPATH message retrieves the path of the currently open folder or directory for an Explorer-style Open or Save As common dialog box. The dialog box must have been created with the OFN_EXPLORER flag; otherwise, the message fails.

CDM_GETFOLDERPATH
wParam = (WPARAM) cbmax;
lParam = (LPARAM) (LPTSTR) psz;

// Corresponding macro
int CommDlg_OpenSave_GetFolderPath(hdlg, psz, cbmax);

Parameters

hdlg
Handle of the common dialog box window to receive the message.
psz
Pointer to the buffer that receives the path.
cbmax
Size, in bytes (ANSI version) or 16-bit characters (Unicode version), of the psz buffer.

Return Values

If the message succeeds, the return value is the size, in bytes or characters, of the path string, including the terminating NULL character. This is either the number of bytes or characters copied to the psz buffer, or the required buffer size if the buffer is too small.

If an error occurs, the return value is less than zero.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, GetOpenFileName, GetSaveFileName, OPENFILENAME


CDM_GETSPEC

The CDM_GETSPEC message retrieves the filename (not including the path) of the currently selected file in an Explorer-style Open or Save As common dialog box. The dialog box must have been created with the OFN_EXPLORER flag; otherwise, the message fails.

CDM_GETSPEC
wParam = (WPARAM) cbmax;
lParam = (LPARAM) (LPTSTR) psz;

// Corresponding macro
int CommDlg_OpenSave_GetSpec(hdlg, psz, cbmax);

Parameters

hdlg
Handle of the common dialog box window to receive the message.
psz
Address of the buffer that receives the filename.
cbmax
Size, in bytes (ANSI version) or 16-bit characters (Unicode version), of the psz buffer.

Return Values

If the message succeeds, the return value is the size, in bytes or characters, of the filename string, including the terminating NULL character. This is either the number of bytes or characters copied to the psz buffer, or the required buffer size if the buffer is too small.

If an error occurs, the return value is less than zero.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, GetOpenFileName, GetSaveFileName, OPENFILENAME


CDM_HIDECONTROL

The CDM_HIDECONTROL message hides the specified control in an Explorer-style Open or Save As common dialog box. The dialog box must have been created with the OFN_EXPLORER flag; otherwise, the message fails.

CDM_HIDECONTROL
wParam = (WPARAM) id;
lParam = 0;

// corresponding macro
void CommDlg_OpenSave_HideControl(hdlg, id);

Parameters

hdlg
Handle of the common dialog box window to receive the message.
id
Identifier of the control to hide.

Return Values

No return value.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, GetOpenFileName, GetSaveFileName, OPENFILENAME


CDM_SETCONTROLTEXT

The CDM_SETCONTROLTEXT message sets the text for the specified control in an Explorer-style Open or Save As common dialog box. The dialog box must have been created with the OFN_EXPLORER flag; otherwise, the message fails.

CDM_SETCONTROLTEXT
wParam = (WPARAM) id;
lParam = (LPARAM) (LPSTR) text;

// corresponding macro
void CommDlg_OpenSave_SetControlText(hdlg, id, text)

Parameters

hdlg
Handle of the common dialog box window to receive the message.
id
Identifier of the control to whose text is set.
text
Pointer to a null-terminated string specifying the new text for the control.

Return Values

No return value.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, GetOpenFileName, GetSaveFileName, OPENFILENAME


CDM_SETDEFEXT

The CDM_SETDEFEXT message sets the default filename extension for an Explorer-style Open or Save As common dialog box. The dialog box must have been created with the OFN_EXPLORER flag; otherwise, the message fails.

CDM_SETDEFEXT
wParam = 0;
lParam = (LPARAM) (LPSTR) pszext;

// corresponding macro
void CommDlg_OpenSave_SetDefExt(hdlg, pszext)

Parameters

hdlg
Handle of the common dialog box window to receive the message.
pszext
Pointer to the new filename extension. Must not include the dot (.).

Return Values

No return value.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, GetOpenFileName, GetSaveFileName, OPENFILENAME


CDN_FILEOK

The CDN_FILEOK notification message is sent by an Explorer-style Open or Save As common dialog box when the user specifies a filename and clicks the OK button. Your OFNHookProc hook procedure receives this message in the form of a WM_NOTIFY message.

CDN_FILEOK
lpon = (LPOFNOTIFY) lParam;

Parameters

lpon
Pointer to an OFNOTIFY structure.

The OFNOTIFY structure contains an NMHDR structure whose code member indicates the CDN_FILEOK notification code.

The OFNOTIFY structure also contains a pointer to an OPENFILENAME structure whose lpstrFile member specifies the address of the selected filename.

Return Values

If the hook procedure returns zero, the dialog box accepts the specified filename and closes.

To reject the specified filename and force the dialog box to remain open, return a nonzero value from the hook procedure and call the SetWindowLong function to set a nonzero DWL_MSGRESULT value.

Remarks

The system sends this notification only if the dialog box was created using the OFN_EXPLORER value.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, GetOpenFileName, GetSaveFileName, NMHDR, OFNHookProc, OFNOTIFY, OPENFILENAME, SetWindowLong, WM_NOTIFY


CDN_FOLDERCHANGE

The CDN_FOLDERCHANGE notification message is sent by an Explorer-style Open or Save As common dialog box when a new folder is opened. Your OFNHookProc hook procedure receives this message in the form of a WM_NOTIFY message.

CDN_FOLDERCHANGE
lpon = (LPOFNOTIFY) lParam;

Parameters

lpon
Pointer to an OFNOTIFY structure.

The OFNOTIFY structure contains an NMHDR structure whose code member indicates the CDN_FOLDERCHANGE notification code.

Return Values

The return value is ignored.

Remarks

The system sends this notification only if the dialog box was created using the OFN_EXPLORER value.

To get the path of the newly opened folder, the hook procedure can send the CDM_GETFOLDERPATH message to the dialog box.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, CDM_GETFOLDERPATH, GetOpenFileName, GetSaveFileName, NMHDR, OFNHookProc, OFNOTIFY, WM_NOTIFY


CDN_HELP

The CDN_HELP notification message is sent by an Explorer-style Open or Save As common dialog box when the user clicks the Help button. Your OFNHookProc hook procedure receives this message in the form of a WM_NOTIFY message.

CDN_HELP
lpon = (LPOFNOTIFY) lParam;

Parameters

lpon
Pointer to an OFNOTIFY structure.

The OFNOTIFY structure contains an NMHDR structure whose code member indicates the CDN_HELP notification code.

Return Values

The return value is ignored.

Remarks

The system sends this notification only if the dialog box was created using the OFN_EXPLORER value.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, GetOpenFileName, GetSaveFileName, NMHDR, OFNHookProc, OFNOTIFY, OPENFILENAME, WM_NOTIFY


CDN_INITDONE

The CDN_INITDONE notification message is sent by an Explorer-style Open or Save As common dialog box when the system has finished arranging the controls in the dialog box. The system moves the standard controls to make room for the controls of the child dialog box. Your OFNHookProc hook procedure receives this message in the form of a WM_NOTIFY message.

CDN_INITDONE
lpon = (LPOFNOTIFY) lParam;

Parameters

lpon
Pointer to an OFNOTIFY structure.

The OFNOTIFY structure contains an NMHDR structure whose code member indicates the CDN_INITDONE notification code.

Return Values

The return value is ignored.

Remarks

The system sends this notification only if the dialog box was created using the OFN_EXPLORER value.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, GetOpenFileName, GetSaveFileName, NMHDR, OFNHookProc, OFNOTIFY, OPENFILENAME, WM_NOTIFY


CDN_SELCHANGE

The CDN_SELCHANGE notification message is sent by an Explorer-style Open or Save As common dialog box when the selection changes in the list box that displays the contents of the currently opened folder or directory. Your OFNHookProc hook procedure receives this message in the form of a WM_NOTIFY message.

CDN_SELCHANGE
lpon = (LPOFNOTIFY) lParam;

Parameters

lpon
Pointer to an OFNOTIFY structure.

The OFNOTIFY structure contains an NMHDR structure whose code member indicates the CDN_SELCHANGE notification code.

Return Values

The return value is ignored.

Remarks

The system sends this notification only if the dialog box was created using the OFN_EXPLORER value.

To get the name of the newly selected file or folder, the hook procedure can send the CDM_GETFILEPATH or CDM_GETSPEC message to the common dialog box.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, CDM_GETFILEPATH, CDM_GETSPEC, GetOpenFileName, GetSaveFileName, NMHDR, OFNHookProc, OFNOTIFY, WM_NOTIFY


CDN_SHAREVIOLATION

The CDN_SHAREVIOLATION notification message is sent by an Explorer-style Open or Save As common dialog box when the user clicks the OK button and a network sharing violation occurs for the selected file. Your OFNHookProc hook procedure receives this message in the form of a WM_NOTIFY message.

CDN_SHAREVIOLATION
lpon = (LPOFNOTIFY) lParam;

Parameters

lpon
Pointer to an OFNOTIFY structure. The pszFile member of this structure points to the name of the file that had the sharing violation.

The OFNOTIFY structure contains an NMHDR structure whose code member indicates the CDN_SHAREVIOLATION notification code.

Return Values

The return value indicates how the dialog box should handle the sharing violation.

If the hook procedure returns zero, the dialog box displays the standard warning message for a sharing violation.

To prevent the display of the standard warning message, return a nonzero value from the hook procedure and call the SetWindowLong function to set one of the following DWL_MSGRESULT values:

OFN_SHAREFALLTHROUGH | Causes the dialog box to return the filename without warning the user about the sharing violation.
OFN_SHARENOWARN | Causes the dialog box to reject the filename without warning the user about the sharing violation.

Remarks

The system sends this notification only if the dialog box was created using the OFN_EXPLORER value.

The system sends this notification only if the the OFN_SHAREAWARE value was not specified when the dialog box was created.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, GetOpenFileName, GetSaveFileName, NMHDR, OFNHookProc, OFNOTIFY, OPENFILENAME, SetWindowLong, WM_NOTIFY


CDN_TYPECHANGE

The CDN_TYPECHANGE notification message is sent by an Explorer-style Open or Save As common dialog box when the user selects a new file type from the file types combo box. Your OFNHookProc hook procedure receives this message in the form of a WM_NOTIFY message.

CDN_TYPECHANGE
lpon = (LPOFNOTIFY) lParam;

Parameters

lpon
Address of an OFNOTIFY structure.

The OFNOTIFY structure contains an NMHDR structure whose code member indicates the CDN_TYPECHANGE notification code.

The OFNOTIFY structure also contains a pointer to an OPENFILENAME structure whose nFilterIndex member indicates the one-based index of the newly selected file type filter.

Return Values

The return value is ignored.

Remarks

The system sends this notification only if the dialog box was created using the OFN_EXPLORER value.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, GetOpenFileName, GetSaveFileName, NMHDR, OFNHookProc, OFNOTIFY, OPENFILENAME, WM_NOTIFY


COLOROKSTRING

A Color dialog box sends the COLOROKSTRING registered message to your hook procedure when the user selects a color and clicks the OK button. The hook procedure can accept the color and allow the dialog box to close, or reject the color and force the dialog box to remain open.

MessageID = RegisterWindowMessage(COLOROKSTRING);
wParam = 0;
lpcc = (LPCHOOSECOLOR) lParam;

Parameters

lpcc
Pointer to a CHOOSECOLOR structure. The rgbResult member of this structure contains the RGB color value of the selected color.

Return Values

If the hook procedure returns zero, the Color dialog box accepts the selected color and closes.

If the hook procedure returns a nonzero value, the Color dialog box rejects the selected color and remains open.

Remarks

The hook procedure must specify the COLOROKSTRING constant in a call to the RegisterWindowMessage function to get the identifier for the message sent by the dialog box.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.
Unicode: Defined as Unicode and ANSI messages.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, CHOOSECOLOR, RegisterWindowMessage


FILEOKSTRING

An Open or Save As dialog box sends the FILEOKSTRING registered message to your hook procedure when the user specifies a filename and clicks the OK button. The hook procedure can accept the filename and allow the dialog box to close, or reject the filename and force the dialog box to remain open.

For Explorer-style Open and Save As dialog boxes, this message has been superseded by the CDN_FILEOK notification message.

MessageID = RegisterWindowMessage(FILEOKSTRING);
wParam = 0;
lpofn = (LPOPENFILENAME) lParam;

Parameters

lpofn
Pointer to an OPENFILENAME structure. The lpstrFile member of this structure contains the drive, path, and filename specified by the user.

Return Values

If the hook procedure returns zero, the Open or Save As dialog box accepts the specified filename and closes.

If the hook procedure returns a nonzero value, the Open or Save As dialog box rejects the specified filename and remains open.

Remarks

The hook procedure must specify the FILEOKSTRING constant in a call to the RegisterWindowMessage function to get the identifier for the message sent by the dialog box.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.
Unicode: Defined as Unicode and ANSI messages.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, CDN_FILEOK, OPENFILENAME, RegisterWindowMessage


FINDMSGSTRING

A Find or Replace dialog box sends the FINDMSGSTRING registered message to the window procedure of its owner window when the user clicks the Find Next, Replace, or Replace All button, or closes the dialog box.

MessageID = RegisterWindowMessage(FINDMSGSTRING);
wParam = 0;
lpfr = (LPFINDREPLACE) lParam;

Parameters

lpfr
Pointer to a FINDREPLACE structure. The members of this structure contain the latest user input, including the string to search for, the replacement string (if any) and the search-and-replacement options.

Return Values

No return value.

Remarks

You must specify the FINDMSGSTRING constant in a call to the RegisterWindowMessage function to get the identifier for the message sent by the dialog box.

When you create the dialog box, use the hwndOwner member of the FINDREPLACE structure to identify the window to receive FINDMSGSTRING messages.

The Flags member of the FINDREPLACE structure includes one of the following flags to indicate the event that caused the message:

Flag | Meaning
FR_DIALOGTERM | The dialog box is closing. After the owner window processes this message, the handle of the dialog box is no longer valid.
FR_FINDNEXT | The user clicked the Find Next button in a Find or Replace dialog box. The lpstrFindWhat member specifies the string to search for.
FR_REPLACE | The user clicked the Replace button in a Replace dialog box. The lpstrFindWhat member specifies the string to replace and the lpstrReplaceWith member specifies the replacement string.
FR_REPLACEALL | The user clicked the Replace All button in a Replace dialog box. The lpstrFindWhat member specifies the string to replace and the lpstrReplaceWith member specifies the replacement string.

For a Find Next or Replace All message, the Flags member can include any combination of the following flags to indicate the search options:

Flag | Meaning
FR_DOWN | If set, the Down button of the direction radio buttons is selected indicating that user wants to search from the current location to the end of the document. If FR_DOWN is not set, the Up button is selected so the user wants to search to the beginning of the document.
FR_MATCHCASE | If set, the Match Case check box is checked indicating that the user wants the search to be case-sensitive. If FR_MATCHCASE is not set, the check box is unchecked so the search should be case-insensitive.
FR_WHOLEWORD | If set, the Match Whole Word Only check box is checked indicating that the user wants to search only for whole words that match the search string. If FR_WHOLEWORD is not set, the check box is unchecked so you should also search for word fragments that match the search string.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.
Unicode: Defined as Unicode and ANSI messages.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, FINDREPLACE, RegisterWindowMessage


HELPMSGSTRING

A common dialog box sends the HELPMSGSTRING registered message to the window procedure of its owner window when the user clicks the Help button.

For Explorer-style Open and Save As dialog boxes, this message has been superseded by the CDN_HELP notification message.

MessageID = RegisterWindowMessage(HELPMSGSTRING);
hdlg = (HWND) wParam;
lpStruct = (LPVOID) lParam;

Parameters

hdlg
Handle of the common dialog box.
lpStruct
Pointer to the initialization structure for the common dialog box. This structure can be a CHOOSECOLOR, CHOOSEFONT, FINDREPLACE, OPENFILENAME, PRINTDLG or PAGESETUPDLG structure.

Return Values

No return value.

Remarks

You must specify the HELPMSGSTRING constant in a call to the RegisterWindowMessage function to get the identifier for the message sent by the dialog box.

When you create the dialog box, use the hwndOwner member of the initialization structure to identify the window to receive HELPMSGSTRING messages.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.
Unicode: Defined as Unicode and ANSI messages.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, CDN_HELP, CHOOSECOLOR, CHOOSEFONT, FINDREPLACE, OPENFILENAME, PRINTDLG, PAGESETUPDLG, RegisterWindowMessage


LBSELCHSTRING

An Open or Save As dialog box sends the LBSELCHSTRING registered message to your hook procedure when the selection changes in any of the list boxes or combo boxes of the dialog box.

For Explorer-style Open and Save As dialog boxes, this message has been superseded by the CDN_SELCHANGE and CDN_TYPECHANGE messages.

MessageID = RegisterWindowMessage(LBSELCHSTRING);
idListBox = (UINT) wParam;
iItem = LOWORD (lParam);
iType = HIWORD (lParam);

Parameters

idListBox
Identifier of the list box or combo box in which the selection changed.
iItem
Item number of the selected string in the list box or combo box.
iType
Type of selection change. This parameter can be one of the following values:
CD_LBSELCHANGE | The item identified by iItem is the only item selected in a single-selection list box.
CD_LBSELADD | The item identified by iItem is one of the items selected in a multiple-selection list box.
CD_LBSELSUB | The item identified by iItem is no longer selected in a multiple-selection list box.
CD_LBSELNOITEMS | No items exist in a multiple-selection list box.

Return Values

No return value.

Remarks

The hook procedure must specify the LBSELCHSTRING constant in a call to the RegisterWindowMessage function to get the identifier for the message sent by the dialog box.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.
Unicode: Defined as Unicode and ANSI messages.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, CDN_SELCHANGE, CDN_TYPECHANGE, RegisterWindowMessage


SETRGBSTRING

The hook procedure of a Color dialog box can send the SETRGBSTRING registered message to the dialog box to set the current color selection.

MessageID = RegisterWindowMessage(SETRGBSTRING);
wParam = 0;
lParam = (COLORREF) rgbColor;

Parameters

rgbColor
Specifies the RGB value of the color to select in the Color dialog box. You can use the RGB macro to specify the red, green, and blue intensities of an RGB color value.

Return Values

No return value.

Remarks

If rgbColor matches one of the basic colors or one of the 16 custom colors, the dialog box procedure selects that color. The dialog box procedure also updates all the controls in the custom color extension of the Color dialog box, if it is open.

If rgbColor does not match a basic or custom color, the dialog box procedure does not change the current color selection, but it does update the custom color controls, if they are visible.

For example, the following sample code gets the SETRGBSTRING message identifier and then sets the color selection to blue.

UINT uiSetRGB;
uiSetRGB = RegisterWindowMessage(SETRGBSTRING);
SendMessage(hwndDlg, uiSetRGB, 0, (LPARAM) RGB(0, 0, 255));

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.
Unicode: Defined as Unicode and ANSI messages.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, RegisterWindowMessage, RGB, SendMessage


SHAREVISTRING

An Open or Save As dialog box sends the SHAREVISTRING registered message to your hook procedure if a sharing violation occurs for the selected file when the user clicks the OK button.

For Explorer-style Open and Save As dialog boxes, this message has been superseded by the CDN_SHAREVIOLATION notification message.

MessageID = RegisterWindowMessage(SHAREVISTRING);
wParam = 0;
lpofn = (LPOPENFILENAME) lParam;

Parameters

lpofn
Pointer to a OPENFILENAME structure. The lpstrFile member of this structure contains the filename that caused the sharing violation.

Return Values

The hook procedure must return one of the following values to indicate how the dialog box should handle the sharing violation:

Return value | Description
OFN_SHAREFALLTHROUGH | Accept the filename
OFN_SHARENOWARN | Reject the filename but do not warn the user. The application is responsible for displaying a warning message.
OFN_SHAREWARN | Rejects the filename and displays a warning message (the same result as if there were no hook procedure).

Remarks

The hook procedure must specify the SHAREVISTRING constant in a call to the RegisterWindowMessage function to get the identifier for the message sent by the dialog box.

The dialog box sends the SHAREVISTRING registered message only if you did not specify the OFN_SHAREAWARE flag in the Flags member of the OPENFILENAME structure when you created the dialog.

If the hook procedure returns an undefined value, the dialog box responds as if OFN_SHAREWARN was returned.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.
Unicode: Defined as Unicode and ANSI messages.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, CDN_SHAREVIOLATION, OPENFILENAME, RegisterWindowMessage


WM_CHOOSEFONT_GETLOGFONT

Send the WM_CHOOSEFONT_GETLOGFONT message to a Font dialog box to retrieve information about the user's current font selections.

WM_CHOOSEFONT_GETLOGFONT
wParam = 0;                // not used, must be zero
lParam = (LPLOGFONT) lplf; // address of struct. with font data

Parameters

lplf
Pointer to a LOGFONT structure that receives information about the user's current font selections.

Return Values

This message does not return a value.

Remarks

The ChooseFont function creates a Font dialog box. When the user closes the Font dialog box, the ChooseFont function returns information about the user's font selections in the CHOOSEFONT structure. The lpLogFont member of the CHOOSEFONT structure is a pointer to a LOGFONT structure.

Use the WM_CHOOSEFONT_GETLOGFONT message to get information about the user's current font selections while the Font dialog box is open. For example, if you enable the Apply button in the Font dialog box, send the message to get the font information to apply to the current text selection.

Typically, you enable a CFHookProc hook procedure to process WM_COMMAND messages for the Apply button. When the user clicks the Apply button, the hook procedure sends the WM_CHOOSEFONT_GETLOGFONT message to the dialog box.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, CFHookProc, ChooseFont, CHOOSEFONT, LOGFONT, WM_COMMAND


WM_CHOOSEFONT_SETFLAGS

Send the WM_CHOOSEFONT_SETFLAGS message to a Font dialog box to set the display options for the dialog box.

WM_CHOOSEFONT_SETFLAGS
wParam = 0;                   // not used, must be zero
lParam = (LPCHOOSEFONT) lpcf; // address of struct. with flags data

Parameters

lpcf
Pointer to a CHOOSEFONT structure that contains new settings in the Flags member.

Return Values

No return value.

Remarks

The ChooseFont function creates a Font dialog box and uses a CHOOSEFONT structure to specify the initial values for the Flags member. Use the WM_CHOOSEFONT_SETFLAGS message to specify different values for the Flags member while the Font dialog box is open.

Typically, you should send the WM_CHOOSEFONT_SETFLAGS message from a CFHookProc hook procedure.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, CFHookProc, ChooseFont, CHOOSEFONT


WM_CHOOSEFONT_SETLOGFONT

Send the WM_CHOOSEFONT_SETLOGFONT message to a Font dialog box to set the current logical font information.

WM_CHOOSEFONT_SETLOGFONT
wParam = 0;                // not used, must be zero
lParam = (LPLOGFONT) lplf; // pointer to structure with font data

Parameters

lplf
Pointer to a LOGFONT structure that contains information about the current logical font.

Return Values

No return value.

Remarks

When you call the ChooseFont function to create a Font dialog box, you can use the lpLogFont member of the CHOOSEFONT structure to specify a LOGFONT structure containing initial values for the dialog box. Use the WM_CHOOSEFONT_SETLOGFONT message to specify a LOGFONT structure with different values while the Font dialog box is open.

Typically, you would send the WM_CHOOSEFONT_SETLOGFONT message from a CFHookProc hook procedure. The hook procedure can also send the WM_CHOOSEFONT_GETLOGFONT and WM_CHOOSEFONT_SETFLAGS messages.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, CFHookProc, ChooseFont, CHOOSEFONT, LOGFONT, WM_CHOOSEFONT_GETLOGFONT, WM_CHOOSEFONT_SETFLAGS


WM_PSD_ENVSTAMPRECT

The WM_PSD_ENVSTAMPRECT message notifies the hook procedure of a Page Setup dialog box that the dialog box is about to draw the envelope-stamp rectangle of the sample page.

WM_PSD_ENVSTAMPRECT
hDC = (WPARAM) (HDC) wParam;           // handle of the device context
lprcEnvStamp = (LPARAM) (LPRECT) lParam; // envelope-stamp rectangle

Parameters

hDC
Value of wParam. Identifies the device context for the sample page.
lprcMargin
Value of lParam. Pointer to a RECT structure that contains the coordinates, in pixels, of the envelope-stamp rectangle.

Return Values

If the hook procedure returns TRUE, the dialog box does not draw the envelope-stamp portion of the sample page.

If the hook procedure returns FALSE, the dialog box draws the envelope-stamp portion of the sample page.

Remarks

The Page Setup dialog box includes an image of a sample page that shows how the user's selections affect the appearance of the printed output. When you call the PageSetupDlg function, you can provide a PagePaintHook hook procedure to customize the appearance of the sample page. Whenever the dialog box is about to draw the contents of the sample page, the dialog box sends a sequence of WM_PSD* messages to the hook procedure.

A hook procedure receives this message only if the selected paper type is an envelope.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, PagePaintHook, PageSetupDlg, RECT, WM_PSD_PAGESETUPDLG


WM_PSD_FULLPAGERECT

The WM_PSD_FULLPAGERECT message informs a PagePaintHook hook procedure of the coordinates of the sample page rectangle in the Page Setup dialog box. The dialog box sends this message when it is about to draw the contents of the sample page.

WM_PSD_FULLPAGERECT
hDC = (WPARAM) (HDC) wParam;         // handle of the device context
lprcPage = (LPARAM) (LPRECT) lParam; // dimensions of page rectangle

Parameters

hDC
Value of wParam. Handle of the device context for the sample page.
lprcPage
Value of lParam. Pointer to a RECT structure that contains the coordinates, in pixels, of the sample page.

Return Values

If the hook procedure returns TRUE, the dialog box sends no more WM_PSD* messages and does not draw in the sample page until the next time the system needs to redraw the sample page.

If the hook procedure returns FALSE, the dialog box sends the remaining messages of the drawing sequence.

Remarks

The Page Setup dialog box includes an image of a sample page that shows how the user's selections affect the appearance of the printed output. When you call the PageSetupDlg function, you can provide a PagePaintHook hook procedure to customize the appearance of the sample page. Whenever the dialog box is about to draw the contents of the sample page, the dialog box sends a sequence of WM_PSD* messages to the hook procedure.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, PagePaintHook, PageSetupDlg, RECT, WM_PSD_PAGESETUPDLG


WM_PSD_GREEKTEXTRECT

The WM_PSD_GREEKTEXTRECT message notifies the hook procedure of a Page Setup dialog box that the dialog box is about to draw Greek text inside the margin rectangle of the sample page.

WM_PSD_GREEKTEXTRECT
hDC = (WPARAM) (HDC) wParam;           // handle of the device context
lprcGreekText = (LPARAM) (LPRECT) lParam; // Greek text rectangle

Parameters

hDC
Value of wParam. Identifies the device context for the sample page.
lprcMargin
Value of lParam. Pointer to a RECT structure that contains the coordinates, in pixels, of the Greek text rectangle.

Return Values

If the hook procedure returns TRUE, the dialog box does not draw the Greek text portion of the sample page.

If the hook procedure returns FALSE, the dialog box draws the Greek text portion of the sample page.

Remarks

The Page Setup dialog box includes an image of a sample page that shows how the user's selections affect the appearance of the printed output. When you call the PageSetupDlg function, you can provide a PagePaintHook hook procedure to customize the appearance of the sample page. Whenever the dialog box is about to draw the contents of the sample page, the dialog box sends a sequence of WM_PSD* messages to the hook procedure.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, PagePaintHook, PageSetupDlg, RECT, WM_PSD_PAGESETUPDLG


WM_PSD_MARGINRECT

The WM_PSD_MARGINRECT message notifies the hook procedure of a Page Setup dialog box that the dialog box is about to draw the margin rectangle of the sample page.

WM_PSD_MARGINRECT
hDC = (WPARAM) (HDC) wParam;           // handle of the device context
lprcMargin = (LPARAM) (LPRECT) lParam; // margin rectangle

Parameters

hDC
Value of wParam. Identifies the device context for the sample page.
lprcMargin
Value of lParam. Pointer to a RECT structure that contains the coordinates, in pixels, of the margin rectangle.

Return Values

If the hook procedure returns TRUE, the dialog box does not draw the margin rectangle in the sample page.

If the hook procedure returns FALSE, the dialog box draws the margin rectangle in the sample page.

Remarks

The Page Setup dialog box includes an image of a sample page that shows how the user's selections affect the appearance of the printed output. When you call the PageSetupDlg function, you can provide a PagePaintHook hook procedure to customize the appearance of the sample page. Whenever the dialog box is about to draw the contents of the sample page, the dialog box sends a sequence of WM_PSD* messages to the hook procedure.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, PagePaintHook, PageSetupDlg, RECT, WM_PSD_PAGESETUPDLG


WM_PSD_MINMARGINRECT

The WM_PSD_MINMARGINRECT message informs a PagePaintHook hook procedure of the coordinates of the margin rectangle in the sample page. A Page Setup dialog box sends this message when it is about to draw the contents of the sample page.

WM_PSD_MINMARGINRECT
hDC = (WPARAM) (HDC) wParam;          // handle of the device context
lprcMinMargin = (LPARAM) (LPRECT) lParam; // minimum margin rectangle

Parameters

hDC
Value of wParam. Identifies the device context for the sample page.
lprcMinMargin
Value of lParam. Pointer to a RECT structure that contains the coordinates, in pixels, of the minimum margin rectangle.

Return Values

If the hook procedure returns TRUE, the dialog box sends no more WM_PSD* messages and does not draw in the sample page until the next time the system needs to redraw the sample page.

If the hook procedure returns FALSE, the dialog box sends the remaining messages of the drawing sequence.

Remarks

The Page Setup dialog box includes an image of a sample page that shows how the user's selections affect the appearance of the printed output. When you call the PageSetupDlg function, you can provide a PagePaintHook hook procedure to customize the appearance of the sample page. Whenever the dialog box is about to draw the contents of the sample page, the dialog box sends a sequence of WM_PSD* messages to the hook procedure.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, PagePaintHook, PageSetupDlg, RECT, WM_PSD_PAGESETUPDLG


WM_PSD_PAGESETUPDLG

The WM_PSD_PAGESETUPDLG message notifies a PagePaintHook hook procedure that the Page Setup dialog box is about to draw the contents of the sample page. The hook procedure can use this message to carry out initialization tasks related to drawing the contents of the sample page.

WM_PSD_PAGESETUPDLG
wPaper = LOWORD(wParam);         // paper-size flag
wFlags = HIWORD(wParam);         // paper-orientation flag
lppsd = (LPPAGESETUPDLG) lParam; // dialog box information

Parameters

wPaper
Value of the low-order word of wParam. Specifies a value that indicates the paper size. This value can be one of the DMPAPER_ values listed in the description of the DEVMODE structure.
wFlags
Value of the high-order word of wParam. Indicates the orientation of the paper or envelope, and whether the printer is a dot matrix or HPPCL (Hewlett Packard Printer Control Language) device. This parameter can be one of the following values:
0x0001 | Paper in landscape mode (dot matrix)
0x0003 | Paper in landscape mode (HPPCL)
0x0005 | Paper in portrait mode (dot matrix)
0x0007 | Paper in portrait mode (HPPCL)
0x000b | Envelope in landscape mode (HPPCL)
0x000d | Envelope in portrait mode (dot matrix)
0x0019 | Envelope in landscape mode (dot matrix)
0x001f | Envelope in portrait mode (HPPCL)

lppsd
Value of lParam. Points to a PAGESETUPDLG structure that contains information used to initialize the Page Setup dialog box.

Return Values

If the hook procedure returns TRUE, the dialog box sends no more WM_PSD* messages and does not draw in the sample page until the next time the system needs to redraw the sample page.

If the hook procedure returns FALSE, the dialog box sends the remaining messages of the drawing sequence.

Remarks

The Page Setup dialog box includes an image of a sample page that shows how the user's selections affect the appearance of the printed output. When you call the PageSetupDlg function, you can provide a PagePaintHook hook procedure to customize the appearance of the sample page. Whenever the dialog box is about to draw the contents of the sample page, the dialog box sends a sequence of WM_PSD* messages to the hook procedure.

The first three messages of a drawing sequence (WM_PSD_PAGESETUPDLG, WM_PSD_FULLPAGERECT, or WM_PSD_MINMARGINRECT) provide information that the hook procedure can use to draw the contents of the sample page. The remaining messages (WM_PSD_MARGINRECT, WM_PSD_GREEKTEXTRECT, WM_PSD_ENVSTAMPRECT, WM_PSD_YAFULLPAGERECT) notify the hook procedure that the dialog box is about to draw a specific portion of the sample page. This allows the hook procedure to selectively draw portions of the sample page.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, DEVMODE, PagePaintHook, PageSetupDlg, PAGESETUPDLG, WM_PSD_ENVSTAMPRECT, WM_PSD_FULLPAGERECT, WM_PSD_GREEKTEXTRECT, WM_PSD_MARGINRECT, WM_PSD_MINMARGINRECT, WM_PSD_YAFULLPAGERECT


WM_PSD_YAFULLPAGERECT

The WM_PSD_YAFULLPAGERECT message notifies the hook procedure of a Page Setup dialog box that the dialog box is about to draw the return address portion of an envelope sample page.

WM_PSD_YAFULLPAGERECT
hDC = (WPARAM) (HDC) wParam;               // handle of the device context
lprcYaFullPage = (LPARAM) (LPRECT) lParam; // dimensions of page rectangle

Parameters

hDC
Value of wParam. Handle of the device context for the sample page.
lprcPage
Value of lParam. Pointer to a RECT structure that contains the coordinates, in pixels, of the sample page.

Return Values

If the hook procedure returns TRUE, the dialog box does not draw the return address portion of an envelope sample page.

If the hook procedure returns FALSE, the dialog box draws the return address portion of an envelope sample page.

If the paper type is not an envelope, the return value has no effect.

Remarks

The Page Setup dialog box includes an image of a sample page that shows how the user's selections affect the appearance of the printed output. When you call the PageSetupDlg function, you can provide a PagePaintHook hook procedure to customize the appearance of the sample page. Whenever the dialog box is about to draw the contents of the sample page, the dialog box sends a sequence of WM_PSD* messages to the hook procedure.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, PagePaintHook, PageSetupDlg, RECT, WM_PSD_PAGESETUPDLG


Common Dialog Box Interfaces

The following Interfaces are used with the Common Dialog Box Library.

IPrintDialogCallback

IPrintDialogServices


IPrintDialogCallback

[This is preliminary documentation and subject to change.]

The IPrintDialogCallback interface enables an application to receive notifications and messages from the PrintDlgEx function while the Print property sheet is displayed.

When to Implement

Implement the IPrintDialogCallback interface if you are using the PrintDlgEx function and want to receive callback notifications and messages. You must implement the interface if you specify a custom dialog box template with application-specific controls. The HandleMessage method enables you to receive messages for the custom dialog box.

When you call PrintDlgEx, you can specify a pointer to your callback object in the lpCallback member of the PRINTDLGEX structure.

Typically, the callback object also contains the IObjectWithSite class. If you specify a callback object, PrintDlgEx calls QueryInterface for both IID_IPrintDialogCallback and IID_IObjectWithSite. If the callback object implements IObjectWithSite, PrintDlgEx calls the SetSite method to pass a pointer to an IPrintDialogServices interface to the application. The IPrintDialogCallback methods can use the IPrintDialogServices interface to retrieve information about the currently selected printer.

When to Use

Applications do not call the IPrintDialogCallback methods. The PrintDlgEx function calls the interface methods to pass information to the application.

Methods in VTable Order

IUnknown Methods

QueryInterface
AddRef
Release

IPrintDialogCallback Methods

Method | Description
InitDone | Called when the system has finished initializing the General page of the Print property sheet.
SelectionChange | Called when the user selects a different printer from the list of installed printers in the Print property sheet.
HandleMessage | Called to pass messages sent to the child dialog box in the lower portion of the General page.

See Also

IObjectWithSite, IPrintDialogServices, PrintDlgEx, PRINTDLGEX


IPrintDialogCallback::InitDone

[This is preliminary documentation and subject to change.]

The PrintDlgEx function calls the InitDone method when the system has finished initializing the General page of the Print property sheet.

HRESULT InitDone();

Parameters

None.

Return Values

Return S_OK to prevent the PrintDlgEx function from performing its default actions.

Return S_FALSE to allow PrintDlgEx to perform its default actions. Currently, PrintDlgEx does not perform any default processing after the InitDone call.

Remarks

If your callback object implements the IObjectWithSite interface, the PrintDlgEx function calls the IObjectWithSite::SetSite method to pass an IPrintDialogServices pointer to the callback object. The PrintDlgEx function calls the SetSite method before calling the InitDone method. This enables your InitDone implementation to use the IPrintDialogServices methods to retrieve information about the currently selected printer.

QuickInfo

Windows NT: Requires version 5.0 or later.
Windows: Unsupported.
Windows CE: Unsupported.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, IPrintDialogCallback, IObjectWithSite, IPrintDialogServices, PrintDlgEx


IPrintDialogCallback::HandleMessage

[This is preliminary documentation and subject to change.]

The PrintDlgEx function calls the HandleMessage method to give your application an opportunity to handle messages sent to the child dialog box in the lower portion of the General page of the Print property sheet. The child dialog box contains controls similar to those of the Print dialog box.

HRESULT HandleMessage(
  HWND hDlg,
  UINT uMsg,
  WPARAM wParam,
  LPARAM lParam,
  LRESULT *pResult
);

Parameters

hDlg
Handle to the child dialog box in the lower portion of the General page.
uMsg
Identifies the message being received.
wParam
Specifies additional information about the message. The exact meaning depends on the value of the uMsg parameter.
lParam
Specifies additional information about the message. The exact meaning depends on the value of the uMsg parameter.

If the uMsg parameter indicates the WM_INITDIALOG message, lParam is a pointer to a PRINTDLGEX structure containing the values specified when the property sheet was created.

pResult
Pointer to a variable that you should set to indicate the result to be returned by the dialog box for the message.

Return Values

Return S_OK if your HandleMessage implementation handled the message. In this case, the PrintDlgEx function does not perform any default message handling.

Return S_FALSE if you want PrintDlgEx to perform its default message handling.

Remarks

For notification messages passed by the WM_NOTIFY message, you must use the SetWindowLong function with the DWL_MSGRESULT value to set a return value. When you call SetWindowLong, use GetParent(hDlg) to set the DWL_MSGRESULT value of the General page, which is the parent of the child window.

The default dialog box procedure for the child window in the lower portion of the General page processes the WM_INITDIALOG message before passing it to the HandleMessage method. For all other messages sent to the child window, HandleMessage receives the message first. Then the HandleMessage return value determines whether the default dialog procedure processes the message or ignores it.

If HandleMessage processes the WM_CTLCOLORDLG message, it must return a valid brush handle for painting the background of the dialog box. In general, if HandleMessage processes any WM_CTLCOLOR* message, it must return a valid brush handle for painting the background of the specified control.

Do not call the EndDialog function from the HandleMessage method. Instead, HandleMessage can call the PostMessage function to post a WM_COMMAND message with the IDABORT value to the dialog box procedure. Posting IDABORT closes the Print property sheet and causes PrintDlgEx to return PD_RESULT_CANCEL in the dwResultAction member of the PRINTDLGEX structure. If you need to know why HandleMessage closed the dialog box, you must provide your own communication mechanism between the HandleMessage method and your application.

You can subclass the standard controls of the child dialog box in the lower portion of the General page. These standard controls are similar to those found in the Print dialog box. However, the default dialog box procedure may also subclass the controls. Because of this, you should subclass controls when HandleMessage processes the WM_INITDIALOG message. This ensures that your subclass procedure receives control-specific messages before the subclass procedure set by the dialog box procedure.

QuickInfo

Windows NT: Requires version 5.0 or later.
Windows: Unsupported.
Windows CE: Unsupported.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, IPrintDialogCallback, EndDialog, PostMessage, PrintDlgEx, PRINTDLGEX, SetWindowLong, WM_COMMAND, WM_CTLCOLORDLG, WM_INITDIALOG, WM_NOTIFY


IPrintDialogCallback::SelectionChange

[This is preliminary documentation and subject to change.]

The PrintDlgEx function calls the SelectionChange method when the user selects a different printer from the list of installed printers on the General page of the Print property sheet.

HRESULT SelectionChange();

Parameters

None.

Return Values

Return S_OK to prevent the PrintDlgEx function from performing its default actions.

Return S_FALSE to allow PrintDlgEx to perform its default actions, which include adjustments to the Copies, Collate, and Print Range items.

QuickInfo

Windows NT: Requires version 5.0 or later.
Windows: Unsupported.
Windows CE: Unsupported.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, IPrintDialogCallback, PrintDlgEx


IPrintDialogServices

[This is preliminary documentation and subject to change.]

The IPrintDialogServices interface enables an application using the PrintDlgEx function to retrieve information about the currently selected printer. This printer is indicated on the list of installed printers on the General page of the Print property sheet.

When to Implement

Applications do not implement the IPrintDialogServices interface. The PrintDlgEx function implements this interface.

When to Use

Applications that call the PrintDlgEx function can use the IPrintDialogServices interface to retrieve information about the currently selected printer while the Print property sheet is displayed. The IPrintDialogServices interface is useful for applications that implement the IPrintDialogCallback interface to process messages and notifications for the child dialog box in the lower portion of the General page.

The IPrintDialogServices interface is also useful for applications that create additional pages to follow the General page. The dialog box procedures for the additional pages can call IPrintDialogServices methods.

To retrieve a pointer to the IPrintDialogServices interface, implement a callback object that contains the IObjectWithSite class. When you call PrintDlgEx, you can specify a pointer to your callback object in the lpCallback member of the PRINTDLGEX structure. PrintDlgEx calls the IObjectWithSite::SetSite method to pass a pointer to an IPrintDialogServices interface to the application.

Methods in VTable Order

IUnknown Methods

QueryInterface
AddRef
Release

IPrintDialogServices Methods

Method | Description
GetCurrentDevMode | Fills a DEVMODE structure with information about the currently selected printer.
GetCurrentPrinterName | Retrieves the name of the currently selected printer.
GetCurrentPortName | Retrieves the name of the current port.


IPrintDialogServices::GetCurrentDevMode

[This is preliminary documentation and subject to change.]

An application using the PrintDlgEx function can call the GetCurrentDevMode method to fill a DEVMODE structure with information about the currently selected printer.

HRESULT GetCurrentDevMode(
  LPDEVMODE lpDevMode,
  UINT *pcbSize
);

Parameters

lpDevMode
Pointer to a buffer that receives a DEVMODE structure containing information about the currently selected printer.
pcbSize
Pointer to a UINT variable. On input, the variable specifies the size, in bytes, of the buffer pointed to by the lpDevMode parameter. On output, the variable contains the number of bytes written to lpDevMode.

If the size is zero on input, the function returns the required buffer size (in bytes) in pcbSize and does not use the lpDevMode buffer.

Return Values

If the method is successful, the return value is S_OK. If no printer is currently selected, the return value is S_OK, the value returned in pcbSize is zero, and the lpDevMode buffer is unchanged.

If an error occurs, the return value is a COM error code. For more information, see Error Handling.

QuickInfo

Windows NT: Requires version 5.0 or later.
Windows: Unsupported.
Windows CE: Unsupported.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, IPrintDialogServices, DEVMODE, PrintDlgEx


IPrintDialogServices::GetCurrentPortName

[This is preliminary documentation and subject to change.]

An application using the PrintDlgEx function can call the GetCurrentPortName method to retrieve the name of the current port.

HRESULT GetCurrentPortName(
  LPTSTR lpPortName,
  UINT *pcchSize
);

Parameters

lpPortName
Pointer to a buffer that receives the null-terminated name of the current port.
pcchSize
Pointer to a UINT variable. On input, the variable specifies the size, in bytes (ANSI version) or 16-bit characters (Unicode version), of the buffer pointed to by the lpPortName parameter. On output, the variable contains the number of bytes or characters, including the terminating null character, written to the buffer.

If the size is zero on input, the function returns the required buffer size (in bytes or characters) in pcchSize and does not use the lpPortName buffer.

Return Values

If the method is successful, the return value is S_OK. If there is no current port, the return value is S_OK, the value returned in pcchSize is zero, and the lpPortName buffer is unchanged.

If an error occurs, the return value is a COM error code. For more information, see Error Handling.

QuickInfo

Windows NT: Requires version 5.0 or later.
Windows: Unsupported.
Windows CE: Unsupported.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, IPrintDialogServices, PrintDlgEx


IPrintDialogServices::GetCurrentPrinterName

[This is preliminary documentation and subject to change.]

An application using the PrintDlgEx function can call the GetCurrentPrinterName method to retrieve the name of the currently selected printer.

HRESULT GetCurrentPrinterName(
  LPTSTR lpPrinterName,
  UINT *pcchSize
);

Parameters

lpPrinterName
Pointer to a buffer that receives the null-terminated name of the currently selected printer.
pcchSize
Pointer to a UINT variable. On input, the variable specifies the size, in bytes (ANSI version) or 16-bit characters (Unicode version), of the buffer pointed to by the lpPrinterName parameter. On output, the variable contains the number of bytes or characters, including the terminating null character, written to the buffer.

If the size is zero on input, the function returns the required buffer size (in bytes or characters) in pcchSize and does not use the lpPrinterName buffer.

Return Values

If the method is successful, the return value is S_OK. If no printer is currently selected, the return value is S_OK, the value returned in pcchSize is zero, and the lpPrinterName buffer is unchanged.

If an error occurs, the return value is a COM error code. For more information, see Error Handling.

QuickInfo

Windows NT: Requires version 5.0 or later.
Windows: Unsupported.
Windows CE: Unsupported.
Header: Declared in commdlg.h.

See Also

Common Dialog Box Library Overview, IPrintDialogServices, PrintDlgEx


Mouse Input

This overview describes how the system provides mouse input to your application and how the application receives and processes that input.


About Mouse Input

The mouse is an important, but optional, user-input device for Win32-based applications. A well-written Win32-based application should include a mouse interface, but it should not depend on the mouse as the sole means of acquiring user input. The application should provide full keyboard support as well.

A Win32-based application receives mouse input in the form of messages that are sent or posted to its windows.


Mouse Cursor

When the user moves the mouse, the system moves a bitmap on the screen called the mouse cursor. The mouse cursor contains a single-pixel point called the hot spot, a point that the system tracks and recognizes as the position of the cursor. When a mouse event occurs, the window that contains the hot spot typically receives the mouse message resulting from the event. The window need not be active or have the keyboard focus to receive a mouse message.

The system maintains a variable that controls the mouse speed — that is, the distance the cursor moves when the user moves the mouse. You can use the SystemParametersInfo function with the SPI_GETMOUSE or SPI_SETMOUSE flag to retrieve or set the mouse speed. For more information about mouse cursors, see Cursors.


Mouse Capture

The system typically posts a mouse message to the window that contains the cursor hot spot at the time a mouse event occurs. An application can change this behavior by using the SetCapture function to route mouse messages to a specific window. The window receives all mouse messages until the application calls the ReleaseCapture function or specifies another capture window, or until the user clicks a window created by another thread.

Whenever the mouse capture changes, the system sends a WM_CAPTURECHANGED message to the window that is losing the mouse capture. The lParam parameter of the message specifies the handle of the window that is gaining the mouse capture.

Only the foreground window can capture mouse input. When a background window attempts to capture mouse input, it receives messages only for mouse events that occur when the cursor hot spot is within the visible portion of the window.

Capturing mouse input is useful if a window must receive all mouse input, even when the cursor moves outside the window. For example, an application typically tracks the cursor position after a mouse "button down" event, following the cursor until a "button up" event occurs. If an application has not captured mouse input and the user releases the mouse button outside the window, the window does not receive the button up message.

A thread can use the GetCapture function to determine whether one of its windows has captured the mouse. If one of the thread's windows has captured the mouse, GetCapture retrieves the handle of the window.


Mouse Configuration

Although the mouse is an important input device for Win32-based applications, not every user necessarily has a mouse. An application can determine whether the system includes a mouse by passing the SM_MOUSEPRESENT value to the GetSystemMetrics function.

The Win32 API supports a mouse having up to three buttons. On a three-button mouse, the buttons are designated as the left, middle, and right buttons. Win32 messages and named constants related to the mouse buttons use the letters L, M, and R to identify the buttons. The button on a single-button mouse is considered to be the left button. Although the Win32 API supports a mouse with multiple buttons, most applications use the left button primarily and use the others little, if at all.

An application can determine the number of buttons on the mouse by passing the SM_CMOUSEBUTTONS value to the GetSystemMetrics function. To configure the mouse for a left-handed user, the application can use the SwapMouseButton function to reverse the meaning of the left and right mouse buttons. Passing the SPI_SETMOUSEBUTTONSWAP value to the SystemParametersInfo function is another way to reverse the meaning of the buttons. Note, however, that the mouse is a shared resource, so reversing the meaning of the buttons affects all applications.


Mouse Messages

The mouse generates an input event whenever the user moves the mouse, or presses or releases a mouse button. The system converts mouse input events into messages and posts them to the appropriate thread's message queue. When mouse messages are posted faster than a thread can process them, the system discards all but the most recent mouse message.

A window receives a mouse message when a mouse event occurs while the cursor is within the borders of the window, or when the window has captured the mouse. Mouse messages are divided into two groups: client area messages and nonclient area messages. Typically, an application processes client area messages and ignores nonclient area messages.


Client Area Mouse Messages

A window receives a client area mouse message when a mouse event occurs within the window's client area. The system posts the WM_MOUSEMOVE message to the window when the user moves the cursor within the client area. It posts one of the following messages when the user presses or releases a mouse button while the cursor is within the client area.

Message | Meaning
WM_LBUTTONDBLCLK | The left mouse button was double-clicked.
WM_LBUTTONDOWN | The left mouse button was pressed.
WM_LBUTTONUP | The left mouse button was released.
WM_MBUTTONDBLCLK | The middle mouse button was double-clicked.
WM_MBUTTONDOWN | The middle mouse button was pressed.
WM_MBUTTONUP | The middle mouse button was released.
WM_RBUTTONDBLCLK | The right mouse button was double-clicked.
WM_RBUTTONDOWN | The right mouse button was pressed.
WM_RBUTTONUP | The right mouse button was released.

Message Parameters

The lParam parameter of a client area mouse message indicates the position of the cursor hot spot. The low-order word indicates the x-coordinate of the hot spot, and the high-order word indicates the y-coordinate. The coordinates are given in client coordinates. In the client coordinate system, all points on the screen are given relative to the coordinates (0,0) of the upper left corner of the client area.

The wParam parameter contains flags that indicate the status of the other mouse buttons and the ctrl and shift keys at the time of the mouse event. You can check for these flags when mouse-message processing depends on the state of another mouse button or of the ctrl or shift key. The lParam parameter can be a combination of the following values.

Value | Meaning
MK_CONTROL | The ctrl key is down.
MK_LBUTTON | The left mouse button is down.
MK_MBUTTON | The middle mouse button is down.
MK_RBUTTON | The right mouse button is down.
MK_SHIFT | The shift key is down.

Double-Click Messages

The system generates a double-click message when the user clicks a mouse button twice in quick succession. When the user clicks a button, the system establishes a rectangle centered around the cursor hot spot. It also marks the time at which the click occurred. When the user clicks the same button a second time, the system determines whether the hot spot is still within the rectangle and calculates the time elapsed since the first click. If the hot spot is still within the rectangle and the elapsed time does not exceeded the double-click time-out value, the system generates a double-click message.

An application can get and set double-click time-out values by using the GetDoubleClickTime and SetDoubleClickTime functions, respectively. Alternatively, the application can set the double-click time-out value by using the SPI_SETDOUBLECLICKTIME flag with the SystemParametersInfo function. It can also set the size of the rectangle that the system uses to detect double-clicks by passing the SPI_SETDOUBLECLKWIDTH and SPI_SETDOUBLECLKHEIGHT flags to SystemParametersInfo. Note, however, that setting the double-click time-out value and rectangle affects all applications.

An application-defined window does not, by default, receive double-click messages. Because of the system overhead involved in generating double-click messages, these messages are generated only for windows belonging to classes that have the CS_DBLCLKS class style. Your application must set this style when registering the window class. For more information, see Window Classes.

A double-click message is always the third message in a four-message series. The first two messages are the button down and button up messages generated by the first click. The second click generates the double-click message followed by another button up message. For example, double-clicking the left mouse button generates the following message sequence:

WM_LBUTTONDOWN
WM_LBUTTONUP
WM_LBUTTONDBLCLK
WM_LBUTTONUP

Because a window always receives a button down message before receiving a double-click message, an application typically uses a double-click message to extend a task it began during a button down message. For example, when the user clicks a color in the color palette of Microsoft Paint, Paint displays the selected color next to the palette. When the user double-clicks a color, Paint displays the color and opens the Edit Colors dialog box.


Nonclient Area Mouse Messages

A window receives a nonclient area mouse message when a mouse event occurs in any part of a window except the client area. A window's nonclient area consists of its border, menu bar, title bar, scroll bar, window menu, minimize button, and maximize button.

The system generates nonclient area messages primarily for its own use. For example, the system uses nonclient area messages to change the cursor to a two-headed arrow when the cursor hot spot moves into a window's border. A window must pass nonclient area mouse messages to the DefWindowProc function to take advantage of the built-in mouse interface.

There is a corresponding nonclient area mouse message for each client area mouse message. The names of these messages are similar except that the named constants for the nonclient area messages include the letters "NC". For example, moving the cursor in the nonclient area generates a WM_NCMOUSEMOVE message, and pressing the left mouse button while the cursor is in the nonclient area generates a WM_NCLBUTTONDOWN message.

The lParam parameter of a nonclient area mouse message is a POINTS structure that contains the x- and y-coordinates of the cursor hot spot. Unlike coordinates of client area mouse messages, the coordinates are given in screen coordinates rather than client coordinates. In the screen coordinate system, all points on the screen are relative to the coordinates (0,0) of the upper left corner of the screen.

The wParam parameter contains a hit-test value, a value that indicates where in the nonclient area the mouse event occurred. The following section explains the purpose of hit-test values.


The WM_NCHITTEST Message

Whenever a mouse event occurs, the system sends a WM_NCHITTEST message to either the window that contains the cursor hot spot or the window that has captured the mouse. The system uses this message to determine whether to send a client area or nonclient area mouse message. An application that must receive mouse movement and mouse button messages must pass the WM_NCHITTEST message to the DefWindowProc function.

The lParam parameter of the WM_NCHITTEST message contains the screen coordinates of the cursor hot spot. The DefWindowProc function examines the coordinates and returns a hit-test value that identifies the location of the hot spot. The hit-test value can be one of the following values.

Value | Location of hot spot
HTBORDER | In the border of a window that does not have a sizing border
HTBOTTOM | In the lower horizontal border of a window
HTBOTTOMLEFT | In the lower left corner of a window border
HTBOTTOMRIGHT | In the lower right corner of a window border
HTCAPTION | In a title bar
HTCLIENT | In a client area
HTCLOSE | In close button.
HTERROR | On the screen background or on a dividing line between windows (same as HTNOWHERE, except that the DefWindowProc function produces a system beep to indicate an error)
HTGROWBOX | In a size box (same as HTSIZE)
HTHELP | In Help button.
HTHSCROLL | In a horizontal scroll bar
HTLEFT | In the left border of a window
HTMENU | In a menu
HTMAXBUTTON | In Maximize button.
HTMINBUTTON | In Minimize button.
HTNOWHERE | On the screen background or on a dividing line between windows
HTREDUCE | In a Minimize button
HTRIGHT | In the right border of a window
HTSIZE | In a size box (same as HTGROWBOX)
HTSYSMENU | In a System menu or in a Close button in a child window
HTTOP | In the upper horizontal border of a window
HTTOPLEFT | In the upper left corner of a window border
HTTOPRIGHT | In the upper right corner of a window border
HTTRANSPARENT | In a window currently covered by another window in the same thread
HTVSCROLL | In the vertical scroll bar
HTZOOM | In a Maximize button

If the cursor is in the client area of a window, DefWindowProc returns the HTCLIENT hit-test value to the window procedure. When the window procedure returns this code to the system, the system converts the screen coordinates of the cursor hot spot to client coordinates, and then posts the appropriate client area mouse message.

The DefWindowProc function returns one of the other hit-test values when the cursor hot spot is in a window's nonclient area. When the window procedure returns one of these hit-test values, the system posts a nonclient area mouse message, placing the hit-test value in the message's wParam parameter and the cursor coordinates in the lParam parameter.


Window Activation

When the user clicks an inactive top-level window or the child window of a inactive top-level window, the system sends the WM_MOUSEACTIVATE message (among others) to the top-level or child window. The system sends this message after posting the WM_NCHITTEST message to the window, but before posting the button down message. When WM_MOUSEACTIVATE is passed to the DefWindowProc function, the system activates the top-level window and then posts the button down message to the top-level or child window.

By processing WM_MOUSEACTIVATE, a window can control whether the top-level window becomes the active window as a result of a mouse click, and whether the window that was clicked receives the subsequent button down message. It does so by returning one of the following values after processing WM_MOUSEACTIVATE.

Value | Meaning
MA_ACTIVATE | Activates the window and does not discard the mouse message.
MA_NOACTIVATE | Does not activate the window and does not discard the mouse message.
MA_ACTIVATEANDEAT | Activates the window and discards the mouse message.
MA_NOACTIVATEANDEAT | Does not activate the window but discards the mouse message.


Using Mouse Input

  • Tracking the mouse cursor
  • Drawing lines with the mouse
  • Processing a double-click message
  • Selecting a line of text


Tracking the Mouse Cursor

Win32-based applications often perform tasks that involve tracking the position of the mouse cursor. Most drawing applications, for example, track it during drawing operations, allowing the user to draw in a window's client area by dragging the mouse. Word-processing applications also track the cursor, enabling the user to select a word or block of text by clicking and dragging the mouse.

Tracking the cursor typically involves processing the WM_LBUTTONDOWN, WM_MOUSEMOVE, and WM_LBUTTONUP messages. A window determines when to begin tracking the cursor by checking the cursor position provided in the lParam parameter of the WM_LBUTTONDOWN message. For example, a word-processing application would begin tracking the cursor only if the WM_LBUTTONDOWN message occurred while the cursor was on a line of text, but not if it was past the end of the document.

A window tracks the position of the cursor by processing the stream of WM_MOUSEMOVE messages posted to the window as the mouse moves. Processing the WM_MOUSEMOVE message typically involves a repetitive painting or drawing operation in the client area. For example, a drawing application might redraw a line repeatedly as the mouse moves. A window uses the WM_LBUTTONUP message as a signal to stop tracking the cursor.


Drawing Lines with the Mouse

The example in this section demonstrates how to track the mouse cursor. It contains portions of a window procedure that enables the user to draw lines in a window's client area by dragging the mouse.

When the window procedure receives a WM_LBUTTONDOWN message, it captures the mouse and saves the coordinates of the cursor, using the coordinates as the starting point of the line. It also uses the ClipCursor function to confine the cursor to the client area during the line drawing operation.

During the first WM_MOUSEMOVE message, the window procedure draws a line from the starting point to the current position of the cursor. During subsequent WM_MOUSEMOVE messages, the window procedure erases the previous line by drawing over it with an inverted pen color. Then it draws a new line from the starting point to the new position of the cursor.

The WM_LBUTTONUP message signals the end of the drawing operation. The window procedure releases the mouse capture and frees the mouse from the client area.

LRESULT APIENTRY MainWndProc(HWND hwndMain, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    HDC hdc;                       // handle of device context
    RECT rcClient;                 // client area rectangle
    POINT ptClientUL;              // client upper left corner
    POINT ptClientLR;              // client lower right corner
    static POINTS ptsBegin;        // beginning point
    static POINTS ptsEnd;          // new endpoint
    static POINTS ptsPrevEnd;      // previous endpoint
    static BOOL fPrevLine = FALSE; // previous line flag

    switch (uMsg)
    {
        case WM_LBUTTONDOWN:

            // Capture mouse input.

            SetCapture(hwndMain);

            // Retrieve the screen coordinates of the client area,
            // and convert them into client coordinates.

            GetClientRect(hwndMain, &rcClient);
            ptClientUL.x = rcClient.left;
            ptClientUL.y = rcClient.top;

            // Add one to the right and bottom sides, because the
            // coordinates retrieved by GetClientRect do not
            // include the far left and lowermost pixels.

            ptClientLR.x = rcClient.right + 1;
            ptClientLR.y = rcClient.bottom + 1;
            ClientToScreen(hwndMain, &ptClientUL);
            ClientToScreen(hwndMain, &ptClientLR);

            // Copy the client coordinates of the client area
            // to the rcClient structure. Confine the mouse cursor
            // to the client area by passing the rcClient structure
            // to the ClipCursor function.

            SetRect(&rcClient, ptClientUL.x, ptClientUL.y,
                ptClientLR.x, ptClientLR.y);
            ClipCursor(&rcClient);

            // Convert the cursor coordinates into a POINTS
            // structure, which defines the beginning point of the
            // line drawn during a WM_MOUSEMOVE message.

            ptsBegin = MAKEPOINTS(lParam);
            return 0;

        case WM_MOUSEMOVE:

            // When moving the mouse, the user must hold down
            // the left mouse button to draw lines.

            if (wParam & MK_LBUTTON)
            {

                // Retrieve a device context (DC) for the client area.

                hdc = GetDC(hwndMain);

                // The following function ensures that pixels of
                // the previously drawn line are set to white and
                // those of the new line are set to black.

                SetROP2(hdc, R2_NOTXORPEN);

                // If a line was drawn during an earlier WM_MOUSEMOVE
                // message, draw over it. This erases the line by
                // setting the color of its pixels to white.

                if (fPrevLine)
                {
                    MoveToEx(hdc, ptsBegin.x, ptsBegin.y,
                        (LPPOINT) NULL);
                    LineTo(hdc, ptsPrevEnd.x, ptsPrevEnd.y);
                }

                // Convert the current cursor coordinates to a
                // POINTS structure, and then draw a new line.

                ptsEnd = MAKEPOINTS(lParam);
                MoveToEx(hdc, ptsBegin.x, ptsBegin.y, (LPPOINT) NULL);
                LineTo(hdc, ptsEnd.x, ptsEnd.y);

                // Set the previous line flag, save the ending
                // point of the new line, and then release the DC.

                fPrevLine = TRUE;
                ptsPrevEnd = ptsEnd;
                ReleaseDC(hwndMain, hdc);
            }
            break;

        case WM_LBUTTONUP:

            // The user has finished drawing the line. Reset the
            // previous line flag, release the mouse cursor, and
            // release the mouse capture.

            fPrevLine = FALSE;
            ClipCursor(NULL);
            ReleaseCapture();
            return 0;

        case WM_DESTROY:
            PostQuitMessage(0);
            break;

        // Process other messages.


Processing a Double-Click Message

To receive double-click messages, a window must belong to a window class that has the CS_DBLCLKS class style. You set this style when registering the window class, as shown in the following example.

BOOL InitApplication(HINSTANCE hInstance)
{
    WNDCLASS wc;

    wc.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = (WNDPROC) MainWndProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = hInstance;
    wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wc.hCursor = LoadCursor(NULL, IDC_IBEAM);
    wc.hbrBackground = GetStockObject(WHITE_BRUSH);
    wc.lpszMenuName = "MainMenu";
    wc.lpszClassName = "MainWClass";

    return RegisterClass(&wc);
}

A double-click message is always preceded by a button down message. For this reason, applications typically use a double-click message to extend a task that it began during a button down message.


Selecting a Line of Text

The example in this section is taken from a simple word-processing application. It includes code that enables the user to set the position of the caret by clicking anywhere on a line of text, and to select (highlight) a line of text by double-clicking anywhere on the line.

LRESULT APIENTRY MainWndProc(HWND hwndMain, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    HDC hdc;                     // handle of device context
    TEXTMETRIC tm;               // font size data
    int i, j;                    // loop counters
    int cCR = 0;                 // count of carriage returns
    char ch;                     // character from input buffer
    static int nBegLine;         // beginning of selected line
    static int nCurrentLine = 0; // currently selected line
    static int nLastLine = 0;    // last text line
    static int nCaretPosX = 0;   // x-coordinate of caret
    static int cch = 0;          // number of characters entered
    static int nCharWidth = 0;   // exact width of a character
    static char szHilite[128];   // text string to highlight
    static DWORD dwCharX;        // average width of characters
    static DWORD dwLineHeight;   // line height
    static POINTS ptsCursor;     // coordinates of mouse cursor
    static COLORREF crPrevText;  // previous text color
    static COLORREF crPrevBk;    // previous background color
    static PTCHAR pchInputBuf;   // address of input buffer
    static BOOL fTextSelected = FALSE; // text-selection flag

    switch (uMsg)
    {
        case WM_CREATE:

            // Get the metrics of the current font.

            hdc = GetDC(hwndMain);
            GetTextMetrics(hdc, &tm);
            ReleaseDC(hwndMain, hdc);

            // Save the average character width and height.

            dwCharX = tm.tmAveCharWidth;
            dwLineHeight = tm.tmHeight;

            // Allocate a buffer to store keyboard input.

            pchInputBuf = (LPSTR) GlobalAlloc(GPTR,
                BUFSIZE * sizeof(TCHAR));

            return 0;

        case WM_CHAR:
            switch (wParam)
            {
                case 0x08:  // backspace
                case 0x0A:  // linefeed
                case 0x1B:  // escape
                    MessageBeep(0xFFFFFFFF);
                    return 0;

                case 0x09:  // tab

                    // Convert tabs to four consecutive spaces.

                    for (i = 0; i < 4; i++)
                        SendMessage(hwndMain, WM_CHAR, 0x20, 0);
                    return 0;

                case 0x0D:  // carriage return

                    // Record the carriage return, and position the
                    // caret at the beginning of the new line.

                    pchInputBuf[cch++] = 0x0D;
                    nCaretPosX = 0;
                    nCurrentLine += 1;
                    break;

                default:    / displayable character

                    ch = (char) wParam;
                    HideCaret(hwndMain);

                    // Retrieve the character's width, and display the
                    // character.

                    hdc = GetDC(hwndMain);
                    GetCharWidth32(hdc, (UINT) wParam, (UINT) wParam,
                        &nCharWidth);
                    TextOut(hdc, nCaretPosX,
                        nCurrentLine * dwLineHeight, &ch, 1);
                    ReleaseDC(hwndMain, hdc);

                    // Store the character in the buffer.

                    pchInputBuf[cch++] = ch;

                    // Calculate the new horizontal position of the
                    // caret. If the new position exceeds the maximum,
                    // insert a carriage return and reposition the
                    // caret at the beginning of the next line.

                    nCaretPosX += nCharWidth;
                    if ((DWORD) nCaretPosX > dwMaxCharX)
                    {
                        nCaretPosX = 0;
                        pchInputBuf[cch++] = 0x0D;
                        ++nCurrentLine;
                    }

                    ShowCaret(hwndMain);

                    break;
            }
            SetCaretPos(nCaretPosX, nCurrentLine * dwLineHeight);
            nLastLine = max(nLastLine, nCurrentLine);
            break;

        // Process other messages.

        case WM_LBUTTONDOWN:

            // If a line of text is currently highlighted, redraw
            // the text to remove the highlighting.

            if (fTextSelected)
            {
                hdc = GetDC(hwndMain);
                SetTextColor(hdc, crPrevText);
                SetBkColor(hdc, crPrevBk);
                TextOut(hdc, 0, nCurrentLine * dwLineHeight,
                    szHilite, lstrlen(szHilite));
                ReleaseDC(hwndMain, hdc);
                ShowCaret(hwndMain);
                fTextSelected = FALSE;
            }

            // Save the current mouse-cursor coordinates.

            ptsCursor = MAKEPOINTS(lParam);

            // Determine which line the cursor is on, and save
            // the line number. Do not allow line numbers greater
            // than the number of the last line of text. The
            // line number is later multiplied by the average height
            // of the current font. The result is used to set the
            // y-coordinate of the caret.

            nCurrentLine = min((int)(ptsCursor.y / dwLineHeight),
                nLastLine);

            // Parse the text input buffer to find the first
            // character in the selected line of text. Each
            // line ends with a carriage return, so it is possible
            // to count the carriage returns to find the selected
            // line.

            cCR = 0;
            nBegLine = 0;
            if (nCurrentLine != 0)
            {
                for (i = 0; (i < cch) &&
                        (cCR < nCurrentLine); i++)
                {
                    if (pchInputBuf[i] == 0x0D)
                        ++cCR;
                }
                nBegLine = i;
            }

            // Starting at the beginning of the selected line,
            // measure  the width of each character, summing the
            // width with each character measured. Stop when the
            // sum is greater than the x-coordinate of the cursor.
            // The sum is used to set the x-coordinate of the caret.

            hdc = GetDC(hwndMain);
            nCaretPosX = 0;
            for (i = nBegLine;
                (pchInputBuf[i] != 0x0D) && (i < cch); i++)
            {
                ch = pchInputBuf[i];
                GetCharWidth32(hdc, (int) ch, (int) ch, &nCharWidth);
                if ((nCaretPosX + nCharWidth) > ptsCursor.x) break;
                else nCaretPosX += nCharWidth;
            }
            ReleaseDC(hwndMain, hdc);

            // Set the caret to the user-selected position.

            SetCaretPos(nCaretPosX, nCurrentLine * dwLineHeight);
            break;

        case WM_LBUTTONDBLCLK:

            // Copy the selected line of text to a buffer.

            for (i = nBegLine, j = 0; (pchInputBuf[i] != 0x0D) &&
                    (i < cch); i++)
            {
                szHilite[j++] = pchInputBuf[i];
            }
            szHilite[j] = '\0';

            // Hide the caret, invert the background and foreground
            // colors, and then redraw the selected line.

            HideCaret(hwndMain);
            hdc = GetDC(hwndMain);
            crPrevText = SetTextColor(hdc, RGB(255, 255, 255));
            crPrevBk = SetBkColor(hdc, RGB(0, 0, 0));
            TextOut(hdc, 0, nCurrentLine * dwLineHeight, szHilite,
                lstrlen(szHilite));
            SetTextColor(hdc, crPrevText);
            SetBkColor(hdc, crPrevBk);
            ReleaseDC(hwndMain, hdc);

            fTextSelected = TRUE;
            break;

            // Process other messages.

        default:
            return DefWindowProc(hwndMain, uMsg, wParam, lParam);
    }
    return NULL;
}


Mouse Input Reference

The following elements are associated with mouse input.

  • Mouse Input Functions
  • Mouse Input Structures
  • Mouse Input Messages


Mouse Input Functions

The following functions are used with mouse input.

DragDetect
GetCapture
GetDoubleClickTime
GetMouseMovePoints
mouse_event
ReleaseCapture
SetCapture
SetDoubleClickTime
SwapMouseButton
TrackMouseEvent


DragDetect

The DragDetect function captures the mouse and tracks its movement until the user releases the left button, presses the esc key, or moves the mouse outside the "drag rectangle" around the specified point. The width and height of the drag rectangle are specified by the SM_CXDRAG and SM_CYDRAG values returned by the GetSystemMetrics function.

BOOL DragDetect(
  HWND hwnd,
  POINT pt
);

Parameters

hwnd
Handle to the window receiving mouse input.
pt
Initial position of the mouse, in screen coordinates. The function determines the coordinates of the drag rectangle by using this point.

Return Values

If the user moved the mouse outside of the drag rectangle while holding the left button down, the return value is nonzero.

If the user did not move the mouse outside of the drag rectangle while holding the left button down, the return value is zero.

Remarks

The system metrics for the drag rectangle are configurable, allowing for larger or smaller drag rectangles.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Mouse Input Overview, Mouse Input Functions, GetSystemMetrics


GetCapture

The GetCapture function retrieves the handle of the window (if any) that has captured the mouse. Only one window at a time can capture the mouse; this window receives mouse input whether or not the cursor is within its borders.

HWND GetCapture(VOID)

Parameters

This function has no parameters.

Return Values

The return value is the handle of the capture window associated with the current thread. If no window in the thread has captured the mouse, the return value is NULL.

Remarks

A NULL return value does not mean no other thread or process in the system has captured the mouse; it just means the current thread has not captured the mouse.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Mouse Input Overview, Mouse Input Functions, ReleaseCapture, SetCapture


GetDoubleClickTime

The GetDoubleClickTime function retrieves the current double-click time for the mouse. A double-click is a series of two clicks of the mouse button, the second occurring within a specified time after the first. The double-click time is the maximum number of milliseconds that may occur between the first and second click of a double-click.

UINT GetDoubleClickTime(VOID)

Parameters

This function has no parameters.

Return Values

The return value specifies the current double-click time, in milliseconds.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Mouse Input Overview, Mouse Input Functions, SetDoubleClickTime


GetMouseMovePoints

[This is preliminary documentation and subject to change.]

The GetMouseMovePoints function retrieves a history of up to 64 previous coordinates of the mouse or pen.

int GetMouseMovePoints(
  UINT cbSize                // size of the MOUSEMOVEPOINT struct
  LPMOUSEMOVEPOINT lppt,     // pointer to current mouse move point
  LPMOUSEMOVEPOINT lpptBuf,  // buffer to store the points
  int nBufPoints,            // how many points the buffer can store
  DWORD resolution           // resolution of the points
);

Parameters

cbSize
Size of the MOUSEMOVEPOINT structure.
lppt
Pointer to a MOUSEMOVEPOINT structure containing valid mouse coordinates (in screen coordinates). It may also contain a time stamp.

The GetMouseMovePoints function searches for the point in the mouse coordinates history. If the function finds the point, it returns the last nBufPoints prior to and including the supplied point.

If your application supplies a time stamp, the GetMouseMovePoints function will use it to differentiate between two equal points that were recorded at different times.

An application should call this function using the mouse coordinates received from the WM_MOUSEMOVE message and convert them to screen coordinates.

lpptBuf
Pointer to a buffer that will receive the points. It should be at least cbSize*nBuffPoints in size.
nBufPoints
Specifies the number of points to retrieve.
resolution
Specifies the resolution desired. This parameter can be one of the following values.
Value | Meaning
GMMP_USE_DISPLAY_POINTS | Retrieves the points using the display resolution.
GMMP_USE_DRIVER_POINTS | Retrieves the points using the driver resolution. The Windows CE platform supports pen drivers with a resolution much higher than the display resolution. In this case, GetMouseMovePoints can be used by applications (such as handwriting recognition software or computer-aided design software) that need a much more accurate resolution.

Return Values

If the function succeeds, the return value is the number of points in the buffer. Otherwise, the function returns –1. For extended error information, your application can call GetLastError. The GetLastError function may return the following error code.

Value | Meaning
GMMP_ERR_POINT_NOT_FOUND | The point specified by lppt is could not be found or is no longer in the system buffer.

Remarks

The system retains the last 64 mouse coordinates and their time stamps. If your application supplies a mouse coordinate to GetMouseMovePoints and the coordinate exists in the system's mouse coordinate history, the function retrieves the specified number of coordinates from the systems' history. You can also supply a time stamp, which will be used to differentiate between identical points in the history.

The GetMouseMovePoints function will return points that eventually were dispatched not only to the calling thread but also to other threads.

QuickInfo

Windows NT: Requires version 5.0 or later.
Windows: Requires Windows 98.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Mouse Input Overview, Mouse Input Functions, MOUSEMOVEPOINT


mouse_event

The mouse_event function synthesizes mouse motion and button clicks.

Windows NT: This function has been superseded. Use SendInput instead.

VOID mouse_event(
  DWORD dwFlags, // flags specifying various motion/click variants
  DWORD dx,      // horizontal mouse position or position change
  DWORD dy,      // vertical mouse position or position change
  DWORD dwData,  // amount of wheel movement
  DWORD dwExtraInfo
                 // 32 bits of application-defined information
);

Parameters

dwFlags
A set of flag bits that specify various aspects of mouse motion and button clicking. The bits in this parameter can be any reasonable combination of the following values:
Value | Meaning
MOUSEEVENTF_ABSOLUTE | Specifies that the dx and dy parameters contain normalized absolute coordinates. If not set, those parameters contain relative data: the change in position since the last reported position. This flag can be set, or not set, regardless of what kind of mouse or mouse-like device, if any, is connected to the system. For further information about relative mouse motion, see the following Remarks section.
MOUSEEVENTF_MOVE | Specifies that movement occurred.
MOUSEEVENTF_LEFTDOWN | Specifies that the left button is down.
MOUSEEVENTF_LEFTUP | Specifies that the left button is up.
MOUSEEVENTF_RIGHTDOWN | Specifies that the right button is down.
MOUSEEVENTF_RIGHTUP | Specifies that the right button is up.
MOUSEEVENTF_MIDDLEDOWN | Specifies that the middle button is down.
MOUSEEVENTF_MIDDLEUP | Specifies that the middle button is up.
MOUSEEVENTF_WHEEL | Windows NT: Specifies that the wheel has been moved, if the mouse has a wheel. The amount of movement is given in dwData

dx
Specifies the mouse's absolute position along the x-axis or its amount of motion since the last mouse event was generated, depending on the setting of MOUSEEVENTF_ABSOLUTE. Absolute data is given as the mouse's actual x-coordinate; relative data is given as the number of mickeys moved. A mickey is the amount that a mouse has to move for it to report that it has moved.
dy
Specifies the mouse's absolute position along the y-axis or its amount of motion since the last mouse event was generated, depending on the setting of MOUSEEVENTF_ABSOLUTE. Absolute data is given as the mouse's actual y-coordinate; relative data is given as the number of mickeys moved.
dwData
If dwFlags is MOUSEEVENTF_WHEEL, then dwData specifies the amount of wheel movement. A positive value indicates that the wheel was rotated forward, away from the user; a negative value indicates that the wheel was rotated backward, toward the user. One wheel click is defined as WHEEL_DELTA, which is 120.

If dwFlags is not MOUSEEVENTF_WHEEL, then dwData should be zero.

dwExtraInfo
Specifies an additional 32-bit value associated with the mouse event. An application calls GetMessageExtraInfo to obtain this extra information.

Return Values

This function has no return value.

Remarks

If the mouse has moved, indicated by MOUSEEVENTF_MOVE being set, dx and dy hold information about that motion. The information is given as absolute or relative integer values.

If MOUSEEVENTF_ABSOLUTE value is specified, dx and dy contain normalized absolute coordinates between 0 and 65,535. The event procedure maps these coordinates onto the display surface. Coordinate (0,0) maps onto the upper-left corner of the display surface, (65535,65535) maps onto the lower-right corner.

If the MOUSEEVENTF_ABSOLUTE value is not specified, dx and dy specify relative motions from when the last mouse event was generated (the last reported position). Positive values mean the mouse moved right (or down); negative values mean the mouse moved left (or up).

Relative mouse motion is subject to the settings for mouse speed and acceleration level. An end user sets these values using the Mouse control panel application. An application obtains and sets these values with the SystemParametersInfo function.

The system applies two tests to the specified relative mouse motion when applying acceleration. If the specified distance along either the x or y axis is greater than the first mouse threshold value, and the mouse acceleration level is not zero, the operating system doubles the distance. If the specified distance along either the x or y axis is greater than the second mouse threshold value, and the mouse acceleration level is equal to two, the operating system doubles the distance that resulted from applying the first threshold test. It is thus possible for the operating system to multiply relatively-specified mouse motion along the x or y axis by up to four times.

Once acceleration has been applied, the system scales the resultant value by the desired mouse speed. Mouse speed can range from 1 (slowest) to 20 (fastest) and represents how much the pointer moves based on the distance the mouse moves. The default value is 10, which results in no additional modification to the mouse motion.

The mouse_event function is used to synthesize mouse events by applications that need to do so. It is also used by applications that need to obtain more information from the mouse than its position and button state. For example, if a tablet manufacturer wants to pass pen-based information to its own applications, it can write a dynamic-link library (DLL) that communicates directly to the tablet hardware, obtains the extra information, and saves it in a queue. The DLL then calls mouse_event with the standard button and x/y position data, along with, in the dwExtraInfo parameter, some pointer or index to the queued extra information. When the application needs the extra information, it calls the DLL with the pointer or index stored in dwExtraInfo, and the DLL returns the extra information.

Windows CE: Windows CE does not support the MOUSEEVENTF_WHEEL constant in the dwFlags parameter.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Mouse Input Overview, Mouse Input Functions, GetMessageExtraInfo, SystemParametersInfo


ReleaseCapture

The ReleaseCapture function releases the mouse capture from a window in the current thread and restores normal mouse input processing. A window that has captured the mouse receives all mouse input, regardless of the position of the cursor, except when a mouse button is clicked while the cursor hot spot is in the window of another thread.

BOOL ReleaseCapture(VOID)

Parameters

This function has no parameters.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

An application calls this function after calling the SetCapture function.

Windows 95: Calling ReleaseCapture causes the window that is losing the mouse capture to receive a WM_CAPTURECHANGED message.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Mouse Input Overview, Mouse Input Functions, GetCapture, SetCapture, WM_CAPTURECHANGED


SetCapture

The SetCapture function sets the mouse capture to the specified window belonging to the current thread. Once a window has captured the mouse, all mouse input is directed to that window, regardless of whether the cursor is within the borders of that window. Only one window at a time can capture the mouse.

If the mouse cursor is over a window created by another thread, the system will direct mouse input to the specified window only if a mouse button is down.

HWND SetCapture(
  HWND hWnd   // handle of window to receive mouse capture
);

Parameters

hWnd
Handle to the window in the current thread that is to capture the mouse.

Return Values

The return value is the handle of the window that had previously captured the mouse. If there is no such window, the return value is NULL.

Remarks

Only the foreground window can capture the mouse. When a background window attempts to do so, the window receives messages only for mouse events that occur when the cursor hot spot is within the visible portion of the window. Also, even if the foreground window has captured the mouse, the user can still click another window, bringing it to the foreground.

When the window no longer requires all mouse input, the thread that created the window should call the ReleaseCapture function to release the mouse.

This function cannot be used to capture mouse input meant for another process.

Windows 95: Calling SetCapture causes the window that is losing the mouse capture to receive a WM_CAPTURECHANGED message.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Mouse Input Overview, Mouse Input Functions, GetCapture, ReleaseCapture, WM_CAPTURECHANGED


SetDoubleClickTime

The SetDoubleClickTime function sets the double-click time for the mouse. A double-click is a series of two clicks of a mouse button, the second occurring within a specified time after the first. The double-click time is the maximum number of milliseconds that may occur between the first and second clicks of a double-click.

BOOL SetDoubleClickTime(
  UINT uInterval   // double-click interval
);

Parameters

uInterval
Specifies the number of milliseconds that may occur between the first and second clicks of a double-click. If this parameter is set to zero, the system uses the default double-click time of 500 milliseconds.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The SetDoubleClickTime function alters the double-click time for all windows in the system.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Mouse Input Overview, Mouse Input Functions, GetDoubleClickTime


SwapMouseButton

The SwapMouseButton function reverses or restores the meaning of the left and right mouse buttons.

BOOL SwapMouseButton(
  BOOL fSwap   // reverse or restore buttons
);

Parameters

fSwap
Specifies whether the mouse button meanings are reversed or restored. If this parameter is TRUE, the left button generates right-button messages and the right button generates left-button messages. If this parameter is FALSE, the buttons are restored to their original meanings.

Return Values

If the meaning of the mouse buttons was reversed previously, before the function was called, the return value is nonzero.

If the meaning of the mouse buttons was not reversed, the return value is zero.

Remarks

Button swapping is provided as a convenience to people who use the mouse with their left hands. The SwapMouseButton function is usually called by Control Panel only. Although an application is free to call the function, the mouse is a shared resource and reversing the meaning of its buttons affects all applications.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Mouse Input Overview, Mouse Input Functions, SetDoubleClickTime


TrackMouseEvent

The TrackMouseEvent function posts messages when the mouse pointer leaves a window or hovers over a window for a specified amount of time.

BOOL TrackMouseEvent(
  LPTRACKMOUSEEVENT lpEventTrack  // pointer to a TRACKMOUSEEVENT
                                  // structure
);

Parameters

lpEventTrack
Pointer to a TRACKMOUSEEVENT structure.

Return Values

If the function succeeds, the return value is nonzero .

If the function fails, return value is zero. To get extended error information, call GetLastError.

The messages that the function can post are the following:

Message | Meaning
WM_MOUSEHOVER | The mouse hovered over the client area of the window for the period of time specified in a prior call to TrackMouseEvent. Hover tracking stops when this message is generated. The application must call TrackMouseEvent again if it requires further tracking of mouse hover behavior.
WM_MOUSELEAVE | The mouse left the client area of the window specified in a prior call to TrackMouseEvent. All tracking requested by TrackMouseEvent is canceled when this message is generated. The application must call TrackMouseEvent when the mouse re-enters its window if it requires further tracking of mouse hover behavior.

Remarks

The mouse pointer is considered to be hovering when it stays within a specified rectangle for a specified period of time. Call SystemParametersInfo and use the values SPI_GETMOUSEHOVERWIDTH, SPI_GETMOUSEHOVERHEIGHT, and SPI_GETMOUSEHOVERTIME to retrieve the size of the rectangle and the time.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 98.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Mouse Input Overview, Mouse Input Functions, SystemParametersInfo , TRACKMOUSEEVENT


Mouse Input Structures

The following strucutres are used with mouse input.

MOUSEMOVEPOINT
TRACKMOUSEEVENT


MOUSEMOVEPOINT

[This is preliminary documentation and subject to change.]

The MOUSEMOVEPOINT structure contains information about the mouse's location in screen coordinates.

typedef struct tagMOUSEMOVEPOINT {
    int   x;
    int   y;
    DWORD time;
    DWORD dwExtraInfo;
} MOUSEMOVEPOINT, *PMOUSEMOVEPOINT, FAR* LPMOUSEMOVEPOINT;

Members

x
Identifies the x-coordinate of the mouse.
y
Identifies the y-coordinate of the mouse.
time
Specifies the time stamp of the mouse coordinate.
dwExtraInfo
Specifies extra information associated with this coordinate.

QuickInfo

Windows NT: Requires version 5.0 or later.
Windows: Requires Windows 98 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Mouse Input Overview, Mouse Input Structures, GetMouseMovePoints


TRACKMOUSEEVENT

The TRACKMOUSEEVENT structure is used by the TrackMouseEvent function to track when the mouse pointer leaves a window or hovers over a window for a specified amount of time.

typedef struct tagTRACKMOUSEEVENT {
    DWORD cbSize;
    DWORD dwFlags;
    HWND  hwndTrack;
    DWORD dwHoverTime;
} TRACKMOUSEEVENT, *LPTRACKMOUSEEVENT;

Members

cbSize
Specifies the size of the TRACKMOUSEEVENT structure.
dwFlags
Specifies the services requested. This member can be a combination of the following values:
Value | Meaning
TME_CANCEL The caller wants to cancel a prior tracking request.

The caller should also specify the type of tracking that it wants to cancel. For example, to cancel hover tracking, the caller must pass the TME_CANCEL and TME_HOVER flags.
TME_HOVER The caller wants hover notification. Notification is delivered as a WM_MOUSEHOVER message.

If the caller requests hover tracking while hover tracking is already active, the hover timer will be reset.

This flag is ignored if the mouse pointer is not over the specified window or area.
TME_LEAVE The caller wants leave notification. Notification is delivered as a WM_MOUSELEAVE message.

If the mouse is not over the specified window or area, a leave notification is generated immediately and no further tracking is performed.
TME_QUERY | The function fills in the structure instead of treating it as a tracking request. The structure is filled such that had that structure been passed to TrackMouseEvent it would generate the current tracking. The only anomaly is that the hover timeout returned is always the actual timeout and not HOVER_DEFAULT, if HOVER_DEFAULT was specified during the original TrackMouseEvent request.

hwndTrack
Specifies the handle of the window to track.
dwHoverTime
Specifies the hover timeout (if TME_HOVER was specified in dwFlags), in milliseconds. Can be HOVER_DEFAULT, which means to use the system default hover timeout.

Remarks

The system default hover timeout is initially the menu dropdown time, which is 400 milliseconds. You can call SystemParametersInfo and use SPI_GETMOUSEHOVERTIME to retrieve the default hover timeout.

The system default hover rectangle is the same as the double-click rectangle. You can call SystemParametersInfo and use SPI_GETMOUSEHOVERWIDTH and SPI_GETMOUSEHOVERHEIGHT to retrieve the size of the rectangle within which the mouse pointer has to stay for TrackMouseEvent to generate a WM_MOUSEHOVER message.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 98 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Mouse Input Overview, Mouse Input Structures, SystemParametersInfo ,
TrackMouseEvent


Mouse Input Messages

The following messages are used with mouse input.

WM_CAPTURECHANGED
WM_LBUTTONDBLCLK
WM_LBUTTONDOWN
WM_LBUTTONUP
WM_MBUTTONDBLCLK
WM_MBUTTONDOWN
WM_MBUTTONUP
WM_MOUSEACTIVATE
WM_MOUSEMOVE
WM_MOUSEWHEEL
WM_NCHITTEST
WM_NCLBUTTONDBLCLK
WM_NCLBUTTONDOWN
WM_NCLBUTTONUP
WM_NCMBUTTONDBLCLK
WM_NCMBUTTONDOWN
WM_NCMBUTTONUP
WM_NCMOUSEMOVE
WM_NCRBUTTONDBLCLK
WM_NCRBUTTONDOWN
WM_NCRBUTTONUP
WM_RBUTTONDBLCLK
WM_RBUTTONDOWN
WM_RBUTTONUP


WM_CAPTURECHANGED

The WM_CAPTURECHANGED message is sent to the window that is losing the mouse capture.

WM_CAPTURECHANGED
hwndNewCapture = (HWND) lParam;    // handle of window to gain mouse capture

Parameters

hwndNewCapture
Value of lParam. Handle to the window that is gaining the mouse capture.

Return Values

An application should return zero if it processes this message.

Remarks

A window receives this message even if it calls ReleaseCapture itself. An application should not attempt to set the mouse capture in response to this message.

When it receives this message, a window should redraw itself, if necessary, to reflect the new mouse-capture state.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Mouse Input Overview, Mouse Input Messages, ReleaseCapture, SetCapture


WM_LBUTTONDBLCLK

The WM_LBUTTONDBLCLK message is posted when the user double-clicks the left mouse button while the cursor is in the client area of a window. If the mouse is not captured, the message is posted to the window beneath the cursor. Otherwise, the message is posted to the window that has captured the mouse.

WM_LBUTTONDBLCLK
fwKeys = wParam;        // key flags
xPos = LOWORD(lParam);  // horizontal position of cursor
yPos = HIWORD(lParam);  // vertical position of cursor

Parameters

fwKeys
Value of wParam. Indicates whether various virtual keys are down. This parameter can be any combination of the following values:
Value | Description
MK_CONTROL | Set if the ctrl key is down.
MK_LBUTTON | Set if the left mouse button is down.
MK_MBUTTON | Set if the middle mouse button is down.
MK_RBUTTON | Set if the right mouse button is down.
MK_SHIFT | Set if the shift key is down.

xPos
Value of the low-order word of lParam. Specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.
yPos
Value of the high-order word of lParam. Specifies the y-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

Return Values

If an application processes this message, it should return zero.

Remarks

Only windows that have the CS_DBLCLKS style can receive WM_LBUTTONDBLCLK messages, which the system generates whenever the user presses, releases, and again presses the left mouse button within the system's double-click time limit. Double-clicking the left mouse button actually generates four messages: WM_LBUTTONDOWN, WM_LBUTTONUP, WM_LBUTTONDBLCLK, and WM_LBUTTONUP again.

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Mouse Input Overview, Mouse Input Messages, GetCapture, GetDoubleClickTime, MAKEPOINTS, POINTS, SetCapture, SetDoubleClickTime, WM_LBUTTONDOWN, WM_LBUTTONUP


WM_LBUTTONDOWN

The WM_LBUTTONDOWN message is posted when the user presses the left mouse button while the cursor is in the client area of a window. If the mouse is not captured, the message is posted to the window beneath the cursor. Otherwise, the message is posted to the window that has captured the mouse.

WM_LBUTTONDOWN
fwKeys = wParam;        // key flags
xPos = LOWORD(lParam);  // horizontal position of cursor
yPos = HIWORD(lParam);  // vertical position of cursor

Parameters

fwKeys
Value of wParam. Indicates whether various virtual keys are down. This parameter can be any combination of the following values:
Value | Description
MK_CONTROL | Set if the ctrl key is down.
MK_LBUTTON | Set if the left mouse button is down.
MK_MBUTTON | Set if the middle mouse button is down.
MK_RBUTTON | Set if the right mouse button is down.
MK_SHIFT | Set if the shift key is down.

xPos
Value of the low-order word of lParam. Specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.
yPos
Value of the high-order word of lParam. Specifies the y-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

Return Values

If an application processes this message, it should return zero.

Remarks

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Mouse Input Overview, Mouse Input Messages, GetCapture, MAKEPOINTS, POINTS, SetCapture, WM_LBUTTONDBLCLK, WM_LBUTTONUP


WM_LBUTTONUP

The WM_LBUTTONUP message is posted when the user releases the left mouse button while the cursor is in the client area of a window. If the mouse is not captured, the message is posted to the window beneath the cursor. Otherwise, the message is posted to the window that has captured the mouse.

WM_LBUTTONUP
fwKeys = wParam;        // key flags
xPos = LOWORD(lParam);  // horizontal position of cursor
yPos = HIWORD(lParam);  // vertical position of cursor

Parameters

fwKeys
Value of wParam. Indicates whether various virtual keys are down. This parameter can be any combination of the following values:
Value | Description
MK_CONTROL | Set if the ctrl key is down.
MK_MBUTTON | Set if the middle mouse button is down.
MK_RBUTTON | Set if the right mouse button is down.
MK_SHIFT | Set if the shift key is down.

xPos
Value of the low-order word of lParam. Specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.
yPos
Value of the high-order word of lParam. Specifies the y-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

Return Values

If an application processes this message, it should return zero.

Remarks

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Mouse Input Overview, Mouse Input Messages, GetCapture, MAKEPOINTS, POINTS, SetCapture, WM_LBUTTONDBLCLK, WM_LBUTTONDOWN


WM_MBUTTONDBLCLK

The WM_MBUTTONDBLCLK message is posted when the user double-clicks the middle mouse button while the cursor is in the client area of a window. If the mouse is not captured, the message is posted to the window beneath the cursor. Otherwise, the message is posted to the window that has captured the mouse.

WM_MBUTTONDBLCLK
fwKeys = wParam;        // key flags
xPos = LOWORD(lParam);  // horizontal position of cursor
yPos = HIWORD(lParam);  // vertical position of cursor

Parameters

fwKeys
Value of wParam. Indicates whether various virtual keys are down. This parameter can be any combination of the following values:
Value | Description
MK_CONTROL | Set if the ctrl key is down.
MK_LBUTTON | Set if the left mouse button is down.
MK_MBUTTON | Set if the middle mouse button is down.
MK_RBUTTON | Set if the right mouse button is down.
MK_SHIFT | Set if the shift key is down.

xPos
Value of the low-order word of lParam. Specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.
yPos
Value of the high-order word of lParam. Specifies the y-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

Return Values

If an application processes this message, it should return zero.

Remarks

Only windows that have the CS_DBLCLKS style can receive WM_MBUTTONDBLCLK messages, which the system generates whenever the user presses, releases, and again presses the middle mouse button within the system's double-click time limit. Double-clicking the middle mouse button actually generates four messages: WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MBUTTONDBLCLK, and WM_MBUTTONUP again.

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Mouse Input Overview, Mouse Input Messages, GetCapture, GetDoubleClickTime, MAKEPOINTS, POINTS, SetCapture, SetDoubleClickTime, WM_MBUTTONDOWN, WM_MBUTTONUP


WM_MBUTTONDOWN

The WM_MBUTTONDOWN message is posted when the user presses the middle mouse button while the cursor is in the client area of a window. If the mouse is not captured, the message is posted to the window beneath the cursor. Otherwise, the message is posted to the window that has captured the mouse.

WM_MBUTTONDOWN
fwKeys = wParam;        // key flags
xPos = LOWORD(lParam);  // horizontal position of cursor
yPos = HIWORD(lParam);  // vertical position of cursor

Parameters

fwKeys
Value of wParam. Indicates whether various virtual keys are down. This parameter can be any combination of the following values:
Value | Description
MK_CONTROL | Set if the ctrl key is down.
MK_LBUTTON | Set if the left mouse button is down.
MK_MBUTTON | Set if the middle mouse button is down.
MK_RBUTTON | Set if the right mouse button is down.
MK_SHIFT | Set if the shift key is down.

xPos
Value of the low-order word of lParam. Specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.
yPos
Value of the high-order word of lParam. Specifies the y-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

Return Values

If an application processes this message, it should return zero.

Remarks

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Mouse Input Overview, Mouse Input Messages, GetCapture, MAKEPOINTS, POINTS, SetCapture, WM_MBUTTONDBLCLK, WM_MBUTTONUP


WM_MBUTTONUP

The WM_MBUTTONUP message is posted when the user releases the middle mouse button while the cursor is in the client area of a window. If the mouse is not captured, the message is posted to the window beneath the cursor. Otherwise, the message is posted to the window that has captured the mouse.

WM_MBUTTONUP
fwKeys = wParam;        // key flags
xPos = LOWORD(lParam);  // horizontal position of cursor
yPos = HIWORD(lParam);  // vertical position of cursor

Parameters

fwKeys
Value of wParam. Indicates whether various virtual keys are down. This parameter can be any combination of the following values:
Value | Description
MK_CONTROL | Set if the ctrl key is down.
MK_LBUTTON | Set if the left mouse button is down.
MK_RBUTTON | Set if the right mouse button is down.
MK_SHIFT | Set if the shift key is down.

xPos
Value of the low-order word of lParam. Specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.
yPos
Value of the high-order word of lParam. Specifies the y-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Mouse Input Overview, Mouse Input Messages, GetCapture, MAKEPOINTS, POINTS, SetCapture, WM_MBUTTONDBLCLK, WM_MBUTTONDOWN


WM_MOUSEACTIVATE

The WM_MOUSEACTIVATE message is sent when the cursor is in an inactive window and the user presses a mouse button. The parent window receives this message only if the child window passes it to the DefWindowProc function.

WM_MOUSEACTIVATE
hwndTopLevel = (HWND) wParam;       // handle of top-level parent
nHittest = (INT) LOWORD(lParam);    // hit-test value
uMsg =    (UINT) HIWORD(lParam);    // mouse message

Parameters

hwndTopLevel
Value of wParam. Handle to the top-level parent window of the window being activated.
nHittest
Value of the low-order word of lParam. Specifies the hit-test value returned by the DefWindowProc function as a result of processing the WM_NCHITTEST message. For a list of hit-test values, see WM_NCHITTEST.
uMsg
Value of the high-order word of lParam. Specifies the identifier of the mouse message generated when the user pressed a mouse button. The mouse message is either discarded or posted to the window, depending on the return value.

Return Values

The return value specifies whether the window should be activated and whether the identifier of the mouse message should be discarded. It must be one of the following values:

Value | Meaning
MA_ACTIVATE | Activates the window, and does not discard the mouse message.
MA_ACTIVATEANDEAT | Activates the window, and discards the mouse message.
MA_NOACTIVATE | Does not activate the window, and does not discard the mouse message.
MA_NOACTIVATEANDEAT | Does not activate the window, but discards the mouse message.

Default Action

The DefWindowProc function passes the message to a child window's parent window before any processing occurs. The parent window determines whether to activate the child window. If it activates the child window, the parent window should return MA_NOACTIVATE or MA_NOACTIVATEANDEAT to prevent the system from processing the message further.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, WM_NCHITTEST


WM_MOUSEMOVE

The WM_MOUSEMOVE message is posted to a window when the cursor moves. If the mouse is not captured, the message is posted to the window that contains the cursor. Otherwise, the message is posted to the window that has captured the mouse.

WM_MOUSEMOVE
fwKeys = wParam;        // key flags
xPos = LOWORD(lParam);  // horizontal position of cursor
yPos = HIWORD(lParam);  // vertical position of cursor

Parameters

fwKeys
Value of wParam. Indicates whether various virtual keys are down. This parameter can be any combination of the following values:
Value | Description
MK_CONTROL | Set if the ctrl key is down.
MK_LBUTTON | Set if the left mouse button is down.
MK_MBUTTON | Set if the middle mouse button is down.
MK_RBUTTON | Set if the right mouse button is down.
MK_SHIFT | Set if the shift key is down.

xPos
Value of the low-order word of lParam. Specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.
yPos
Value of the high-order word of lParam. Specifies the y-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

Remarks

The MAKEPOINTS macro can be used to convert the lParam parameter to a POINTS structure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Mouse Input Overview, Mouse Input Messages, GetCapture, MAKEPOINTS, POINTS, SetCapture


WM_MOUSEWHEEL

The WM_MOUSEWHEEL message is sent to the focus window when the mouse wheel is rotated. The DefWindowProc function propagates the message to the window's parent. There should be no internal forwarding of the message, since DefWindowProc propagates it up the parent chain until it finds a window that processes it.

WM_MOUSEWHEEL
fwKeys = LOWORD(wParam);    // key flags
zDelta = (short) HIWORD(wParam);    // wheel rotation
xPos = (short) LOWORD(lParam);    // horizontal position of pointer
yPos = (short) HIWORD(lParam);    // vertical position of pointer

Parameters

fwKeys
Value of the low-order word of wParam. Indicates whether various virtual keys are down. This parameter can be any combination of the following values:
Value | Description
MK_CONTROL | Set if the ctrl key is down.
MK_LBUTTON | Set if the left mouse button is down.
MK_MBUTTON | Set if the middle mouse button is down.
MK_RBUTTON | Set if the right mouse button is down.
MK_SHIFT | Set if the shift key is down.

zDelta
The value of the high-order word of wParam. Indicates the distance that the wheel is rotated, expressed in multiples or divisions of WHEEL_DELTA, which is 120. A positive value indicates that the wheel was rotated forward, away from the user; a negative value indicates that the wheel was rotated backward, toward the user.
xPos
Value of the low-order word of lParam. Specifies the x-coordinate of the pointer, relative to the upper-left corner of the screen.
yPos
Value of the high-order word of lParam. Specifies the y-coordinate of the pointer, relative to the upper-left corner of the screen.

Remarks

The zDelta parameter will be a multiple of WHEEL_DELTA, which is set at 120. This is the threshold for action to be taken, and one such action (for example, scrolling one increment) should occur for each delta.

The delta was set to 120 to allow Microsoft or other vendors to build finer-resolution wheels in the future, including perhaps a freely-rotating wheel with no notches. The expectation is that such a device would send more messages per rotation, but with a smaller value in each message. To support this possibility, you should either add the incoming delta values until WHEEL_DELTA is reached (so for a given delta-rotation you get the same response), or scroll partial lines in response to the more frequent messages. You could also choose your scroll granularity and accumulate deltas until it is reached.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 98.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Mouse Input Overview, Mouse Input Messages, GetSystemMetrics, mouse_event, SystemParametersInfo


WM_NCHITTEST

The WM_NCHITTEST message is sent to a window when the cursor moves, or when a mouse button is pressed or released. If the mouse is not captured, the message is sent to the window beneath the cursor. Otherwise, the message is sent to the window that has captured the mouse.

WM_NCHITTEST
xPos = LOWORD(lParam);  // horizontal position of cursor
yPos = HIWORD(lParam);  // vertical position of cursor

Parameters

xPos
Value of the low-order word of lParam. Specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the screen.
yPos
Value of the high-order word of lParam. Specifies the y-coordinate of the cursor. The coordinate is relative to the upper-left corner of the screen.

Return Values

The return value of the DefWindowProc function is one of the following values, indicating the position of the cursor hot spot:

Value | Location of hot spot
HTBORDER | In the border of a window that does not have a sizing border
HTBOTTOM | In the lower horizontal border of a resizable window (the user can click the mouse to resize the window vertically)
HTBOTTOMLEFT | In the lower-left corner of a border of a resizable window (the user can click the mouse to resize the window diagonally)
HTBOTTOMRIGHT | In the lower-right corner of a border of a resizable window (the user can click the mouse to resize the window diagonally)
HTCAPTION | In a title bar
HTCLIENT | In a client area
HTCLOSE | In a close button
HTERROR | On the screen background or on a dividing line between windows (same as HTNOWHERE, except that the DefWindowProc function produces a system beep to indicate an error)
HTGROWBOX | In a size box (same as HTSIZE)
HTHELP | In a Help button
HTHSCROLL | In a horizontal scroll bar
HTLEFT | In the left border of a resizable window (the user can click the mouse to resize the window horizontally)
HTMENU | In a menu
HTMAXBUTTON | In Maximize button
HTMINBUTTON | In Minimize button
HTNOWHERE | On the screen background or on a dividing line between windows
HTREDUCE | In a Minimize button
HTRIGHT | In the right border of a resizable window (the user can click the mouse to resize the window horizontally)
HTSIZE | In a size box (same as HTGROWBOX)
HTSYSMENU | In a System menu or in a Close button in a child window
HTTOP | In the upper horizontal border of a window
HTTOPLEFT | In the upper-left corner of a window border
HTTOPRIGHT | In the upper right corner of a window border
HTTRANSPARENT | In a window currently covered by another window in the same thread (the message will be sent to underlying windows in the same thread until one of them returns a code that is not HTTRANSPARENT)
HTVSCROLL | In the vertical scroll bar
HTZOOM | In a Maximize button

Remarks

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, MAKEPOINTS, POINTS


WM_NCLBUTTONDBLCLK

The WM_NCLBUTTONDBLCLK message is posted when the user double-clicks the left mouse button while the cursor is within the nonclient area of a window. This message is posted to the window that contains the cursor. If a window has captured the mouse, this message is not posted.

WM_NCLBUTTONDBLCLK
nHittest = (INT) wParam;    // hit-test value
pts = MAKEPOINTS(lParam);   // position of cursor

Parameters

nHittest
Value of wParam. Specifies the hit-test value returned by the DefWindowProc function as a result of processing the WM_NCHITTEST message. For a list of hit-test values, see WM_NCHITTEST.
pts
Value of lParam. Specifies a POINTS structure that contains the x- and y-coordinates of the cursor. The coordinates are relative to the upper-left corner of the screen.

Return Values

If an application processes this message, it should return zero.

Default Action

The DefWindowProc function tests the given point to find out the location of the cursor and performs the appropriate action. If appropriate, DefWindowProc sends the WM_SYSCOMMAND message to the window.

Remarks

A window need not have the CS_DBLCLKS style to receive WM_NCLBUTTONDBLCLK messages.

The system generates a WM_NCLBUTTONDBLCLK message when the user presses, releases, and again presses the left mouse button within the system's double-click time limit. Double-clicking the left mouse button actually generates four messages: WM_NCLBUTTONDOWN, WM_NCLBUTTONUP, WM_NCLBUTTONDBLCLK, and WM_NCLBUTTONUP again.

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, MAKEPOINTS, POINTS, WM_NCHITTEST, WM_NCLBUTTONDOWN, WM_NCLBUTTONUP, WM_SYSCOMMAND


WM_NCLBUTTONDOWN

The WM_NCLBUTTONDOWN message is posted when the user presses the left mouse button while the cursor is within the nonclient area of a window. This message is posted to the window that contains the cursor. If a window has captured the mouse, this message is not posted.

WM_NCLBUTTONDOWN
nHittest = (INT) wParam;    // hit-test value
pts = MAKEPOINTS(lParam);   // position of cursor

Parameters

nHittest
Value of wParam. Specifies the hit-test value returned by the DefWindowProc function as a result of processing the WM_NCHITTEST message. For a list of hit-test values, see WM_NCHITTEST.
pts
Value of lParam. Specifies a POINTS structure that contains the x- and y-coordinates of the cursor. The coordinates are relative to the upper-left corner of the screen.

Return Values

If an application processes this message, it should return zero.

Default Action

The DefWindowProc function tests the given point to find out the location of the cursor and performs the appropriate action. If appropriate, DefWindowProc sends the WM_SYSCOMMAND message to the window.

Remarks

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, MAKEPOINTS, POINTS, WM_NCHITTEST, WM_NCLBUTTONDBLCLK, WM_NCLBUTTONUP, WM_SYSCOMMAND


WM_NCLBUTTONUP

The WM_NCLBUTTONUP message is posted when the user releases the left mouse button while the cursor is within the nonclient area of a window. This message is posted to the window that contains the cursor. If a window has captured the mouse, this message is not posted.

WM_NCLBUTTONUP
nHittest = (INT) wParam;    // hit-test value
pts = MAKEPOINTS(lParam);   // mouse-cursor coordinates

Parameters

nHittest
Value of wParam. Specifies the hit-test value returned by the DefWindowProc function as a result of processing the WM_NCHITTEST message. For a list of hit-test values, see WM_NCHITTEST.
pts
Value of lParam. Specifies a POINTS structure that contains the x- and y-coordinates of the cursor. The coordinates are relative to the upper-left corner of the screen.

Return Values

If an application processes this message, it should return zero.

Default Action

The DefWindowProc function tests the given point to find out the location of the cursor and performs the appropriate action. If appropriate, DefWindowProc sends the WM_SYSCOMMAND message to the window.

Remarks

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

If it is appropriate to do so, the system sends the WM_SYSCOMMAND message to the window.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, MAKEPOINTS, POINTS, WM_NCHITTEST, WM_NCLBUTTONDBLCLK, WM_NCLBUTTONDOWN, WM_SYSCOMMAND


WM_NCMBUTTONDBLCLK

The WM_NCMBUTTONDBLCLK message is posted when the user double-clicks the middle mouse button while the cursor is within the nonclient area of a window. This message is posted to the window that contains the cursor. If a window has captured the mouse, this message is not posted.

WM_NCMBUTTONDBLCLK
nHittest = (INT) wParam;    // hit-test value
pts = MAKEPOINTS(lParam);   // position of cursor

Parameters

nHittest
Value of wParam. Specifies the hit-test value returned by the DefWindowProc function as a result of processing the WM_NCHITTEST message. For a list of hit-test values, see WM_NCHITTEST.
pts
Value of lParam. Specifies a POINTS structure that contains the x- and y-coordinates of the cursor. The coordinates are relative to the upper-left corner of the screen.

Return Values

If an application processes this message, it should return zero.

Remarks

A window need not have the CS_DBLCLKS style to receive WM_NCMBUTTONDBLCLK messages.

The system generates a WM_NCMBUTTONDBLCLK message when the user presses, releases, and again presses the middle mouse button within the system's double-click time limit. Double-clicking the middle mouse button actually generates four messages: WM_NCMBUTTONDOWN, WM_NCMBUTTONUP, WM_NCMBUTTONDBLCLK, and WM_NCMBUTTONUP again.

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

If it is appropriate to do so, the system sends the WM_SYSCOMMAND message to the window.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, MAKEPOINTS, POINTS, WM_NCHITTEST, WM_NCMBUTTONDOWN, WM_NCMBUTTONUP, WM_SYSCOMMAND


WM_NCMBUTTONDOWN

The WM_NCMBUTTONDOWN message is posted when the user presses the middle mouse button while the cursor is within the nonclient area of a window. This message is posted to the window that contains the cursor. If a window has captured the mouse, this message is not posted.

WM_NCMBUTTONDOWN
nHittest = (INT) wParam;    // hit-test value
pts = MAKEPOINTS(lParam);   // position of cursor

Parameters

nHittest
Value of wParam. Specifies the hit-test value returned by the DefWindowProc function as a result of processing the WM_NCHITTEST message. For a list of hit-test values, see WM_NCHITTEST.
pts
Value of lParam. Specifies a POINTS structure that contains the x- and y-coordinates of the cursor. The coordinates are relative to the upper-left corner of the screen.

Return Values

If an application processes this message, it should return zero.

Remarks

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

If it is appropriate to do so, the system sends the WM_SYSCOMMAND message to the window.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, MAKEPOINTS, POINTS, WM_NCHITTEST, WM_NCMBUTTONDBLCLK, WM_NCMBUTTONUP, WM_SYSCOMMAND


WM_NCMBUTTONUP

The WM_NCMBUTTONUP message is posted when the user releases the middle mouse button while the cursor is within the nonclient area of a window. This message is posted to the window that contains the cursor. If a window has captured the mouse, this message is not posted.

WM_NCMBUTTONUP
nHittest = (INT) wParam;    // hit-test value
pts = MAKEPOINTS(lParam);   // position of cursor

Parameters

nHittest
Value of wParam. Specifies the hit-test value returned by the DefWindowProc function as a result of processing the WM_NCHITTEST message. For a list of hit-test values, see WM_NCHITTEST.
pts
Value of lParam. Specifies a POINTS structure that contains the x- and y-coordinates of the cursor. The coordinates are relative to the upper-left corner of the screen.

Return Values

If an application processes this message, it should return zero.

Remarks

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

If it is appropriate to do so, the system sends the WM_SYSCOMMAND message to the window.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, MAKEPOINTS, POINTS, WM_NCHITTEST, WM_NCMBUTTONDBLCLK, WM_NCMBUTTONDOWN, WM_SYSCOMMAND


WM_NCMOUSEMOVE

The WM_NCMOUSEMOVE message is posted to a window when the cursor is moved within the nonclient area of the window. This message is posted to the window that contains the cursor. If a window has captured the mouse, this message is not posted.

WM_NCMOUSEMOVE
nHittest = (INT) wParam;    // hit-test value
pts = MAKEPOINTS(lParam);   // position of cursor

Parameters

nHittest
Value of wParam. Specifies the hit-test value returned by the DefWindowProc function as a result of processing the WM_NCHITTEST message. For a list of hit-test values, see WM_NCHITTEST.
pts
Value of lParam. Specifies a POINTS structure that contains the x- and y-coordinates of the cursor. The coordinates are relative to the upper-left corner of the screen.

Return Values

If an application processes this message, it should return zero.

Remarks

If it is appropriate to do so, the system sends the WM_SYSCOMMAND message to the window.

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, MAKEPOINTS, POINTS, WM_NCHITTEST, WM_SYSCOMMAND


WM_NCRBUTTONDBLCLK

The WM_NCRBUTTONDBLCLK message is posted when the user double-clicks the right mouse button while the cursor is within the nonclient area of a window. This message is posted to the window that contains the cursor. If a window has captured the mouse, this message is not posted.

WM_NCRBUTTONDBLCLK
nHittest = (INT) wParam;    // hit-test value
pts = MAKEPOINTS(lParam);   // position of cursor

Parameters

nHittest
Value of wParam. Specifies the hit-test value returned by the DefWindowProc function as a result of processing the WM_NCHITTEST message. For a list of hit-test values, see WM_NCHITTEST.
pts
Value of lParam. Specifies a POINTS structure that contains the x- and y-coordinates of the cursor. The coordinates are relative to the upper-left corner of the screen.

Return Values

If an application processes this message, it should return zero.

Remarks

A window need not have the CS_DBLCLKS style to receive WM_NCRBUTTONDBLCLK messages.

The system generates a WM_NCRBUTTONDBLCLK message when the user presses, releases, and again presses the right mouse button within the system's double-click time limit. Double-clicking the right mouse button actually generates four messages: WM_NCRBUTTONDOWN, WM_NCRBUTTONUP, WM_NCRBUTTONDBLCLK, and WM_NCRBUTTONUP again.

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

If it is appropriate to do so, the system sends the WM_SYSCOMMAND message to the window.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, MAKEPOINTS, POINTS, WM_NCHITTEST, WM_NCRBUTTONDOWN, WM_NCRBUTTONUP, WM_SYSCOMMAND


WM_NCRBUTTONDOWN

The WM_NCRBUTTONDOWN message is posted when the user presses the right mouse button while the cursor is within the nonclient area of a window. This message is posted to the window that contains the cursor. If a window has captured the mouse, this message is not posted.

WM_NCRBUTTONDOWN
nHittest = (INT) wParam;    // hit-test value
pts = MAKEPOINTS(lParam);   // position of cursor

Parameters

nHittest
Value of wParam. Specifies the hit-test value returned by the DefWindowProc function as a result of processing the WM_NCHITTEST message. For a list of hit-test values, see WM_NCHITTEST.
pts
Value of lParam. Specifies a POINTS structure that contains the x- and y-coordinates of the cursor. The coordinates are relative to the upper-left corner of the screen.

Return Values

If an application processes this message, it should return zero.

Remarks

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

If it is appropriate to do so, the system sends the WM_SYSCOMMAND message to the window.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, MAKEPOINTS, POINTS, WM_NCHITTEST, WM_NCRBUTTONDBLCLK, WM_NCRBUTTONUP, WM_SYSCOMMAND


WM_NCRBUTTONUP

The WM_NCRBUTTONUP message is posted when the user releases the right mouse button while the cursor is within the nonclient area of a window. This message is posted to the window that contains the cursor. If a window has captured the mouse, this message is not posted.

WM_NCRBUTTONUP
nHittest = (INT) wParam;    // hit-test value
pts = MAKEPOINTS(lParam);   // position of cursor

Parameters

nHittest
Value of wParam. Specifies the hit-test value returned by the DefWindowProc function as a result of processing the WM_NCHITTEST message. For a list of hit-test values, see WM_NCHITTEST.
pts
Value of lParam. Specifies a POINTS structure that contains the x- and y-coordinates of the cursor. The coordinates are relative to the upper-left corner of the screen.

Return Values

If an application processes this message, it should return zero.

Remarks

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

If it is appropriate to do so, the system sends the WM_SYSCOMMAND message to the window.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, MAKEPOINTS, POINTS, WM_NCHITTEST, WM_NCRBUTTONDBLCLK, WM_NCRBUTTONDOWN, WM_SYSCOMMAND


WM_RBUTTONDBLCLK

The WM_RBUTTONDBLCLK message is posted when the user double-clicks the right mouse button while the cursor is in the client area of a window. If the mouse is not captured, the message is posted to the window beneath the cursor. Otherwise, the message is posted to the window that has captured the mouse.

WM_RBUTTONDBLCLK
fwKeys = wParam;        // key flags
xPos = LOWORD(lParam);  // horizontal position of cursor
yPos = HIWORD(lParam);  // vertical position of cursor

Parameters

fwKeys
Value of wParam. Indicates whether various virtual keys are down. This parameter can be any combination of the following values:
Value | Description
MK_CONTROL | Set if the ctrl key is down.
MK_LBUTTON | Set if the left mouse button is down.
MK_MBUTTON | Set if the middle mouse button is down.
MK_RBUTTON | Set if the right mouse button is down.
MK_SHIFT | Set if the shift key is down.

xPos
Value of the low-order word of lParam. Specifies the x-coordinate of the cursor. The coordinate is relative to the upper left corner of the client area.
yPos
Value of the high-order word of lParam. Specifies the y-coordinate of the cursor. The coordinate is relative to the upper left corner of the client area.

Return Values

If an application processes this message, it should return zero.

Remarks

Only windows that have the CS_DBLCLKS style can receive WM_RBUTTONDBLCLK messages, which the system generates whenever the user presses, releases, and again presses the right mouse button within the system's double-click time limit. Double-clicking the right mouse button actually generates four messages: WM_RBUTTONDOWN, WM_RBUTTONUP, WM_RBUTTONDBLCLK, and WM_RBUTTONUP again.

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Mouse Input Overview, Mouse Input Messages, GetCapture, GetDoubleClickTime, MAKEPOINTS, POINTS, SetCapture, SetDoubleClickTime, WM_RBUTTONDOWN, WM_RBUTTONUP


WM_RBUTTONDOWN

The WM_RBUTTONDOWN message is posted when the user presses the right mouse button while the cursor is in the client area of a window. If the mouse is not captured, the message is posted to the window beneath the cursor. Otherwise, the message is posted to the window that has captured the mouse.

WM_RBUTTONDOWN
fwKeys = wParam;        // key flags
xPos = LOWORD(lParam);  // horizontal position of cursor
yPos = HIWORD(lParam);  // vertical position of cursor

Parameters

fwKeys
Value of wParam. Indicates whether various virtual keys are down. This parameter can be any combination of the following values:
Value | Description
MK_CONTROL | Set if the ctrl key is down.
MK_LBUTTON | Set if the left mouse button is down.
MK_MBUTTON | Set if the middle mouse button is down.
MK_RBUTTON | Set if the right mouse button is down.
MK_SHIFT | Set if the shift key is down.

xPos
Value of the low-order word of lParam. Specifies the x-coordinate of the cursor. The coordinate is relative to the upper left corner of the client area.
yPos
Value of the high-order word of lParam. Specifies the y-coordinate of the cursor. The coordinate is relative to the upper left corner of the client area.

Return Values

If an application processes this message, it should return zero.

Remarks

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Mouse Input Overview, Mouse Input Messages, GetCapture, MAKEPOINTS, POINTS, SetCapture, WM_RBUTTONDBLCLK, WM_RBUTTONUP


WM_RBUTTONUP

The WM_RBUTTONUP message is posted when the user releases the right mouse button while the cursor is in the client area of a window. If the mouse is not captured, the message is posted to the window beneath the cursor. Otherwise, the message is posted to the window that has captured the mouse.

WM_RBUTTONUP
fwKeys = wParam;        // key flags
xPos = LOWORD(lParam);  // horizontal position of cursor
yPos = HIWORD(lParam);  // vertical position of cursor

Parameters

fwKeys
Value of wParam. Indicates whether various virtual keys are down. This parameter can be any combination of the following values:
Value | Description
MK_CONTROL | Set if the ctrl key is down.
MK_LBUTTON | Set if the left mouse button is down.
MK_MBUTTON | Set if the middle mouse button is down.
MK_SHIFT | Set if the shift key is down.

xPos
Value of the low-order word of lParam. Specifies the x-coordinate of the cursor. The coordinate is relative to the upper left corner of the client area.
yPos
Value of the high-order word of lParam. Specifies the y-coordinate of the cursor. The coordinate is relative to the upper left corner of the client area.

Return Values

If an application processes this message, it should return zero.

Remarks

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Mouse Input Overview, Mouse Input Messages, GetCapture, MAKEPOINTS, POINTS, SetCapture, WM_RBUTTONDBLCLK, WM_RBUTTONDOWN


Keyboard Accelerators

A keyboard accelerator (or, simply, accelerator) is a keystroke or combination of keystrokes that generates a WM_COMMAND or WM_SYSCOMMAND message for an application.


About Keyboard Accelerators

Accelerators are closely related to menus — both provide the user with access to an application's command set. Typically, users rely on an application's menus to learn the command set and then switch over to using accelerators as they become more proficient with the application. Accelerators provide faster, more direct access to commands than menus do. At a minimum, an application should provide accelerators for the more commonly used commands. Although accelerators typically generate commands that exist as menu items, they can also generate commands that have no equivalent menu items.


Accelerator Tables

An accelerator table consists of an array of ACCEL structures, each defining an individual accelerator. Each ACCEL structure includes the following information:

  • The accelerator's keystroke combination.
  • The accelerator's identifier.
  • Various flags. This includes one that specifies whether the system is to provide visual feedback by highlighting the corresponding menu item, if any, when the accelerator is used

To process accelerator keystrokes for a given thread, the developer must call the TranslateAccelerator function in the message loop associated with the thread's message queue. The TranslateAccelerator function monitors keyboard input to the message queue, checking for key combinations that match an entry in the accelerator table. When TranslateAccelerator finds a match, it translates the keyboard input (that is, the WM_KEYUP and WM_KEYDOWN messages) into a WM_COMMAND or WM_SYSCOMMAND message and then sends the message to the window procedure of the specified window. The following illustration shows how accelerators are processed.

The WM_COMMAND message includes the identifier of the accelerator that caused TranslateAccelerator to generate the message. The window procedure examines the identifier to determine the source of the message and then processes the message accordingly.

Accelerator tables exist at two different levels. The system maintains a single, system-wide accelerator table that applies to all applications. An application cannot modify the system accelerator table. For a description of the accelerators provided by the system accelerator table, see Accelerator Keystroke Assignments.

The system also maintains accelerator tables for each application. An application can define any number of accelerator tables for use with its own windows. A unique 32-bit handle (HACCEL) identifies each table. However, only one accelerator table can be active at a time for a given thread. The handle to the accelerator table passed to the TranslateAccelerator function determines which accelerator table is active for a thread. The active accelerator table can be changed at any time by passing a different accelerator-table handle to TranslateAccelerator.


Accelerator-Table Creation

Several steps are required to create an accelerator table for an application. First, a resource compiler is used to create accelerator-table resources and to add them to the application's executable file. At run time, the LoadAccelerators function is used to load the accelerator table into memory and retrieve the handle to the accelerator table. This handle is passed to the TranslateAccelerator function to activate the accelerator table.

An accelerator table can also be created for an application at run time by passing an array of ACCEL structures to the CreateAcceleratorTable function. This method supports user-defined accelerators in the application. Like the LoadAccelerators function, CreateAcceleratorTable returns an accelerator-table handle that can be passed to TranslateAccelerator to activate the accelerator table.

The system automatically destroys accelerator tables loaded by LoadAccelerators. An accelerator table created by CreateAcceleratorTable must be destroyed before an application closes; otherwise, the table continues to exist in memory after the application has closed. An accelerator table is destroyed by calling the DestroyAcceleratorTable function.

An existing accelerator table can be copied and modified. The existing accelerator table is copied by using the CopyAcceleratorTable function. After the copy is modified, a handle to the new accelerator table is retrieved by calling CreateAcceleratorTable. Finally, the handle is passed to TranslateAccelerator to activate the new table.


Accelerator Keystroke Assignments

An ASCII character code or a virtual-key code can be used to define the accelerator. An ASCII character code makes the accelerator case sensitive. The ASCII "C" character can define the accelerator as alt+c rather than alt+c. Case-sensitive accelerators can, however, be confusing to use. For example, the alt+c accelerator will be generated if the caps lock key is down or if the shift key is down, but not if both are down.

Typically, accelerators don't need to be case sensitive, so most applications use virtual-key codes for accelerators rather than ASCII character codes.

Avoid accelerators that conflict with an application's menu mnemonics, because the accelerator overrides the mnemonic, which can confuse the user. For more information about menu mnemonics, see Menus.

If an application defines an accelerator that is also defined in the system accelerator table, the application-defined accelerator overrides the system accelerator, but only within the context of the application. Avoid this practice, however, because it prevents the system accelerator from performing its standard role in the user interface. The system-wide accelerators are described in the following list:

Accelerator | Description
alt+esc | Switches to the next application.
alt+f4 | Closes an application or a window.
alt+hyphen | Opens the window menu for a document window.
alt+print screen | Copies an image in the active window onto the clipboard.
alt+spacebar | Opens the window menu for the application's main window.
alt+tab | Switches to the next application.
ctrl+esc | Switches to the Start menu.
ctrl+f4 | Closes the active group or document window.
f1 | Starts the application's help file, if one exists.
print screen | Copies an image on the screen onto the clipboard.
shift+alt+tab | Switches to the previous application. The user must press and hold down alt+shift while pressing tab.


Accelerators and Menus

Using an accelerator is the same as choosing a menu item: Both actions cause the system to send a WM_COMMAND or WM_SYSCOMMAND message to the corresponding window procedure. The WM_COMMAND message includes an identifier that the window procedure examines to determine the source of the message. If an accelerator generated the WM_COMMAND message, the identifier is that of the accelerator. Similarly, if a menu item generated the WM_COMMAND message, the identifier is that of the menu item. Because an accelerator provides a shortcut for choosing a command from a menu, an application usually assigns the same identifier to the accelerator and the corresponding menu item.

An application processes an accelerator WM_COMMAND message in exactly the same way as the corresponding menu item WM_COMMAND message. However, the WM_COMMAND message contains a flag that specifies whether the message originated from an accelerator or a menu item, in case accelerators must be processed differently from their corresponding menu items. The WM_SYSCOMMAND message does not contain this flag.

The identifier determines whether an accelerator generates a WM_COMMAND or WM_SYSCOMMAND message. If the identifier has the same value as a menu item in the System menu, the accelerator generates a WM_SYSCOMMAND message. Otherwise, the accelerator generates a WM_COMMAND message.

If an accelerator has the same identifier as a menu item and the menu item is grayed or disabled, the accelerator is disabled and does not generate a WM_COMMAND or WM_SYSCOMMAND message. Also, an accelerator does not generate a command message if the corresponding window is minimized.

When the user uses an accelerator that corresponds to a menu item, the window procedure receives the WM_INITMENU and WM_INITMENUPOPUP messages as though the user had selected the menu item. For information about how to process these messages, see Menus.

An accelerator that corresponds to a menu item should be included in the text of the menu item.


Using Keyboard Accelerators

  • Using an accelerator-table resource
  • Using an accelerator table created at run time


Using an Accelerator-Table Resource

The most common way to add accelerator support to a Win32-based application is to include an accelerator-table resource with the application's executable file and then load the resource at run time. The steps involved in using an accelerator-table resource are as follows:

  • Create an accelerator table in a resource-definition file. Compile it and add the resulting resource to your application's executable file.
  • Include a call to the LoadAccelerators function to load the accelerator-table resource and receive a handle to the accelerator table.
  • Add the TranslateAccelerator function to the message loop associated with the accelerator table.
  • Process the WM_COMMAND messages generated when the user uses the accelerator.


Creating the Accelerator-Table Resource

You create an accelerator-table resource by using the ACCELERATORS statement in your application's resource-definition file. You must assign a name or resource identifier to the accelerator table, preferably unlike that of any other resource. The system uses this identifier to load the resource at run time.

Each accelerator you define requires a separate entry in the accelerator table. In each entry, you define the keystroke (either an ASCII character code or virtual-key code) that generates the accelerator and the accelerator's identifier. You must also specify whether the keystroke must be used in some combination with the alt, shift, or ctrl keys. For more information about virtual keys, see Keyboard Input.

An ASCII keystroke is specified either by enclosing the ASCII character in double quotation marks or by using the integer value of the character in combination with the ASCII flag. The following examples show how to define ASCII accelerators.

"A", ID_ACCEL1         ; SHIFT+A
65,  ID_ACCEL2, ASCII  ; SHIFT+A

A virtual-key code keystroke is specified differently depending on whether the keystroke is an alphanumeric key or a non-alphanumeric key. For an alphanumeric key, the key's letter or number, enclosed in double quotation marks, is combined with the VIRTKEY flag. For a non-alphanumeric key, the virtual-key code for the specific key is combined with the VIRTKEY flag. The following examples show how to define virtual-key code accelerators.

"a",       ID_ACCEL3, VIRTKEY   ; A (caps-lock on) or a
VK_INSERT, ID_ACCEL4, VIRTKEY   ; INSERT key

The following example shows an accelerator-table resource that defines accelerators for file operations. The name of the resource is FileAccel.

FileAccel ACCELERATORS
BEGIN
    VK_F12, IDM_OPEN, CONTROL, VIRTKEY  ; CTRL+F12
    VK_F4,  IDM_CLOSE, ALT, VIRTKEY     ; ALT+F4
    VK_F12, IDM_SAVE, SHIFT, VIRTKEY    ; SHIFT+F12
    VK_F12, IDM_SAVEAS, VIRTKEY         ; F12
END

If you want the user to press the alt, shift, or ctrl keys in some combination with the accelerator keystroke, specify the ALT, SHIFT, and CONTROL flags in the accelerator's definition. Following are some examples.

"B",   ID_ACCEL5, ALT                   ; ALT_SHIFT+B
"I",   ID_ACCEL6, CONTROL, VIRTKEY      ; CTRL+I
VK_F5, ID_ACCEL7, CONTROL, ALT, VIRTKEY ; CTRL+ALT+F5

By default, when an accelerator key corresponds to a menu item, the system highlights the menu item. You can use the NOINVERT flag to prevent highlighting for an individual accelerator. The following example shows how to use the NOINVERT flag.

VK_DELETE, ID_ACCEL8, VIRTKEY, SHIFT, NOINVERT  ; SHIFT+DELETE

To define accelerators that correspond to menu items in your application, include the accelerators in the text of the menu items. The following example shows how to include accelerators in menu-item text in a resource-definition file.

FilePopup MENU
BEGIN
    POPUP   "&File"
    BEGIN
        MENUITEM    "&New..",           IDM_NEW
        MENUITEM    "&Open\tCtrl+F12",  IDM_OPEN
        MENUITEM    "&Close\tAlt+F4"    IDM_CLOSE
        MENUITEM    "&Save\tShift+F12", IDM_SAVE
        MENUITEM    "Save &As...\tF12", IDM_SAVEAS
    END
END


Loading the Accelerator-Table Resource

An application loads an accelerator-table resource by calling the LoadAccelerators function and specifying the instance handle to the application whose executable file contains the resource and the name or identifier of the resource. LoadAccelerators loads the specified accelerator table into memory and returns the handle to the accelerator table.

An application can load an accelerator-table resource at any time. Usually, a single-threaded application loads its accelerator table before entering its main message loop. An application that uses multiple threads typically loads the accelerator-table resource for a thread before entering the message loop for the thread. An application or thread might also use multiple accelerator tables, each associated with a particular window in the application. Such an application would load the accelerator table for the window each time the user activated the window. For more information about threads, see Processes and Threads.


Calling the TranslateAccelerator Function

To process accelerators, an application's (or thread's) message loop must contain a call to the TranslateAccelerator function. TranslateAccelerator compares keystrokes to an accelerator table and, if it finds a match, translates the keystrokes into a WM_COMMAND (or WM_SYSCOMMAND) message. The function then sends the message to a window procedure. The parameters of the TranslateAccelerator function include the handle to the window that is to receive the WM_COMMAND messages, the handle to the accelerator table used to translate accelerators, and a pointer to an MSG structure containing a message from the queue. The following example shows how to call TranslateAccelerator from within a message loop.

while (GetMessage(&msg, (HWND) NULL, 0, 0))
{
    // Check for accelerator keystrokes.

    if (!TranslateAccelerator(
            hwndMain,      // handle to receiving window
            haccel,        // handle to active accelerator table
            &msg))         // address of message data
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}


Processing WM_COMMAND Messages

When an accelerator is used, the window specified in the TranslateAccelerator function receives a WM_COMMAND or WM_SYSCOMMAND message. The low-order word of the wParam parameter contains the identifier of the accelerator. The window procedure examines the identifier to determine the source of the WM_COMMAND message and process the message accordingly.

Typically, if an accelerator corresponds to a menu item in the application, the accelerator and menu item are assigned the same identifier. If you need to know whether a given WM_COMMAND message was generated by an accelerator or by a menu item, you can examine the high-order word of the wParam parameter. If an accelerator generated the message, the high-order word is 1; if a menu item generated the message, the high-order word is 0.


Destroying the Accelerator-Table Resource

The system automatically destroys accelerator-table resources loaded by the LoadAccelerators function, removing the resource from memory after the application closes.


Creating Accelerators for Font Attributes

The example in this section shows how to perform the following tasks:

  • Create an accelerator-table resource.
  • Load the accelerator table at run time.
  • Translate accelerators in a message loop.
  • Process WM_COMMAND messages generated by the accelerators.

These tasks are demonstrated in the context of an application that includes a Character menu and corresponding accelerators that allow the user to select attributes of the current font.

The following portion of a resource-definition file defines the Character menu and the associated accelerator table. Note that the menu items show the accelerator keystrokes and that each accelerator has the same identifier as its associated menu item.

#include <windows.h>
#include "acc.h"

MainMenu MENU
{
    POPUP   "&Character"
    {
        MENUITEM    "&Regular\tF5",         IDM_REGULAR
        MENUITEM    "&Bold\tCtrl+B",        IDM_BOLD
        MENUITEM    "&Italic\tCtrl+I",      IDM_ITALIC
        MENUITEM    "&Underline\tCtrl+U",   IDM_ULINE
    }
}

FontAccel ACCELERATORS
{
    VK_F5,  IDM_REGULAR,    VIRTKEY
    "B",    IDM_BOLD,       CONTROL, VIRTKEY
    "I",    IDM_ITALIC,     CONTROL, VIRTKEY
    "U",    IDM_ULINE,      CONTROL, VIRTKEY
}

The following sections from the application's source file show how to implement the accelerators.

HWND hwndMain;      // handle to main window
HANDLE hinstAcc;    // handle to application instance

int WINAPI WinMain(HINSTANCE hinst, HINSTANCE hinstPrev, LPSTR lpCmdLine, int nCmdShow)
{
    MSG msg;            // application messages
    HACCEL haccel;      // handle to accelerator table

    // Perform the initialization procedure.

    // Create a main window for this application instance.

    hwndMain = CreateWindowEx(0L, "MainWindowClass",
        "Sample Application", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
        CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL,
        hinst, NULL );

    // If a window cannot be created, return "failure."

    if (!hwndMain)
        return FALSE;

    // Make the window visible and update its client area.

    ShowWindow(hwndMain, nCmdShow);
    UpdateWindow(hwndMain);

    // Load the accelerator table.

    haccel = LoadAccelerators(hinstAcc, "FontAccel");
    if (haccel == NULL)
        HandleAccelErr(ERR_LOADING);     // application defined

    // Get and dispatch messages until a WM_QUIT message is
    // received.

    while (GetMessage(&msg, NULL, NULL, NULL))
    {
        // Check for accelerator keystrokes.

        if (!TranslateAccelerator(
                hwndMain,      // handle to receiving window
                haccel,        // handle to active accelerator table
                &msg))         // address of message data
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }
    return msg.wParam;
}

LRESULT APIENTRY MainWndProc(HWND hwndMain, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    BYTE fbFontAttrib;        // array of font-attribute flags
    static HMENU hmenu;       // handle to main menu

    switch (uMsg)
    {
        case WM_CREATE:

            // Add a check mark to the Regular menu item to
            // indicate that it is the default.

            hmenu = GetMenu(hwndMain);
            CheckMenuItem(hmenu, IDM_REGULAR, MF_BYCOMMAND |
                MF_CHECKED);
            return 0;

        case WM_COMMAND:
            switch (LOWORD(wParam))
            {
                // Process the accelerator and menu commands.

                case IDM_REGULAR:
                case IDM_BOLD:
                case IDM_ITALIC:
                case IDM_ULINE:

                    // GetFontAttributes is an application-defined
                    // function that sets the menu-item check marks
                    // and returns the user-selected font attributes.

                    fbFontAttrib = GetFontAttributes(
                        (BYTE) LOWORD(wParam), hmenu);

                    // SetFontAttributes is an application-defined
                    // function that creates a font with the
                    // user-specified attributes the font with
                    // the main window's device context.

                    SetFontAttributes(fbFontAttrib);
                    break;

                default:
                    break;
            }
            break;

            // Process other messages.

        default:
            return DefWindowProc(hwndMain, uMsg, wParam, lParam);
    }
    return NULL;
}


Using an Accelerator Table Created at Run Time

The Win32 API allows you to create accelerator tables at run time. The steps involved in creating and using an accelerator table at run time are as follows:

  • Define the accelerators by filling an array of ACCEL structures, and then create an accelerator table by passing the array to the CreateAcceleratorTable function.
  • Activate the accelerator table and process WM_COMMAND messages generated by the accelerators.
  • Destroy the accelerator table before the application closes.


Creating the Accelerator Table

The first step in creating an accelerator table at run time is filling an array of ACCEL structures. Each structure in the array defines an accelerator in the table. An accelerator's definition includes its flags, its key, and its identifier. The ACCEL structure has the following form.

typedef struct tagACCEL { // accl
    BYTE   fVirt;
    WORD   key;
    WORD   cmd;
} ACCEL;

You define an accelerator's keystroke by specifying an ASCII character code or a virtual-key code in the key member of the ACCEL structure. If you specify a virtual-key code, you must first include the FVIRTKEY flag in the fVirt member; otherwise, the system interprets the code as an ASCII character code. You can include the FCONTROL, FALT, or FSHIFT flag, or all three, to combine the ctrl, alt, or shift key with the keystroke.

To create the accelerator table, pass the address of the array of ACCEL structures to the CreateAcceleratorTable function. CreateAcceleratorTable creates the accelerator table and returns the handle to the table.


Processing Accelerators

The process of loading and calling accelerators provided by an accelerator table created at run time is the same as processing those provided by an accelerator-table resource. For more information, see Loading the Accelerator-Table Resource through Processing WM_COMMAND Messages.


Destroying the Accelerator Table

Before an application closes, it must destroy accelerator tables created at run time. You can destroy an accelerator table and remove it from memory by passing the table's handle to the DestroyAcceleratorTable function.


Creating User-Editable Accelerators

This example shows how to construct a dialog box that allows the user to change the accelerator associated with a menu item. The dialog box consists of a combo box containing menu items, a combo box containing the names of keys, and check boxes for selecting the ctrl, alt, and shift keys. The following illustration shows the dialog box.

The following example shows how the dialog box is defined in the resource-definition file.

EdAccelBox DIALOG 5, 17, 193, 114
STYLE DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION
CAPTION "Edit Accelerators"
BEGIN
    COMBOBOX        IDD_MENUITEMS, 10, 22, 52, 53,
                        CBS_SIMPLE | CBS_SORT | WS_VSCROLL |
                        WS_TABSTOP
    CONTROL         "Control", IDD_CNTRL, "Button",
                        BS_AUTOCHECKBOX | WS_TABSTOP,
                        76, 35, 40, 10
    CONTROL         "Alt", IDD_ALT, "Button",
                        BS_AUTOCHECKBOX | WS_TABSTOP,
                        76, 48, 40, 10
    CONTROL         "Shift", IDD_SHIFT, "Button",
                        BS_AUTOCHECKBOX | WS_TABSTOP,
                        76, 61, 40, 10
    COMBOBOX        IDD_KEYSTROKES, 124, 22, 58, 58,
                        CBS_SIMPLE | CBS_SORT | WS_VSCROLL |
                        WS_TABSTOP
    PUSHBUTTON      "Ok", IDOK, 43, 92, 40, 14
    PUSHBUTTON      "Cancel", IDCANCEL, 103, 92, 40, 14
    LTEXT           "Select Item:", 101, 10, 12, 43, 8
    LTEXT           "Select Keystroke:", 102, 123, 12, 60, 8
END

The application's menu bar contains a Character submenu whose items have accelerators associated with them.

MainMenu MENU
{
    POPUP "&Character"
    {
        MENUITEM    "&Regular\tF5",         IDM_REGULAR
        MENUITEM    "&Bold\tCtrl+B",        IDM_BOLD
        MENUITEM    "&Italic\tCtrl+I",      IDM_ITALIC
        MENUITEM    "&Underline\tCtrl+U",   IDM_ULINE
    }
}

FontAccel ACCELERATORS
{
    VK_F5,  IDM_REGULAR,    VIRTKEY
    "B",    IDM_BOLD,       CONTROL, VIRTKEY
    "I",    IDM_ITALIC,     CONTROL, VIRTKEY
    "U",    IDM_ULINE,      CONTROL, VIRTKEY
}

The menu item values for the menu template are constants defined as follows in the application's header file.

#define IDM_REGULAR    1100
#define IDM_BOLD       1200
#define IDM_ITALIC     1300
#define IDM_ULINE      1400

The dialog box uses an array of application-defined VKEY structures, each containing a keystroke-text string and an accelerator-text string. When the dialog box is created, it parses the array and adds each keystroke-text string to the Select Keystroke combo box. When the user clicks the OK button, the dialog box looks up the selected keystroke-text string and retrieves the corresponding accelerator-text string. The dialog box appends the accelerator-text string to the text of the menu item that the user selected. The following example shows the array of VKEY structures:

// VKey Lookup Support

#define MAXKEYS 25

typedef struct _VKEYS {
    char *pKeyName;
    char *pKeyString;
} VKEYS;

VKEYS vkeys[MAXKEYS] = {
    "BkSp",     "Back Space",
    "PgUp",     "Page Up",
    "PgDn",     "Page Down",
    "End",      "End",
    "Home",     "Home",
    "Lft",      "Left",
    "Up",       "Up",
    "Rgt",      "Right",
    "Dn",       "Down",
    "Ins",      "Insert",
    "Del",      "Delete",
    "Mult",     "Multiply",
    "Add",      "Add",
    "Sub",      "Subtract",
    "DecPt",    "Decimal Point",
    "Div",      "Divide",
    "F2",       "F2",
    "F3",       "F3",
    "F5",       "F5",
    "F6",       "F6",
    "F7",       "F7",
    "F8",       "F8",
    "F9",       "F9",
    "F11",      "F11",
    "F12",      "F12"
};

The dialog box's initialization procedure fills the Select Item and Select Keystroke combo boxes. After the user selects a menu item and associated accelerator, the dialog box examines the controls in the dialog box to get the user's selection, updates the text of the menu item, and then creates a new accelerator table that contains the user-defined new accelerator. The following example shows the dialog-box procedure. Note that you must initialize hwndMain in your window procedure.

// Global variables

HWND hwndMain;      // handle to main window
HACCEL haccel;      // handle to accelerator table

// Dialog-box procedure

BOOL CALLBACK EdAccelProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    int nCurSel;            // index of list box item
    UINT idItem;            // menu-item identifier
    UINT uItemPos;          // menu-item position
    UINT i, j = 0;          // loop counters
    static UINT cItems;     // count of items in menu
    char szTemp[32];        // temporary buffer
    char szAccelText[32];   // buffer for accelerator text
    char szKeyStroke[16];   // buffer for keystroke text
    static char szItem[32]; // buffer for menu-item text
    HWND hwndCtl;           // handle to control window
    static HMENU hmenu;     // handle to "Character" menu
    PCHAR pch, pch2;        // pointers for string copying
    WORD wVKCode;           // accelerator virtual-key code
    BYTE fAccelFlags;       // fVirt flags for ACCEL structure
    LPACCEL lpaccelNew;     // address of new accelerator table
    HACCEL haccelOld;       // handle to old accelerator table
    int cAccelerators;      // number of accelerators in table
    static BOOL fItemSelected = FALSE; // item selection flag
    static BOOL fKeySelected = FALSE;  // key selection flag

    switch (uMsg)
    {
        case WM_INITDIALOG:

            // Get the handle to the menu-item combo box.

            hwndCtl = GetDlgItem(hwndDlg, IDD_MENUITEMS);

            // Get the handle to the Character submenu and
            // count the number of items it has. In this example,
            // the menu has position 0. You must alter this value
            // if you add additional menus.
            hmenu = GetSubMenu(GetMenu(hwndMain), 0);
            cItems = GetMenuItemCount(hmenu);

            // Get the text of each item, strip out the '&' and
            // the accelerator text, and add the text to the
            // menu-item combo box.

            for (i = 0; i < cItems; i++)
            {
                if (!(GetMenuString(hmenu, i, szTemp,
                        sizeof(szTemp), MF_BYPOSITION)))
                    continue;
                for (pch = szTemp, pch2 = szItem; *pch != '\0'; )
                {
                    if (*pch != '&')
                    {
                        if (*pch == '\t')
                        {
                            *pch = '\0';
                            *pch2 = '\0';
                        }
                        else *pch2++ = *pch++;
                    }
                    else pch++;
                }
                SendMessage(hwndCtl, CB_ADDSTRING, 0,
                    (LONG) (LPSTR) szItem);
            }

            // Now fill the keystroke combo box with the list of
            // keystrokes that will be allowed for accelerators.
            // The list of keystrokes is in the application-defined
            // structure called "vkeys".

            hwndCtl = GetDlgItem(hwndDlg, IDD_KEYSTROKES);
            for (i = 0; i < MAXKEYS; i++)
            {
                SendMessage(hwndCtl, CB_ADDSTRING, 0,
                    (LONG) (LPSTR) vkeys[i].pKeyString);
            }

            return TRUE;

        case WM_COMMAND:
            switch (LOWORD(wParam))
            {
                case IDD_MENUITEMS:

                    // The user must select an item from the combo
                    // box. This flag is checked during IDOK
                    // processing to be sure a selection was made.

                    fItemSelected = TRUE;
                    return 0;

                case IDD_KEYSTROKES:

                    // The user must select an item from the combo
                    // box. This flag is checked during IDOK
                    // processing to be sure a selection was made.

                    fKeySelected = TRUE;

                    return 0;

                case IDOK:

                    // If the user has not selected a menu item
                    // and a keystroke, display a reminder in a
                    // message box.

                    if (!fItemSelected || !fKeySelected)
                    {
                        MessageBox(hwndDlg,
                            "Item or key not selected.", NULL,
                            MB_OK);
                        return 0;
                    }

                    // Determine whether the CTRL, ALT, and SHIFT
                    // keys are selected. Concatenate the
                    // appropriate strings to the accelerator-
                    // text buffer, and set the appropriate
                    // accelerator flags.

                    szAccelText[0] = '\0';
                    hwndCtl = GetDlgItem(hwndDlg, IDD_CNTRL);
                    if (SendMessage(hwndCtl, BM_GETCHECK, 0, 0) == 1)
                    {
                        lstrcat(szAccelText, "Ctl+");
                        fAccelFlags |= FCONTROL;
                    }
                    hwndCtl = GetDlgItem(hwndDlg, IDD_ALT);
                    if (SendMessage(hwndCtl, BM_GETCHECK, 0, 0) == 1)
                    {
                        lstrcat(szAccelText, "Alt+");
                        fAccelFlags |= FALT;
                    }
                    hwndCtl = GetDlgItem(hwndDlg, IDD_SHIFT);
                    if (SendMessage(hwndCtl, BM_GETCHECK, 0, 0) == 1)
                    {
                        lstrcat(szAccelText, "Shft+");
                        fAccelFlags |= FSHIFT;
                    }

                    // Get the selected keystroke, and look up the
                    // accelerator text and the virtual-key code
                    // for the keystroke in the vkeys structure.

                    hwndCtl = GetDlgItem(hwndDlg, IDD_KEYSTROKES);
                    nCurSel = (int) SendMessage(hwndCtl,
                        CB_GETCURSEL, 0, 0);
                    SendMessage(hwndCtl, CB_GETLBTEXT,
                        nCurSel, (LONG) (LPSTR) szKeyStroke);
                    for (i = 0; i < MAXKEYS; i++)
                    {
                        if(lstrcmp(vkeys[i].pKeyString, szKeyStroke)
                            == 0)
                        {
                            lstrcpy(szKeyStroke, vkeys[i].pKeyName);
                            break;
                        }
                    }

                    // Concatenate the keystroke text to the
                    // "Ctl+","Alt+", or "Shft+" string.

                    lstrcat(szAccelText, szKeyStroke);

                    // Determine the position in the menu of the
                    // selected menu item. Menu items in the
                    // "Character" menu have positions 0,2,3, and 4.

                    if (lstrcmp(szItem, "Regular") == 0)
                        uItemPos = 0;
                    else if (lstrcmp(szItem, "Bold") == 0)
                        uItemPos = 2;
                    else if (lstrcmp(szItem, "Italic") == 0)
                        uItemPos = 3;
                    else if (lstrcmp(szItem, "Underline") == 0)
                        uItemPos = 4;

                    // Get the string that corresponds to the
                    // selected item.

                    GetMenuString(hmenu, uItemPos, szItem,
                        sizeof(szItem), MF_BYPOSITION);

                    // Append the new accelerator text to the
                    // menu-item text.

                    for (pch = szItem; *pch != '\t'; pch++);
                        ++pch;

                    for (pch2 = szAccelText; *pch2 != '\0'; pch2++)
                        *pch++ = *pch2;
                    *pch = '\0';

                    // Modify the menu item to reflect the new
                    // accelerator text.

                    idItem = GetMenuItemID(hmenu, uItemPos);
                    ModifyMenu(hmenu, idItem, MF_BYCOMMAND |
                        MF_STRING, idItem, szItem);

                    // Reset the selection flags.

                    fItemSelected = FALSE;
                    fKeySelected = FALSE;

                    // Save the current accelerator table.

                    haccelOld = haccel;

                    // Count the number of entries in the current
                    // table, allocate a buffer for the table, and
                    // then copy the table into the buffer.

                    cAccelerators = CopyAcceleratorTable(
                        haccelOld, NULL, 0);
                    lpaccelNew = (LPACCEL) LocalAlloc(LPTR,
                        cAccelerators * sizeof(ACCEL));

                    if (lpaccelNew != NULL)
                    {
                        CopyAcceleratorTable(haccel, lpaccelNew,
                            cAccelerators);
                    }

                    // Find the accelerator that the user modified
                    // and change its flags and virtual-key code
                    // as appropriate.

                    for (i = 0; (lpaccelNew[i].cmd ==
                                (WORD) idItem)
                            && (i < (UINT) cAccelerators); i++)
                    {
                        lpaccelNew[i].fVirt = fAccelFlags;
                        lpaccelNew[i].key = wVKCode;
                    }

                    // Create the new accelerator table, and
                    // destroy the old one.

                    DestroyAcceleratorTable(haccelOld);
                    haccel = CreateAcceleratorTable(lpaccelNew,
                        cAccelerators);

                    // Destroy the dialog box.

                    EndDialog(hwndDlg, TRUE);
                    return 0;

                case IDCANCEL:
                    EndDialog(hwndDlg, TRUE);
                    return TRUE;

                default:
                    break;
            }
        default:
            break;
    }
    return FALSE;
}


Keyboard Accelerator Reference

The following elements are associated with keyboard accelerators.

  • Keyboard Accelerator Functions
  • Keyboard Accelerator Structures
  • Keyboard Accelerator Messages


Keyboard Accelerator Functions

The following functions are used with accelerators.

CopyAcceleratorTable
CreateAcceleratorTable
DestroyAcceleratorTable
LoadAccelerators
TranslateAccelerator


CopyAcceleratorTable

The CopyAcceleratorTable function copies the specified accelerator table. This function is used to obtain the accelerator-table data that corresponds to an accelerator-table handle, or to determine the size of the accelerator-table data.

int CopyAcceleratorTable(
  HACCEL hAccelSrc,   // handle to accelerator table to copy
  LPACCEL lpAccelDst, // pointer to structure receiving copy
  int cAccelEntries   // number of entries in table being copied
);

Parameters

hAccelSrc
Handle to the accelerator table to copy.
lpAccelDst
Pointer to an array of ACCEL structures where the accelerator-table information is to be copied.
cAccelEntries
Specifies the number of ACCEL structures to copy to the buffer pointed to by the lpAccelDst parameter.

Return Values

If lpAccelDst is NULL, the return value specifies the number of accelerator-table entries in the original table. Otherwise, it specifies the number of accelerator-table entries that were copied.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Keyboard Accelerators Overview, Keyboard Accelerator Functions, ACCEL, CreateAcceleratorTable, DestroyAcceleratorTable, LoadAccelerators, TranslateAccelerator


CreateAcceleratorTable

The CreateAcceleratorTable function creates an accelerator table.

HACCEL CreateAcceleratorTable(
  LPACCEL lpaccl,  // pointer to structure array with accelerator data
  int cEntries     // number of structures in the array
);

Parameters

lpaccl
Pointer to an array of ACCEL structures that describes the accelerator table.
cEntries
Specifies the number of ACCEL structures in the array.

Return Values

If the function succeeds, the return value is the handle to the created accelerator table; otherwise, it is NULL. To get extended error information, call GetLastError.

Remarks

Before an application closes, it must use the DestroyAcceleratorTable function to destroy each accelerator table that it created by using the CreateAcceleratorTable function.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Keyboard Accelerators Overview, Keyboard Accelerator Functions, ACCEL, CopyAcceleratorTable, DestroyAcceleratorTable, LoadAccelerators, TranslateAccelerator


DestroyAcceleratorTable

The DestroyAcceleratorTable function destroys an accelerator table. Before an application closes, it must use this function to destroy each accelerator table that it created by using the CreateAcceleratorTable function.

BOOL DestroyAcceleratorTable(
  HACCEL hAccel   // handle to accelerator table
);

Parameters

hAccel
Handle to the accelerator table to destroy. This handle must have been created by a call to the CreateAcceleratorTable function.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Keyboard Accelerators Overview, Keyboard Accelerator Functions, CopyAcceleratorTable, CreateAcceleratorTable, LoadAccelerators, TranslateAccelerator


LoadAccelerators

The LoadAccelerators function loads the specified accelerator table.

HACCEL LoadAccelerators(
  HINSTANCE hInstance,  // handle to application instance
  LPCTSTR lpTableName   // address of table-name string
);

Parameters

hInstance
Handle to an instance of the module whose executable file contains the accelerator table to load.
lpTableName
Pointer to a null-terminated string that names the accelerator table to load. Alternatively, this parameter can specify the resource identifier of an accelerator-table resource in the low-order word and zero in the high-order word. The MAKEINTRESOURCE macro can be used to create this value.

Return Values

If the function succeeds, the return value is the handle to the loaded accelerator table.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

If the accelerator table has not yet been loaded, the function loads it from the specified executable file.

Accelerator tables loaded from resources are freed automatically when the application terminates.

Windows CE: The resource is not copied into RAM, so it may not be modified.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Keyboard Accelerators Overview, Keyboard Accelerator Functions, CopyAcceleratorTable, CreateAcceleratorTable, DestroyAcceleratorTable, MAKEINTRESOURCE


TranslateAccelerator

The TranslateAccelerator function processes accelerator keys for menu commands. The function translates a WM_KEYDOWN or WM_SYSKEYDOWN message to a WM_COMMAND or WM_SYSCOMMAND message (if there is an entry for the key in the specified accelerator table) and then sends the WM_COMMAND or WM_SYSCOMMAND message directly to the appropriate window procedure. TranslateAccelerator does not return until the window procedure has processed the message.

int TranslateAccelerator(
  HWND hWnd,         // handle to destination window
  HACCEL hAccTable,  // handle to accelerator table
  LPMSG lpMsg        // address of structure with message
);

Parameters

hWnd
Handle to the window whose messages are to be translated.
hAccTable
Handle to an accelerator table. The accelerator table must have been loaded by a call to the LoadAccelerators function or created by a call to the CreateAcceleratorTable function.
lpMsg
Pointer to an MSG structure that contains message information retrieved from the calling thread's message queue by using the GetMessage or PeekMessage function.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

To differentiate the message that this function sends from messages sent by menus or controls, the high-order word of the wParam parameter of the WM_COMMAND or WM_SYSCOMMAND message contains the value 1.

Accelerator key combinations used to select items from the window menu are translated into WM_SYSCOMMAND messages; all other accelerator key combinations are translated into WM_COMMAND messages.

When TranslateAccelerator returns a nonzero value and the message is translated, the application should not use the TranslateMessage function to process the message again.

An accelerator need not correspond to a menu command.

If the accelerator command corresponds to a menu item, the application is sent WM_INITMENU and WM_INITMENUPOPUP messages, as if the user were trying to display the menu. However, these messages are not sent if any of the following conditions exist:

  • The window is disabled.
  • The menu item is disabled.
  • The accelerator key combination does not correspond to an item on the window menu and the window is minimized.
  • A mouse capture is in effect. For information about mouse capture, see the SetCapture function.

If the specified window is the active window and no window has the keyboard focus (which is generally the case if the window is minimized), TranslateAccelerator translates WM_SYSKEYUP and WM_SYSKEYDOWN messages instead of WM_KEYUP and WM_KEYDOWN messages.

If an accelerator keystroke occurs that corresponds to a menu item when the window that owns the menu is minimized, TranslateAccelerator does not send a WM_COMMAND message. However, if an accelerator keystroke occurs that does not match any of the items in the window's menu or in the window menu, the function sends a WM_COMMAND message, even if the window is minimized.

Windows CE: All accelerator key messages are translated into WM_COMMAND messages; Windows CE does not support the WM_SYSCOMMAND message.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Keyboard Accelerators Overview, Keyboard Accelerator Functions, CreateAcceleratorTable, GetMessage, LoadAccelerators, MSG, PeekMessage, SetCapture, TranslateMessage, WM_COMMAND, WM_INITMENU, WM_INITMENUPOPUP, WM_KEYDOWN, WM_SYSKEYDOWN, WM_SYSCOMMAND


Keyboard Accelerator Structures

The following structure is used with accelerators.

ACCEL


ACCEL

The ACCEL structure defines an accelerator key used in an accelerator table.

typedef struct tagACCEL { // accl
    BYTE   fVirt;
    WORD   key;
    WORD   cmd;
} ACCEL;

Members

fVirt
Specifies the accelerator flags. This member can be a combination of the following values:
Value | Meaning
FALT | The alt key must be held down when the accelerator key is pressed.
FCONTROL | The ctrl key must be held down when the accelerator key is pressed.
FNOINVERT | Specifies that no top-level menu item is highlighted when the accelerator is used. If this flag is not specified, a top-level menu item will be highlighted, if possible, when the accelerator is used.
FSHIFT | The shift key must be held down when the accelerator key is pressed.
FVIRTKEY | The key member specifies a virtual-key code. If this flag is not specified, key is assumed to specify an ASCII character code.

key
Specifies the accelerator key. This member can be either a virtual-key code or an ASCII character code.
cmd
Specifies the accelerator identifier. This value is placed in the low-order word of the wParam parameter of the WM_COMMAND or WM_SYSCOMMAND message when the accelerator is pressed.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Keyboard Accelerators Overview, Keyboard Accelerator Structures, WM_COMMAND, WM_SYSCOMMAND


Keyboard Accelerator Messages

The following messages are used with accelerators.

WM_COMMAND
WM_INITMENU
WM_INITMENUPOPUP
WM_MENUCHAR
WM_MENUSELECT
WM_SYSCHAR
WM_SYSCOMMAND


WM_INITMENU

The WM_INITMENU message is sent when a menu is about to become active. It occurs when the user clicks an item on the menu bar or presses a menu key. This allows the application to modify the menu before it is displayed.

WM_INITMENU
hmenuInit = (HMENU) wParam; // handle to menu to initialize

Parameters

hmenuInit
Value of wParam. Handle to the menu to be initialized.

Return Values

If an application processes this message, it should return zero.

Remarks

A WM_INITMENU message is sent only when a menu is first accessed; only one WM_INITMENU message is generated for each access. For example, moving the mouse across several menu items while holding down the button does not generate new messages. WM_INITMENU does not provide information about menu items.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Keyboard Accelerators Overview, Keyboard Accelerator Messages, WM_INITMENUPOPUP


WM_INITMENUPOPUP

The WM_INITMENUPOPUP message is sent when a drop-down menu or submenu is about to become active. This allows an application to modify the menu before it is displayed, without changing the entire menu.

WM_INITMENUPOPUP
hmenuPopup = (HMENU) wParam;         // handle to submenu
uPos = (UINT) LOWORD(lParam);        // submenu item position
fSystemMenu = (BOOL) HIWORD(lParam); // window menu flag

Parameters

hmenuPopup
Value of wParam. Handle to the drop-down menu or submenu.
uPos
Value of the low-order word of lParam. Specifies the zero-based relative position of the menu item that opens the drop-down menu or submenu.
fSystemMenu
Value of the high-order word of lParam. Specifies whether the drop-down menu is the window menu (also known as the System menu or the Control menu). If the menu is the window menu, this parameter is TRUE; otherwise, it is FALSE.

Return Values

If an application processes this message, it should return zero.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Keyboard Accelerators Overview, Keyboard Accelerator Messages, WM_INITMENU


WM_MENUCHAR

The WM_MENUCHAR message is sent when a menu is active and the user presses a key that does not correspond to any mnemonic or accelerator key. This message is sent to the window that owns the menu.

WM_MENUCHAR
chUser = (TCHAR) LOWORD(wParam); // character code
fuFlag = (UINT) HIWORD(wParam);  // menu flag
hmenu = (HMENU) lParam;          // handle to menu

Parameters

chUser
Value of the low-order word of wParam. Specifies the character code that corresponds to the key the user pressed.
fuFlag
Value of the high-order word of wParam. Specifies the type of the active menu. This parameter can be one of the following values:
Value | Meaning
MF_POPUP | drop-down menu, submenu, or shortcut menu
MF_SYSMENU | window menu (System menu or Control menu)

hmenu
Value of lParam. Handle to the active menu.

Return Values

An application that processes this message should return one of the following values in the high-order word of the return value:

Value | Meaning
MNC_IGNORE | Informs the system that it should discard the character the user pressed and create a short beep on the system speaker.
MNC_CLOSE | Informs the system that it should close the active menu.
MNC_EXECUTE | Informs the system that it should choose the item specified in the low-order word of the return value. The owner window receives a WM_COMMAND message.
MNC_SELECT | Informs the system that it should select the item specified in the low-order word of the return value.

Remarks

The low-order word is ignored if the high-order word contains 0 or 1. An application should process this message when an accelerator is used to select a menu item that displays a bitmap.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Keyboard Accelerators Overview, Keyboard Accelerator Messages


WM_MENUSELECT

The WM_MENUSELECT message is sent to a menu's owner window when the user selects a menu item.

WM_MENUSELECT
uItem = (UINT) LOWORD(wParam);   // menu item or submenu index
fuFlags = (UINT) HIWORD(wParam); // menu flags
hmenu = (HMENU) lParam;          // handle to menu clicked

Parameters

uItem
Value of the low-order word of wParam. If the selected item is a command item, this parameter contains the identifier of the menu item. If the selected item opens a drop-down menu or submenu, this parameter contains the menu index of the drop-down menu or submenu in the main menu, and the hMenu parameter then contains the handle to the main (clicked) menu; use the GetSubMenu function to get the menu handle to the drop-down menu or submenu.
fuFlags
Value of the high-order word of wParam. Specifies one or more menu flags. This parameter can be a combination of the following values:
Value | Description
MF_BITMAP | Item displays a bitmap.
MF_CHECKED | Item is checked.
MF_DISABLED | Item is disabled.
MF_GRAYED | Item is grayed.
MF_HILITE | Item is highlighted.
MF_MOUSESELECT | Item is selected with the mouse.
MF_OWNERDRAW | Item is an owner-drawn item.
MF_POPUP | Item opens a drop-down menu or submenu.
MF_SYSMENU | Item is contained in the window menu (also known as the System menu or Control menu). The hmenu parameter identifies the window menu associated with the message.

hmenu
Value of lParam. Handle to the menu that was clicked.

Return Values

If an application processes this message, it should return zero.

Remarks

If the fuFlags parameter contains 0xFFFF and the hmenu parameter contains NULL, the system has closed the menu.

Do not use the value –1 for fuFlags. That is because fuFlags is specified as (UINT) HIWORD(wParam). If HIWORD(wParam) were 0xFFFF, fuFlags (because of the UINT cast) would be 0x0000FFFF, not –1.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Keyboard Accelerators Overview, Keyboard Accelerator Messages, GetSubMenu


WM_SYSCHAR

The WM_SYSCHAR message is posted to the window with the keyboard focus when a WM_SYSKEYDOWN message is translated by the TranslateMessage function. It specifies the character code of a system character key — that is, a character key that is pressed while the alt key is down.

WM_SYSCHAR
chCharCode = (TCHAR) wParam;   // character code
lKeyData = lParam;             // key data

Parameters

chCharCode
Value of wParam. Specifies the character code of the window menu key.
lKeyData
Value of lParam. Specifies the repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag, as shown in the following table:
Value | Meaning
0–15 | Specifies the repeat count for the current message. The value is the number of times the keystroke was auto-repeated as a result of the user holding down the key. If the keystroke is held long enough, multiple messages are sent. However, the repeat count is not cumulative.
16–23 | Specifies the scan code. The value depends on the original equipment manufacturer (OEM).
24 | Specifies whether the key is an extended key, such as the right-hand alt and ctrl keys that appear on an enhanced 101- or 102-key keyboard. The value is 1 if it is an extended key; otherwise, it is 0.
25–28 | Reserved; do not use.
29 | Specifies the context code. The value is 1 if the alt key is held down while the key is pressed; otherwise, the value is 0.
30 | Specifies the previous key state. The value is 1 if the key is down before the message is sent, or it is 0 if the key is up.
31 | Specifies the transition state. The value is 1 if the key is being released, or it is 0 if the key is being pressed.

Return Values

An application should return zero if it processes this message.

Remarks

When the context code is zero, the message can be passed to the TranslateAccelerator function, which will handle it as though it were a standard key message instead of a system character-key message. This allows accelerator keys to be used with the active window even if the active window does not have the keyboard focus.

For enhanced 101- and 102-key keyboards, extended keys are the right alt and ctrl keys on the main section of the keyboard; the ins, del, home, end, page up, page down and arrow keys in the clusters to the left of the numeric keypad; the print scrn key; the break key; the numlock key; and the divide (/) and enter keys in the numeric keypad. Other keyboards may support the extended-key bit in the lKeyData parameter.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Keyboard Accelerators Overview, Keyboard Accelerator Messages, TranslateAccelerator, TranslateMessage, WM_SYSKEYDOWN


WM_SYSCOMMAND

A window receives this message when the user chooses a command from the window menu (formerly known as the system or control menu) or when the user chooses the maximize button, minimize button, restore button, or close button.

WM_SYSCOMMAND
uCmdType = wParam;        // type of system command requested
xPos = LOWORD(lParam);    // horizontal position, in screen coordinates
yPos = HIWORD(lParam);    // vertical position, in screen coordinates

Parameters

uCmdType
Specifies the type of system command requested. This parameter can be one of the following values.
Value | Meaning
SC_CLOSE | Closes the window.
SC_CONTEXTHELP | Changes the cursor 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.
SC_DEFAULT | Selects the default item; the user double-clicked the window menu.
SC_HOTKEY | Activates the window associated with the application-specified hot key. The low-order word of lParam identifies the window to activate.
SC_HSCROLL | Scrolls horizontally.
SC_KEYMENU | Retrieves the window menu as a result of a keystroke.
SC_MAXIMIZE | Maximizes the window.
SC_MINIMIZE | Minimizes the window.
SC_MONITORPOWER Sets the state of the display. This command supports devices that have power-saving features, such as a battery-powered personal computer.

lParam can have the following values:

1 means the display is going to low power.

2 means the display is being shut off.
SC_MOUSEMENU | Retrieves the window menu as a result of a mouse click.
SC_MOVE | Moves the window.
SC_NEXTWINDOW | Moves to the next window.
SC_PREVWINDOW | Moves to the previous window.
SC_RESTORE | Restores the window to its normal position and size.
SC_SCREENSAVE | Executes the screen saver application specified in the [boot] section of the SYSTEM.INI file.
SC_SIZE | Sizes the window.
SC_TASKLIST | Activates the Start menu.
SC_VSCROLL | Scrolls vertically.

xPos
Specifies the horizontal position of the cursor, in screen coordinates, if a window menu command is chosen with the mouse. Otherwise, the xPos parameter is not used.
yPos
Specifies the vertical position of the cursor, in screen coordinates, if a window menu command is chosen with the mouse. This parameter is –1 if the command is chosen using a system accelerator, or zero if using a mnenomic.

Return Values

An application should return zero if it processes this message.

Remarks

The DefWindowProc function carries out the window menu request for the predefined actions specified in the previous table.

In WM_SYSCOMMAND messages, the four low-order bits of the uCmdType parameter are used internally by the system. To obtain the correct result when testing the value of uCmdType, an application must combine the value 0xFFF0 with the uCmdType value by using the bitwise AND operator.

The menu items in a window menu can be modified by using the GetSystemMenu, AppendMenu, InsertMenu, ModifyMenu, InsertMenuItem, and SetMenuItem functions. Applications that modify the window menu must process WM_SYSCOMMAND messages.

An application can carry out any system command at any time by passing a WM_SYSCOMMAND message to DefWindowProc. Any WM_SYSCOMMAND messages not handled by the application must be passed to DefWindowProc. Any command values added by an application must be processed by the application and cannot be passed to DefWindowProc.

Accelerator keys that are defined to choose items from the window menu are translated into WM_SYSCOMMAND messages; all other accelerator keystrokes are translated into WM_COMMAND messages.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Keyboard Accelerators Overview, Keyboard Accelerator Messages, Power Management Overview, AppendMenu, DefWindowProc, GetSystemMenu, InsertMenu, ModifyMenu, WM_COMMAND


Keyboard Input

This overview describes how the system generates keyboard input and how an application receives and processes that input.


About Keyboard Input

All Win32-based applications should accept user input from the keyboard as well as from the mouse. A Win32-based application receives keyboard input in the form of messages posted to its windows.


Keyboard Input Model

The system provides device-independent keyboard support for applications by installing a keyboard device driver appropriate for the current keyboard. The system provides language-independent keyboard support by using the language-specific keyboard layout currently selected by the user or the application. The keyboard device driver receives scan codes from the keyboard, which are sent to the keyboard layout where they are translated into messages and posted to the appropriate windows in your application.

Assigned to each key on a keyboard is a unique value called a scan code, a device-dependent identifier for the key on the keyboard. A keyboard generates two scan codes when the user types a key — one when the user presses the key and another when the user releases the key.

The keyboard device driver interprets a scan code and translates (maps) it to a virtual-key code, a device-independent value defined by the system that identifies the purpose of a key. After translating a scan code, the keyboard layout creates a message that includes the scan code, the virtual-key code, and other information about the keystroke, and then places the message in the system message queue. The system removes the message from the system message queue and posts it to the message queue of the appropriate thread. Eventually, the thread's message loop removes the message and passes it to the appropriate window procedure for processing. The following figure illustrates the keyboard input model.


Keyboard Focus and Activation

The system posts keyboard messages to the message queue of the foreground thread that created the window with the keyboard focus. The keyboard focus is a temporary property of a window. The system shares the keyboard among all windows on the display by shifting the keyboard focus, at the user's direction, from one window to another. The window that has the keyboard focus receives (from the message queue of the thread that created it) all keyboard messages until the focus changes to a different window.

A thread can call the GetFocus function to determine which of its windows (if any) currently has the keyboard focus. A thread can give the keyboard focus to one of its windows by calling the SetFocus function. When the keyboard focus changes from one window to another, the system sends a WM_KILLFOCUS message to the window that has lost the focus, and then sends a WM_SETFOCUS message to the window that has gained the focus.

The concept of keyboard focus is related to that of the active window. The active window is the top-level window the user is currently working with. The window with the keyboard focus is either the active window, or a child window of the active window. So the user can easily identify the active window, the system places it at the top of the Z order and makes its title bar (if it has one) and border highlighted.

The user can activate a top-level window by clicking it, selecting it using the alt+tab or alt+esc key combination, or selecting if from Task List. A thread can activate a top-level window by using the SetActiveWindow function. It can determine whether a top-level window it created is active by using the GetActiveWindow function.

When one window is deactivated and another activated, the system sends the WM_ACTIVATE message. The low-order word of the wParam parameter is zero if the window is being deactivated and nonzero if it is being activated. When the default window procedure receives the WM_ACTIVATE message, it sets the keyboard focus to the active window.


Keystroke Messages

Pressing a key results in a WM_KEYDOWN or WM_SYSKEYDOWN message being placed in the thread message queue associated with the window that has the keyboard focus. Releasing a key results in a WM_KEYUP or WM_SYSKEYUP message being placed in the queue.

Key-up and key-down messages typically occur in pairs, but if the user holds down a key long enough to start the keyboard's automatic repeat feature, the system generates a number of WM_KEYDOWN or WM_SYSKEYDOWN messages in a row. It then generates a single WM_KEYUP or WM_SYSKEYUP message when the user releases the key.


System and Nonsystem Keystrokes

The system makes a distinction between system keystrokes and nonsystem keystrokes. System keystrokes produce system keystroke messages, WM_SYSKEYDOWN and WM_SYSKEYUP. Nonsystem keystrokes produce nonsystem keystroke messages, WM_KEYDOWN and WM_KEYUP.

If your window procedure must process a system keystroke message, make sure that after processing the message the procedure passes it to the DefWindowProc function. Otherwise, all system operations involving the alt key will be disabled whenever the window has the keyboard focus. That is, the user won't be able to access the window's menus or System menu, or use the alt+esc or alt+tab key combination to activate a different window.

System keystroke messages are primarily for use by the system rather than by an application. The system uses them to provide its built-in keyboard interface to menus and to allow the user to control which window is active. System keystroke messages are generated when the user types a key in combination with the alt key, or when the user types and no window has the keyboard focus (for example, when the active application is minimized). In this case, the messages are posted to the message queue associated with the active window.

Nonsystem keystroke messages are for use by application windows; the DefWindowProc function does nothing with them. A window procedure can discard any nonsystem keystroke messages that it does not need.


Virtual-Key Codes Described

The wParam parameter of a keystroke message contains the virtual-key code of the key that was pressed or released. A window procedure processes or ignores a keystroke message, depending on the value of the virtual-key code.

A typical window procedure processes only a small subset of the keystroke messages that it receives and ignores the rest. For example, a window procedure might process only WM_KEYDOWN keystroke messages, and only those that contain virtual-key codes for the cursor movement keys, shift keys (also called control keys), and function keys. A typical window procedure does not process keystroke messages from character keys. Instead, it uses the TranslateMessage function to convert the message into character messages. For more information about TranslateMessage and character messages, see Character Messages.


Keystroke Message Flags

The lParam parameter of a keystroke message contains additional information about the keystroke that generated the message. This information includes the repeat count, the scan code, the extended-key flag, the context code, the previous key-state flag, and the transition-state flag. The following illustration shows the locations of these flags and values in the lParam parameter.

An application can use the following values to manipulate the keystroke flags.

Value | Meaning
KF_ALTDOWN | Manipulates the alt key flag, which indicated if the alt key is pressed.
KF_DLGMODE | Manipulates the dialog mode flag, which indicates whether a dialog box is active.
KF_EXTENDED | Manipulates the extended key flag.
KF_MENUMODE | Manipulates the menu mode flag, which indicates whether a menu is active.
KF_REPEAT | Manipulates the repeat count.
KF_UP | Manipulates the transition state flag.

Repeat Count

You can check the repeat count to determine whether a keystroke message represents more than one keystroke. The system increments the count when the keyboard generates WM_KEYDOWN or WM_SYSKEYDOWN messages faster than an application can process them. This often occurs when the user holds down a key long enough to start the keyboard's automatic repeat feature. Instead of filling the system message queue with the resulting key-down messages, the system combines the messages into a single key down message and increments the repeat count. Releasing a key cannot start the automatic repeat feature, so the repeat count for WM_KEYUP and WM_SYSKEYUP messages is always set to 1.

Scan Code

The scan code is the value that the keyboard hardware generates when the user presses a key. It is a device-dependent value that identifies the key pressed, as opposed to the character represented by the key. An application typically ignores scan codes. Instead, it uses the device-independent virtual-key codes to interpret keystroke messages.

Extended-Key Flag

The extended-key flag indicates whether the keystroke message originated from one of the additional keys on the enhanced keyboard. The extended keys consist of the alt and ctrl keys on the right-hand side of the keyboard; the ins, del, home, end, page up, page down and arrow keys in the clusters to the left of the numeric keypad; the num lock key; the break (ctrl+pause) key; the print scrn key; and the divide (/) and enter keys in the numeric keypad. The extended-key flag is set if the key is an extended key.

Context Code

The context code indicates whether the alt key was down when the keystroke message was generated. The code is 1 if the alt key was down and 0 if it was up.

Previous Key-State Flag

The previous key-state flag indicates whether the key that generated the keystroke message was previously up or down. It is 1 if the key was previously down and 0 if the key was previously up. You can use this flag to identify keystroke messages generated by the keyboard's automatic repeat feature. This flag is set to 1 for WM_KEYDOWN and WM_SYSKEYDOWN keystroke messages generated by the automatic repeat feature. It is always set to 0 for WM_KEYUP and WM_SYSKEYUP messages.

Transition-State Flag

The transition-state flag indicates whether pressing a key or releasing a key generated the keystroke message. This flag is always set to 0 for WM_KEYDOWN and WM_SYSKEYDOWN messages; it is always set to 1 for WM_KEYUP and WM_SYSKEYUP messages.


Character Messages

Keystroke messages provide a lot of information about keystrokes, but they don't provide character codes for character keystrokes. To retrieve character codes, an application must include the TranslateMessage function in its thread message loop. TranslateMessage passes a WM_KEYDOWN or WM_SYSKEYDOWN message to the keyboard layout. The layout examines the message's virtual-key code and, if it corresponds to a character key, provides the character code equivalent (taking into account the state of the shift and caps lock keys). It then generates a character message that includes the character code and places the message at the top of the message queue. The next iteration of the message loop removes the character message from the queue and dispatches the message to the appropriate window procedure.


Nonsystem Character Messages

A window procedure can receive four different character messages, including WM_CHAR, WM_DEADCHAR, WM_SYSCHAR, and WM_SYSDEADCHAR. The TranslateMessage function generates a WM_CHAR or WM_DEADCHAR message when it processes a WM_KEYDOWN message. Similarly, it generates a WM_SYSCHAR or WM_SYSDEADCHAR message when it processes a WM_SYSKEYDOWN message.

An application that processes keyboard input typically ignores all but the WM_CHAR message, passing any other messages to the DefWindowProc function. The system uses the WM_SYSCHAR and WM_SYSDEADCHAR messages to implement menu mnemonics.

The wParam parameter of all character messages contains the character code of the character key that was pressed. The value of the character code depends on the window class of the window receiving the message. If the Unicode version of the RegisterClass function was used to register the window class, the system provides Unicode characters to all windows of that class. Otherwise, the system provides ASCII character codes. For more information, see Unicode and Character Sets.

The contents of the lParam parameter of a character message are identical to the contents of the lParam parameter of the key-down message that was translated to produce the character message. For information, see Keystroke Message Flags.


Dead-Character Messages

Some non-English keyboards contain character keys that are not expected to produce characters by themselves. Instead, they are used to add a diacritic to the character produced by the subsequent keystroke. These keys are called dead keys. The circumflex key on a German keyboard is an example of a dead key. To enter the character consisting of an "o" with a circumflex, a German user would type the circumflex key followed by the "o" key. The window with the keyboard focus would receive the following sequence of messages:

WM_KEYDOWN
WM_DEADCHAR
WM_KEYUP
WM_KEYDOWN
WM_CHAR
WM_KEYUP

TranslateMessage generates the WM_DEADCHAR message when it processes the WM_KEYDOWN message from a dead key. Although the wParam parameter of the WM_DEADCHAR message contains the character code of the diacritic for the dead key, an application typically ignores the message. Instead, it processes the WM_CHAR message generated by the subsequent keystroke. The wParam parameter of the WM_CHAR message contains the character code of the letter with the diacritic. If the subsequent keystroke generates a character that cannot be combined with a diacritic, the system generates two WM_CHAR messages. The wParam parameter of the first contains the character code of the diacritic; the wParam parameter of the second contains the character code of the subsequent character key.

The TranslateMessage function generates the WM_SYSDEADCHAR message when it processes the WM_SYSKEYDOWN message from a system dead key (a dead key that is pressed in combination with the alt key). An application typically ignores the WM_SYSDEADCHAR message.


Key Status

While processing a keyboard message, an application may need to determine the status of another key besides the one that generated the current message. For example, a word-processing application that allows the user to press shift+end to select a block of text must check the status of the shift key whenever it receives a keystroke message from the end key. The application can use the GetKeyState function to determine the status of a virtual key at the time the current message was generated; it can use the GetAsyncKeyState function to retrieve the current status of a virtual key.

The keyboard layout maintains a list of names. The name of a key that produces a single character is the same as the character produced by the key. The name of a noncharacter key such as tab and enter is stored as a character string. An application can retrieve the name of any key from the device driver by calling the GetKeyNameText function.


Keystroke and Character Translations

The system includes several special purpose functions that translate scan codes, character codes, and virtual-key codes provided by various keystroke messages. These functions include MapVirtualKey, ToAscii, ToUnicode, and VkKeyScan.


Hot-Key Support

The Win32 API provides a set of functions that applications can use to define hot keys. A hot key is a key combination that generates a WM_HOTKEY message, a message the system places at the top of a thread's message queue, bypassing any existing messages in the queue. Applications use hot keys to obtain high-priority keyboard input from the user. For example, by defining a hot key consisting of the ctrl+c key combination, an application can allow the user to cancel a lengthy operation.

To define a hot key, an application calls the RegisterHotKey function, specifying the combination of keys that generates the WM_HOTKEY message, the handle to the window to receive the message, and the identifier of the hot key. When the user presses the hot key, a WM_HOTKEY message is placed in the message queue of the thread that created the given window. The wParam parameter of the message contains the identifier of the hot key. The application can define multiple hot keys for a thread, but each hot key in the thread must have a unique identifier. Before the application terminates, it should use the UnregisterHotKey function to destroy the hot key.

Applications can use a hot key control to make it easy for the user to choose a hot key. Hot key controls are typically used to define a hot key that activates a window; they do not use the RegisterHotKey and UnregisterHotKey functions. Instead, an application that uses a hot key control typically sends the WM_SETHOTKEY message to set the hot key. Whenever the user presses the hot key, the system sends a WM_SYSCOMMAND message specifying SC_HOTKEY. For more information about hot key controls, see Hot-Key Controls.


Languages, Locales, and Keyboard Layouts

A language is a natural language, such as English, French, and Japanese. A sublanguange is a variant of a natural language that is spoken in a specific geographical region, such as the English sublanguages spoken in Great Britain and the United States. Win32-based applications use values, called language identifiers, to uniquely identify languages and sublanguages.

Applications typically use locales to set the language in which input and output is processed. Setting the locale for the keyboard, for example, affects the character values generated by the keyboard. Setting the locale for the display or printer affects the glyphs displayed or printed. Applications set the locale for a keyboard by loading and using keyboard layouts. They set the locale for a display or printer by selecting a font that supports the given locale.

A keyboard layout not only specifies the physical position of the keys on the keyboard but also determines the character values generated by pressing those keys. Each layout identifies the current input language and determines which character values are generated by which keys and key combinations.

Every keyboard layout has a corresponding handle that identifies the layout and language. The low word of the handle is a language identifier. The high word is a device handle, specifying the physical layout, or is zero, indicating a default physical layout. The user can associate any input language with a given physical layout. For example, an English-speaking user who very occasionally works in French can set the input language of the keyboard to French without changing the physical layout of the keyboard. This means the user can enter text in French using the familiar English layout.

Applications are generally not expected to manipulate input languages directly. Instead, the user sets up language and layout combinations, then switches among them. When the user clicks into text marked with a different language, the application calls the ActivateKeyboardLayout function to activate the user's default layout for that language. If the user edits text in a language which is not in the active list, the application can call the LoadKeyboardLayout function with the language to get a layout based on that language.

The ActivateKeyboardLayout function sets the input language for the current task. The hkl parameter can be either the handle to the keyboard layout or a zero-extended language identifier. Keyboard layout handles can be obtained from the LoadKeyboardLayout or GetKeyboardLayoutList function. The HKL_NEXT and HKL_PREV values can also be used to select the next or previous keyboard. For some operating systems, the KLF_UNLOADPREVIOUS value has no meaning and is ignored.

The GetKeyboardLayoutName function retrieves the name of the active keyboard layout for the calling thread. If an application creates the active layout using the LoadKeyboardLayout function, GetKeyboardLayoutName retrieves the same string used to create the layout. Otherwise, the string is the primary language identifier corresponding to the locale of the active layout. This means the function may not necessarily differentiate among different layouts with the same primary language, so cannot return specific information about the input language. The GetKeyboardLayout function, however, can be used to determine the input language.

The LoadKeyboardLayout function loads a keyboard layout and makes the layout available to the user. Applications can make the layout immediately active for the current thread by using the KLF_ACTIVATE value. An application can use the KLF_REORDER value to reorder the layouts without also specifying the KLF_ACTIVATE value. Applications should always use the KLF_SUBSTITUTE_OK value when loading keyboard layouts to ensure that the user's preference, if any, is selected. For some operating systems, the KLF_UNLOADPREVIOUS value is ignored.

For multilingual support, the LoadKeyboardLayout function provides the KLF_REPLACELANG and KLF_NOTELLSHELL flags. The KLF_REPLACELANG flag directs the function to replace an existing keyboard layout without changing the language. Attempting to replace an existing layout using the same language identifier but without specifying KLF_REPLACELANG is an error. The KLF_NOTELLSHELL flag prevents the function from notifying the shell when a keyboard layout is added or replaced. This is useful for applications that add multiple layouts in a consecutive series of calls. This flag should be used in all but the last call.

The UnloadKeyboardLayout function is restricted in that it cannot unload the system default input language. This ensures that the user always has one layout available for enter text using the same character set as used by the shell and file system.


Using Keyboard Input

A window receives keyboard input in the form of keystroke messages and character messages. The message loop associated with the window must include code to translate keystroke messages into the corresponding character messages. If the window displays keyboard input in its client area, it should create and display a caret to indicate the position where the next character will be entered. The following sections describe the code involved in receiving, processing, and displaying keyboard input:

  • Processing keystroke messages
  • Translating character messages
  • Processing character messages
  • Using the caret
  • Displaying keyboard input


Processing Keystroke Messages

The window procedure of the window that has the keyboard focus receives keystroke messages when the user types at the keyboard. The keystroke messages are WM_KEYDOWN, WM_KEYUP, WM_SYSKEYDOWN, and WM_SYSKEYUP. A typical window procedure ignores all keystroke messages except WM_KEYDOWN. The system posts the WM_KEYDOWN message when the user presses a key.

When the window procedure receives the WM_KEYDOWN message, it should examine the virtual-key code that accompanies the message to determine how to process the keystroke. The virtual-key code is in the message's wParam parameter. Typically, an application processes only keystrokes generated by non-character keys, including the function keys, the cursor movement keys, and the special-purpose keys such as ins, del, home and end.

The following example shows the window procedure framework that a typical application uses to receive and process keystroke messages.

case WM_KEYDOWN:
            switch (wParam)
            {
                case VK_LEFT:

                    // Process the LEFT ARROW key.

                    break;

                case VK_RIGHT:

                    // Process the RIGHT ARROW key.

                    break;

                case VK_UP:

                    // Process the UP ARROW key.

                    break;

                case VK_DOWN:

                    // Process the DOWN ARROW key.

                    break;

                case VK_HOME:

                    // Process the HOME key.

                    break;

                case VK_END:

                    // Process the END key.

                    break;

                case VK_INSERT:

                    // Process the INS key.

                    break;

                case VK_DELETE:

                    // Process the DEL key.

                    break;

                case VK_F2:

                    // Process the F2 key.

                    break;

                // Process other non-character keystrokes.

                default:
                    break;
            }


Translating Character Messages

Any thread that receives character input from the user must include the TranslateMessage function in its message loop. This function examines the virtual-key code of a keystroke message and, if the code corresponds to a character, places a character message into the message queue. The character message is removed and dispatched on the next iteration of the message loop; the wParam parameter of the message contains the character code.

In general, a thread's message loop should use the TranslateMessage function to translate every message, not just virtual-key messages. Although TranslateMessage has no effect on other types of messages, it guarantees that keyboard input is translated correctly. The following example shows how to include the TranslateMessage function in a typical thread message loop.

while (GetMessage(&msg, (HWND) NULL, 0, 0))
{
    if (TranslateAccelerator(hwndMain, haccl, &msg) == 0)
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}


Processing Character Messages

A window procedure receives a character message when the TranslateMessage function translates a virtual-key code corresponding to a character key. The character messages are WM_CHAR, WM_DEADCHAR, WM_SYSCHAR, and WM_SYSDEADCHAR. A typical window procedure ignores all character messages except WM_CHAR. The TranslateMessage function generates a WM_CHAR message when the user presses any of the following keys:

  • Any character key
  • backspace
  • enter (carriage return)
  • esc
  • shift+enter (linefeed)
  • tab

When a window procedure receives the WM_CHAR message, it should examine the character code that accompanies the message to determine how to process the character. The character code is in the message's wParam parameter.

The following example shows the window procedure framework that a typical application uses to receive and process character messages.

case WM_CHAR:
            switch (wParam)
            {
                case 0x08:

                    // Process a backspace.

                    break;

                case 0x0A:

                    // Process a linefeed.

                    break;

                case 0x1B:

                    // Process an escape.

                    break;

                case 0x09:

                    // Process a tab.

                    break;

                case 0x0D:

                    // Process a carriage return.

                    break;

                default:

                    // Process displayable characters.

                    break;
            }


Using the Caret

A window that receives keyboard input typically displays the characters the user types in the window's client area. A window should use a caret to indicate the position in the client area where the next character will appear. The window should also create and display the caret when it receives the keyboard focus, and hide and destroy the caret when it loses the focus. A window can perform these operations in the processing of the WM_SETFOCUS and WM_KILLFOCUS messages. For more information about carets, see Carets.


Displaying Keyboard Input

The example in this section shows how an application can receive characters from the keyboard, display them in the client area of a window, and update the position of the caret with each character typed. It also demonstrates how to move the caret in response to the left arrow, right arrow, home and end keystrokes, and shows how to highlight selected text in response to the shift+right arrow key combination.

During processing of the WM_CREATE message, the window procedure shown in the example allocates a 64K buffer for storing keyboard input. It also retrieves the metrics of the currently loaded font, saving the height and average width of characters in the font. The height and width are used in processing the WM_SIZE message to calculate the line length and maximum number of lines, based on the size of the client area.

The window procedure creates and displays the caret when processing the WM_SETFOCUS message. It hides and deletes the caret when processing the WM_KILLFOCUS message.

When processing the WM_CHAR message, the window procedure displays characters, stores them in the input buffer, and updates the caret position. The window procedure also converts tab characters to four consecutive space characters. Backspace, linefeed, and escape characters generate a beep, but are not otherwise processed.

The window procedure performs the left, right, end, and home caret movements when processing the WM_KEYDOWN message. While processing the action of the right arrow key, the window procedure checks the state of the shift key and, if it is down, selects the character to the right of the caret as the caret is moved.

Note that the following code is written so that it can be compiled either as Unicode or as ANSI. If the source code defines UNICODE, strings are handled as Unicode characters; otherwise, they are handled as ANSI characters.

#define BUFSIZE 65535
#define SHIFTED 0x8000

LONG APIENTRY MainWndProc(HWND hwndMain, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    HDC hdc;                   // handle to device context
    TEXTMETRIC tm;             // structure for text metrics
    static DWORD dwCharX;      // average width of characters
    static DWORD dwCharY;      // height of characters
    static DWORD dwClientX;    // width of client area
    static DWORD dwClientY;    // height of client area
    static DWORD dwLineLen;    // line length
    static DWORD dwLines;      // text lines in client area
    static int nCaretPosX = 0; // horizontal position of caret
    static int nCaretPosY = 0; // vertical position of caret
    static int nCharWidth = 0; // width of a character
    static int cch = 0;        // characters in buffer
    static int nCurChar = 0;   // index of current character
    static PTCHAR pchInputBuf; // address of input buffer
    int i, j;                  // loop counters
    int cCR = 0;               // count of carriage returns
    int nCRIndex = 0;          // index of last carriage return
    int nVirtKey;              // virtual-key code
    TCHAR szBuf[128];          // temporary buffer
    TCHAR ch;                  // current character
    PAINTSTRUCT ps;            // required by BeginPaint
    RECT rc;                   // output rectangle for DrawText
    SIZE sz;                   // string dimensions
    COLORREF crPrevText;       // previous text color
    COLORREF crPrevBk;         // previous background color

    switch (uMsg)
    {
        case WM_CREATE:

            // Get the metrics of the current font.

            hdc = GetDC(hwndMain);
            GetTextMetrics(hdc, &tm);
            ReleaseDC(hwndMain, hdc);

            // Save the average character width and height.

            dwCharX = tm.tmAveCharWidth;
            dwCharY = tm.tmHeight;

            // Allocate a buffer to store keyboard input.

            pchInputBuf = (LPTSTR) GlobalAlloc(GPTR,
                BUFSIZE * sizeof(TCHAR));
            return 0;

        case WM_SIZE:

            // Save the new width and height of the client area.

            dwClientX = LOWORD(lParam);
            dwClientY = HIWORD(lParam);

            // Calculate the maximum width of a line and the
            // maximum number of lines in the client area.

            dwLineLen = dwClientX - dwCharX;
            dwLines = dwClientY / dwCharY;
            break;

        case WM_SETFOCUS:

            // Create, position, and display the caret when the
            // window receives the keyboard focus.

            CreateCaret(hwndMain, (HBITMAP) 1, 0, dwCharY);
            SetCaretPos(nCaretPosX, nCaretPosY * dwCharY);
            ShowCaret(hwndMain);
            break;

        case WM_KILLFOCUS:

            // Hide and destroy the caret when the window loses the
            // keyboard focus.

            HideCaret(hwndMain);
            DestroyCaret();
            break;

        case WM_CHAR:
            switch (wParam)
            {
                case 0x08:  // backspace
                case 0x0A:  // linefeed
                case 0x1B:  // escape
                    MessageBeep(0xFFFFFFFF);
                    return 0;

                case 0x09:  // tab

                    // Convert tabs to four consecutive spaces.

                    for (i = 0; i < 4; i++)
                        SendMessage(hwndMain, WM_CHAR, 0x20, 0);
                    return 0;

                case 0x0D:  // carriage return

                    // Record the carriage return and position the
                    // caret at the beginning of the new line.

                    pchInputBuf[cch++] = 0x0D;
                    nCaretPosX = 0;
                    nCaretPosY += 1;
                    break;

                default:    // displayable character

                    ch = (TCHAR) wParam;
                    HideCaret(hwndMain);

                    // Retrieve the character's width and output
                    // the character.

                    hdc = GetDC(hwndMain);
                    GetCharWidth32(hdc, (UINT) wParam, (UINT) wParam,
                        &nCharWidth);
                    TextOut(hdc, nCaretPosX, nCaretPosY * dwCharY,
                        &ch, 1);
                    ReleaseDC(hwndMain, hdc);

                    // Store the character in the buffer.

                    pchInputBuf[cch++] = ch;

                    // Calculate the new horizontal position of the
                    // caret. If the position exceeds the maximum,
                    // insert a carriage return and move the caret
                    // to the beginning of the next line.

                    nCaretPosX += nCharWidth;
                    if ((DWORD) nCaretPosX > dwLineLen)
                    {
                        nCaretPosX = 0;
                        pchInputBuf[cch++] = 0x0D;
                        ++nCaretPosY;
                    }
                    nCurChar = cch;
                    ShowCaret(hwndMain);
                    break;
            }
            SetCaretPos(nCaretPosX, nCaretPosY * dwCharY);
            break;

        case WM_KEYDOWN:
            switch (wParam)
            {
                case VK_LEFT:   // LEFT ARROW

                    // The caret can move only to the beginning of
                    // the current line.

                    if (nCaretPosX > 0)
                    {
                        HideCaret(hwndMain);

                        // Retrieve the character to the left of
                        // the caret, calculate the character's
                        // width, then subtract the width from the
                        // current horizontal position of the caret
                        // to obtain the new position.

                        ch = pchInputBuf[--nCurChar];
                        hdc = GetDC(hwndMain);
                        GetCharWidth32(hdc, ch, ch, &nCharWidth);
                        ReleaseDC(hwndMain, hdc);
                        nCaretPosX = max(nCaretPosX - nCharWidth,
                            0);
                        ShowCaret(hwndMain);
                    }
                    break;

                case VK_RIGHT:  // RIGHT ARROW

                    // Caret moves to the right or, when a carriage
                    // return is encountered, to the beginning of
                    // the next line.

                    if (nCurChar < cch)
                    {
                        HideCaret(hwndMain);

                        // Retrieve the character to the right of
                        // the caret. If it's a carriage return,
                        // position the caret at the beginning of
                        // the next line.

                        ch = pchInputBuf[nCurChar];
                        if (ch == 0x0D)
                        {
                            nCaretPosX = 0;
                            nCaretPosY++;
                        }

                        // If the character isn't a carriage
                        // return, check to see whether the SHIFT
                        // key is down. If it is, invert the text
                        // colors and output the character.

                        else
                        {
                            hdc = GetDC(hwndMain);
                            nVirtKey = GetKeyState(VK_SHIFT);
                            if (nVirtKey & SHIFTED)
                            {
                                crPrevText = SetTextColor(hdc,
                                    RGB(255, 255, 255));
                                crPrevBk = SetBkColor(hdc,
                                    RGB(0,0,0));
                                TextOut(hdc, nCaretPosX,
                                    nCaretPosY * dwCharY,
                                    &ch, 1);
                                SetTextColor(hdc, crPrevText);
                                SetBkColor(hdc, crPrevBk);
                            }

                            // Get the width of the character and
                            // calculate the new horizontal
                            // position of the caret.

                            GetCharWidth32(hdc, ch, ch, &nCharWidth);
                            ReleaseDC(hwndMain, hdc);
                            nCaretPosX = nCaretPosX + nCharWidth;
                        }
                        nCurChar++;
                        ShowCaret(hwndMain);
                        break;
                    }
                    break;

                case VK_UP:     // UP ARROW
                case VK_DOWN:   // DOWN ARROW
                    MessageBeep(0xFFFFFFFF);
                    return 0;

                case VK_HOME:   // HOME

                    // Set the caret's position to the upper left
                    // corner of the client area.

                    nCaretPosX = nCaretPosY = 0;
                    nCurChar = 0;
                    break;

                case VK_END:    // END

                    // Move the caret to the end of the text.

                    for (i=0; i < cch; i++)
                    {
                        // Count the carriage returns and save the
                        // index of the last one.

                        if (pchInputBuf[i] == 0x0D)
                        {
                            cCR++;
                            nCRIndex = i + 1;
                        }
                    }
                    nCaretPosY = cCR;

                    // Copy all text between the last carriage
                    // return and the end of the keyboard input
                    // buffer to a temporary buffer.

                    for (i = nCRIndex, j = 0; i < cch; i++, j++)
                        szBuf[j] = pchInputBuf[i];
                    szBuf[j] = TEXT('\0');

                    // Retrieve the text extent and use it
                    // to set the horizontal position of the
                    // caret.

                    hdc = GetDC(hwndMain);
                    GetTextExtentPoint32(hdc, szBuf, lstrlen(szBuf),
                        &sz);
                    nCaretPosX = sz.cx;
                    ReleaseDC(hwndMain, hdc);
                    nCurChar = cch;
                    break;

                default:
                    break;
            }
            SetCaretPos(nCaretPosX, nCaretPosY * dwCharY);
            break;

        case WM_PAINT:
            if (cch == 0)       // nothing in input buffer
                break;

            hdc = BeginPaint(hwndMain, &ps);
            HideCaret(hwndMain);

            // Set the clipping rectangle, and then draw the text
            // into it.

            SetRect(&rc, 0, 0, dwLineLen, dwClientY);
            DrawText(hdc, pchInputBuf, -1, &rc, DT_LEFT);

            ShowCaret(hwndMain);
            EndPaint(hwndMain, &ps);
            break;

        // Process other messages.

        case WM_DESTROY:
            PostQuitMessage(0);

            // Free the input buffer.

            GlobalFree((HGLOBAL) pchInputBuf);
            UnregisterHotKey(hwndMain, 0xAAAA);
            break;

        default:
            return DefWindowProc(hwndMain, uMsg, wParam, lParam);
    }
    return NULL;
}


Keyboard Input Reference

The following elements are associated with keyboard input.

  • Keyboard Input Functions
  • Keyboard Input Structures
  • Keyboard Input Messages


Keyboard Input Functions

The following functions are used to receive and process keyboard input.

ActivateKeyboardLayout
EnableWindow
GetActiveWindow
GetAsyncKeyState
GetFocus
GetKeyboardLayout
GetKeyboardLayoutList
GetKeyboardLayoutName
GetKeyboardState
GetKeyNameText
GetKeyState
IsWindowEnabled
keybd_event
LoadKeyboardLayout
MapVirtualKey
MapVirtualKeyEx
OemKeyScan
RegisterHotKey
SendInput
SetActiveWindow
SetFocus
SetKeyboardState
ToAscii
ToAsciiEx
ToUnicode
ToUnicodeEx
UnloadKeyboardLayout
UnregisterHotKey
VkKeyScan
VkKeyScanEx

Obsolete Functions

GetKBCodePage


ActivateKeyboardLayout

The implementations of ActivateKeyboardLayout in Windows NT and Windows 95 are substantially different. To accommodate these differences, this reference page first presents the Windows NT implementation in its entirety, followed by the Windows 95 version.

Windows NT
The ActivateKeyboardLayout function activates a different keyboard layout and sets the active keyboard layout for the entire system rather than the calling thread.

HKL ActivateKeyboardLayout(
  HKL hkl,     // handle to keyboard layout
  UINT Flags   // keyboard layout flags
);

Parameters

hkl
Handle to the keyboard layout to be activated. The layout must have been loaded by a previous call to the LoadKeyboardLayout function. This parameter must be either the handle to a keyboard layout or one of the following values.
Value | Meaning
HKL_NEXT | Selects the next layout in the circular list of loaded layouts maintained by the system.
HKL_PREV | Selects the previous layout in the circular list of loaded layouts maintained by the system.

Flags
Specifies how the keyboard layout is to be activated. This parameter can be one of the following values.
Value | Meaning
KLF_REORDER If this bit is set, the system's circular list of loaded keyboard layouts is reordered. If this bit is not set, the list is rotated without a change of order. For example, if a user had an English layout active, as well as having French, German and Spanish layouts loaded (in that order), then activating the German layout with the KLF_REORDER bit set would produce the following order: German, English, French, Spanish. Activating the German layout without the KLF_REORDER bit set would produce the following order: German, Spanish, English, French.

If less than three keyboard layouts are loaded, the value of this flag is irrelevant.

KLF_SETFORPROCESS | Windows NT 5.0 and later: Activates the specified keyboard layout for the entire process and sends the WM_INPUTLANGCHANGE message to all threads in the current process.
KLF_UNLOADPREVIOUS | The previously active layout is unloaded.

Return Values

If the function succeeds, the return value is the previous keyboard layout handle. Otherwise, it is zero. To get extended error information, use the GetLastError function.

Remarks

Several keyboard layouts can be loaded at any one time, but only one is active at a time. Loading multiple keyboard layouts makes it possible to rapidly switch between layouts.

Windows 95
The ActivateKeyboardLayout function sets the input language for the current thread. This function accepts a keyboard layout handle that identifies a locale as well as the physical layout of the keyboard.

HKL ActivateKeyboardLayout(
  HKL hkl,     // handle to keyboard layout
  UINT Flags   // keyboard layout flags
);

Parameters

hkl
Handle to a keyboard layout or a zero-extended language identifier. This parameter can be any valid keyboard layout handle obtained using the LoadKeyboardLayout or GetKeyboardLayoutList function or one of the following values.
Value | Meaning
HKL_NEXT | Selects the next layout in the keyboard layouts list maintained by the system.
HKL_PREV | Selects the previous layout in the keyboards layout list maintained by the system.

Flags
Specifies the keyboard layout flags. The value of this parameter can be:
Value | Meaning
KLF_REORDER | Reorders the keyboard layouts list by moving the given keyboard layout handle to the head of the list. If this value is not given, the list is rotated without a change of order. For example, if a user had an English layout active, as well as having French, German and Spanish layouts loaded (in that order), then activating the German layout with the KLF_REORDER bit set would produce the following order: German, English, French, Spanish. Activating the German layout without the KLF_REORDER value set would produce the following order: German, Spanish, English, French.

Return Values

If the function succeeds, the return value is the previous keyboard layout handle. Otherwise, it is zero. To get extended error information, use the GetLastError function.

Remarks

Several keyboard layouts can be loaded at any one time, but only one is active at a time. Loading multiple keyboard layouts makes it possible to rapidly switch between layouts.

An application can create a valid keyboard layout handle by setting the high word to zero and the low word to a locale identifier. Using such keyboard layout handles changes the input language without affecting the physical layout.

When multiple input method editors (IMEs) are allowed for each locale, passing in a keyboard layout handle in which the high word (the device handle) is zero activates the first IME in the list "belonging" to the locale.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, LoadKeyboardLayout, GetKeyboardLayoutName, UnloadKeyboardLayout


EnableWindow

The EnableWindow function enables or disables mouse and keyboard input to the specified window or control. When input is disabled, the window does not receive input such as mouse clicks and key presses. When input is enabled, the window receives all input.

BOOL EnableWindow(
  HWND hWnd,     // handle to window
  BOOL bEnable   // flag for enabling or disabling input
);

Parameters

hWnd
Handle to the window to be enabled or disabled.
bEnable
Specifies whether to enable or disable the window. If this parameter is TRUE, the window is enabled. If the parameter is FALSE, the window is disabled.

Return Values

If the window was previously disabled, the return value is nonzero.

If the window was not previously disabled, the return value is zero. To get extended error information, call GetLastError.

Remarks

If the enabled state of a window is changing, a WM_ENABLE message is sent before the EnableWindow function returns. If a window is already disabled, all its child windows are implicitly disabled, although they are not sent a WM_ENABLE message.

A window must be enabled before it can be activated. For example, if an application is displaying a modeless dialog box and has disabled its main window, the application must enable the main window before destroying the dialog box. Otherwise, another window will receive the keyboard focus and be activated. If a child window is disabled, it is ignored when the system tries to determine which window should receive mouse messages.

By default, a window is enabled when it is created. To create a window that is initially disabled, an application can specify the WS_DISABLED style in the CreateWindow or CreateWindowEx function. After a window has been created, an application can use EnableWindow to enable or disable the window.

An application can use this function to enable or disable a control in a dialog box. A disabled control cannot receive the keyboard focus, nor can a user gain access to it.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, CreateWindow, CreateWindowEx, IsWindowEnabled, WM_ENABLE


GetActiveWindow

The GetActiveWindow function retrieves the window handle to the active window associated with the calling thread's message queue.

HWND GetActiveWindow(VOID)

Parameters

This function has no parameters.

Return Values

The return value is the handle to the active window associated with the calling thread's message queue. Otherwise, the return value is NULL.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, SetActiveWindow


GetAsyncKeyState

The GetAsyncKeyState function determines whether a key is up or down at the time the function is called, and whether the key was pressed after a previous call to GetAsyncKeyState.

SHORT GetAsyncKeyState(
  int vKey   // virtual-key code
);

Parameters

vKey
Specifies one of 256 possible virtual-key codes. For more information, see Virtual-Key Codes.

Windows NT: You can use left- and right-distinguishing constants to specify certain keys. See the Remarks section for further information.

Return Values

If the function succeeds, the return value specifies whether the key was pressed since the last call to GetAsyncKeyState, and whether the key is currently up or down. If the most significant bit is set, the key is down, and if the least significant bit is set, the key was pressed after the previous call to GetAsyncKeyState. The return value is zero if a window in another thread or process currently has the keyboard focus.

Windows 95: Windows 95 does not support the left- and right-distinguishing constants. If you call GetAsyncKeyState with these constants, the return value is zero.

Remarks

The GetAsyncKeyState function works with mouse buttons. However, it checks on the state of the physical mouse buttons, not on the logical mouse buttons that the physical buttons are mapped to. For example, the call GetAsyncKeyState(VK_LBUTTON) always returns the state of the left physical mouse button, regardless of whether it is mapped to the left or right logical mouse button. You can determine the system's current mapping of physical mouse buttons to logical mouse buttons by calling

GetSystemMetrics(SM_SWAPBUTTON)

which returns TRUE if the mouse buttons have been swapped.

You can use the virtual-key code constants VK_SHIFT, VK_CONTROL, and VK_MENU as values for the vKey parameter. This gives the state of the shift, ctrl, or alt keys without distinguishing between left and right.

Windows NT: You can use the following virtual-key code constants as values for vKey to distinguish between the left and right instances of those keys.

Code | Meaning
VK_LSHIFT | VK_RSHIFT
VK_LCONTROL | VK_RCONTROL
VK_LMENU | VK_RMENU

These left- and right-distinguishing constants are only available when you call the GetKeyboardState, SetKeyboardState, GetAsyncKeyState, GetKeyState, and MapVirtualKey functions.

Windows CE: The GetAsyncKeyState function supports the left and right virtual key constants, so you can determine whether the left key or the right key was pressed. These constants are VK_LCONTROL, VK_RCONTROL, VK_LMENU, VK_RMENU, VK_LSHIFT, and VK_RSHIFT.

The least significant bit of the return value is not valid in Windows CE, and should be ignored.

GetAsyncKeyState will return the current key state even if a window in another thread or process currently has the keyboard focus.

You can also use the VK_LBUTTON virtual-key code constant to determine the state of the stylus tip, (up/down), on the touch-screen.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, GetKeyboardState, GetKeyState, GetSystemMetrics, MapVirtualKey, SetKeyboardState


GetFocus

The GetFocus function retrieves the handle to the window that has the keyboard focus, if the window is associated with the calling thread's message queue.

HWND GetFocus(VOID)

Parameters

This function has no parameters.

Return Values

The return value is the handle to the window with the keyboard focus. If the calling thread's message queue does not have an associated window with the keyboard focus, the return value is NULL.

Remarks

Even if GetFocus returns NULL, another thread's queue may be associated with a window that has the keyboard focus.

Use the GetForegroundWindow function to retrieve the handle to the window with which the user is currently working. You can associate your thread's message queue with the windows owned by another thread by using the AttachThreadInput function.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, AttachThreadInput, GetForegroundWindow, SetFocus, WM_KILLFOCUS, WM_SETFOCUS


GetKBCodePage

Note This function is obsolete. Use the GetOEMCP function to retrieve the OEM code-page identifier for the system.

The GetKBCodePage function returns the current code page.

UINT GetKBCodePage(VOID)

Parameters

This function has no parameters.

Return Values

The return value is an OEM code-page identifier, or it is the default identifier if the registry value is not readable. For a list of OEM code-page identifiers, see GetOEMCP.

See Also

Keyboard Input Overview, Keyboard Input Functions, GetACP, GetOEMCP


GetKeyboardLayout

The GetKeyboardLayout function retrieves the active keyboard layout for a specified thread. If the dwLayout parameter is zero, the layout for the active thread is returned.

HKL GetKeyboardLayout(
  DWORD dwLayout  // thread identifier
);

Parameters

dwLayout
Identifies the thread to query or is zero for the current thread.

Return Values

The return value is the keyboard layout handle for the thread. The low word contains a language identifier for the input language and the high word contains a device handle for the physical layout of the keyboard.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, ActivateKeyboardLayout, CreateThread, LoadKeyboardLayout


GetKeyboardLayoutList

The GetKeyboardLayoutList function retrieves the keyboard layout handles corresponding to the current set of input locales in the system. The function copies the handles to the given buffer.

UINT GetKeyboardLayoutList(
  int nBuff,       // size of buffer in array element
  HKL FAR *lpList  // buffer for keyboard layout handles
);

Parameters

nBuff
Specifies the maximum number of handles that the buffer can hold.
lpList
Pointer to the buffer that receives the array of keyboard layout handles.

Return Values

If the function succeeds, the return value is the number of layout handles copied to the buffer or, if nBuff is zero, the return value is the size, in array elements, of the buffer needed to receive all current layout handles.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, GetKeyboardLayout


GetKeyboardLayoutName

The GetKeyboardLayoutName function retrieves the name of the active keyboard layout.

BOOL GetKeyboardLayoutName(
  LPTSTR pwszKLID   // pointer to buffer for layout name
);

Parameters

pwszKLID
Pointer to the buffer of at least KL_NAMELENGTH characters that is to receive the name of the keyboard layout, including the NULL terminator. This will be a copy of the string provided to the LoadKeyboardLayout function, unless layout substitution took place.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Windows NT: GetKeyboardLayoutName receives the name of the active keyboard layout for the system.

Windows 95: GetKeyboardLayoutName receives the name of the active keyboard layout for the calling thread.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Keyboard Input Overview, Keyboard Input Functions, ActivateKeyboardLayout, LoadKeyboardLayout, UnloadKeyboardLayout


GetKeyboardState

The GetKeyboardState function copies the status of the 256 virtual keys to the specified buffer.

BOOL GetKeyboardState(
  PBYTE lpKeyState   // pointer to array to receive status data
);

Parameters

lpKeyState
Pointer to the 256-byte array that will receive the status data for each virtual key.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

An application can call this function to retrieve the current status of all the virtual keys. The status changes as a thread removes keyboard messages from its message queue. The status does not change as keyboard messages are posted to the thread's message queue, nor does it change as keyboard messages are posted to or retrieved from message queues of other threads. (Exception: Threads that are connected via AttachThreadInput share the same keyboard state.)

When the function returns, each member of the array pointed to by the lpKeyState parameter contains status data for a virtual key. If the high-order bit is 1, the key is down; otherwise, it is up. If the low-order bit is 1, the key is toggled. A key, such as the caps lock key, is toggled if it is turned on. The key is off and untoggled if the low-order bit is 0. A toggle key's indicator light (if any) on the keyboard will be on when the key is toggled, and off when the key is untoggled.

To retrieve status information for an individual key, use the GetKeyState function. To retrieve the current state for an individual key regardless of whether the corresponding keyboard message has been retrieved from the message queue, use the GetAsyncKeyState function

An application can use the virtual-key code constants VK_SHIFT, VK_CONTROL and VK_MENU as indices into the array pointed to by lpKeyState. This gives the status of the shift, ctrl, or alt keys without distinguishing between left and right. An application can also use the following virtual-key code constants as indices to distinguish between the left and right instances of those keys.

VK_LSHIFT | VK_RSHIFT
VK_LCONTROL | VK_RCONTROL
VK_LMENU | VK_RMENU

These left- and right-distinguishing constants are available to an application only through the GetKeyboardState, SetKeyboardState, GetAsyncKeyState, GetKeyState, and MapVirtualKey functions.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, GetKeyState, GetAsyncKeyState, MapVirtualKey, SetKeyboardState


GetKeyNameText

The GetKeyNameText function retrieves a string that represents the name of a key.

int GetKeyNameText(
  LONG lParam,      // second parameter of keyboard message
  LPTSTR lpString,  // pointer to buffer for key name
  int nSize         // maximum length of key-name string length
);

Parameters

lParam
Specifies the second parameter of the keyboard message (such as WM_KEYDOWN) to be processed. The function interprets the following portions of lParam.
Bits | Meaning
16–23 | Scan code.
24 | Extended-key flag. Distinguishes some keys on an enhanced keyboard.
25 | "Don't care" bit. The application calling this function sets this bit to indicate that the function should not distinguish between left and right ctrl and shift keys, for example.

lpString
Pointer to a buffer that will receive the key name.
nSize
Specifies the maximum length, in characters, of the key name, including the terminating null character. (This parameter should be equal to the size of the buffer pointed to by the lpString parameter.)

Return Values

If the function succeeds, a null-terminated string is copied into the specified buffer, and the return value is the length of the string, in characters, not counting the terminating null character.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The format of the key-name string depends on the current keyboard layout. The keyboard driver maintains a list of names in the form of character strings for keys with names longer than a single character. The key name is translated according to the layout of the currently installed keyboard. The name of a character key is the character itself. The names of dead keys are spelled out in full.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Keyboard Input Overview, Keyboard Input Functions


GetKeyState

The GetKeyState function retrieves the status of the specified virtual key. The status specifies whether the key is up, down, or toggled (on, off — alternating each time the key is pressed).

SHORT GetKeyState(
  int nVirtKey   // virtual-key code
);

Parameters

nVirtKey
Specifies a virtual key. If the desired virtual key is a letter or digit (A through Z, a through z, or 0 through 9), nVirtKey must be set to the ASCII value of that character. For other keys, it must be a virtual-key code.

If a non-English keyboard layout is used, virtual keys with values in the range ASCII A through Z and 0 through 9 are used to specify most of the character keys. For example, for the German keyboard layout, the virtual key of value ASCII O (0x4F) refers to the "o" key, whereas VK_OEM_1 refers to the "o with umlaut" key.

Return Values

The return value specifies the status of the given virtual key, as follows:

  • If the high-order bit is 1, the key is down; otherwise, it is up.
  • If the low-order bit is 1, the key is toggled. A key, such as the caps lock key, is toggled if it is turned on. The key is off and untoggled if the low-order bit is 0. A toggle key's indicator light (if any) on the keyboard will be on when the key is toggled, and off when the key is untoggled.

Remarks

The key status returned from this function changes as a given thread reads key messages from its message queue. The status does not reflect the interrupt-level state associated with the hardware. Use the GetAsyncKeyState function to retrieve that information.

An application calls GetKeyState in response to a keyboard-input message. This function retrieves the state of the key when the input message was generated.

To retrieve state information for all the virtual keys, use the GetKeyboardState function.

An application can use the virtual-key code constants VK_SHIFT, VK_CONTROL, and VK_MENU as values for the nVirtKey parameter. This gives the status of the shift, ctrl, or alt keys without distinguishing between left and right. An application can also use the following virtual-key code constants as values for nVirtKey to distinguish between the left and right instances of those keys.

VK_LSHIFT | VK_RSHIFT
VK_LCONTROL | VK_RCONTROL
VK_LMENU | VK_RMENU

These left- and right-distinguishing constants are available to an application only through the GetKeyboardState, SetKeyboardState, GetAsyncKeyState, GetKeyState, and MapVirtualKey functions.

Windows CE: The GetKeyState function can only be used to check the down state of the following virtual keys:

VK_CONTROL

VK_SHIFT

VK_MENU

VK_LCONTROL

VK_LSHIFT

VK_LMENU

VK_RCONTROL

VK_RSHIFT

VK_RMENU

GetKeyState can only be used to check the toggled state of the VK_CAPITAL virtual key.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, GetAsyncKeyState, GetKeyboardState, MapVirtualKey, SetKeyboardState


IsWindowEnabled

The IsWindowEnabled function determines whether the specified window is enabled for mouse and keyboard input.

BOOL IsWindowEnabled(
  HWND hWnd   // handle to window to test
);

Parameters

hWnd
Handle to the window to test.

Return Values

If the window is enabled, the return value is nonzero.

If the window is not enabled, the return value is zero.

Remarks

A child window receives input only if it is both enabled and visible.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, EnableWindow, IsWindowVisible


keybd_event

The keybd_event function synthesizes a keystroke. The system can use such a synthesized keystroke to generate a WM_KEYUP or WM_KEYDOWN message. The keyboard driver's interrupt handler calls the keybd_event function.

Windows NT: This function has been superseded. Use SendInput instead.

VOID keybd_event(
  BYTE bVk,           // virtual-key code
  BYTE bScan,         // hardware scan code
  DWORD dwFlags,      // flags specifying various function options
  DWORD dwExtraInfo   // additional data associated with keystroke
);

Parameters

bVk
Specifies a virtual-key code. The code must be a value in the range 1 to 254.
bScan
Specifies a hardware scan code for the key.
dwFlags
A set of flag bits that specify various aspects of function operation. An application can use any combination of the following predefined constant values to set the flags.
Value | Meaning
KEYEVENTF_EXTENDEDKEY | If specified, the scan code was preceded by a prefix byte having the value 0xE0 (224).
KEYEVENTF_KEYUP | If specified, the key is being released. If not specified, the key is being depressed.

dwExtraInfo
Specifies an additional 32-bit value associated with the key stroke.

Return Values

This function has no return value.

Remarks

Although keybd_event passes an OEM-dependent hardware scan code to the system, applications should not use the scan code. The system converts scan codes to virtual-key codes internally and clears the up/down bit in the scan code before passing it to applications.

An application can simulate a press of the PRINTSCREEN key in order to obtain a screen snapshot and save it to the clipboard. To do this, call keybd_event with the bVk parameter set to VK_SNAPSHOT, and the bScan parameter set to 0 for a snapshot of the full screen or set bScan to 1 for a snapshot of the active window.

Windows CE: Windows CE supports an additional flag for the dwFlags parameter. Use the KEYEVENTF_SILENT flag to simulate a keystroke without making a clicking sound.

Windows CE does not support the KEYEVENTF_EXTENDEDKEY flag.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, GetAsyncKeyState, GetKeyState, MapVirtualKey, SetKeyboardState


LoadKeyboardLayout

The LoadKeyboardLayout function loads a new keyboard layout into the system. Several keyboard layouts can be loaded at a time, but only one per process is active at a time. Loading multiple keyboard layouts makes it possible to rapidly switch between layouts.

HKL LoadKeyboardLayout(
  LPCTSTR pwszKLID,  // name of layout to load
  UINT Flags         // keyboard layout flags
);

Parameters

pwszKLID
Pointer to the buffer that specifies the name of the keyboard layout to load. This name is a string composed of the hexadecimal value of the language identifier (low word) and a device identifier (high word). For example, U.S. English has a language identifier of 0x0409, so the primary U.S. English layout is named "00000409". Variants of U.S. English layout (such as the Dvorak layout) are named "00010409", "00020409", and so on.
Flags
Specifies how the keyboard layout is to be loaded. This parameter can be one of the following values.
Value | Meaning
KLF_ACTIVATE | If the specified layout is not already loaded, the function loads and activates the layout for the current thread.
KLF_NOTELLSHELL | Prevents a ShellProc hook procedure from receiving an HSHELL_LANGUAGE hook code when the new layout is loaded. This value is typically used when an application loads multiple layouts one after another. Applying this value to all but the last layout delays the shell's processing until all layouts have been added.
KLF_REORDER | Moves the specified layout to the head of the keyboard layouts list, making that layout the active layout for the current thread. This value reorders the keyboard layouts list even if KLF_ACTIVATE is not provided.
KLF_REPLACELANG | Windows NT 4.0, Windows 95, and later: If the new layout has the same language identifier as a current layout, the new layout replaces the current one as the layout for that language. If this value is not provided and the layouts have the same language identifiers, the current layout is not replaced and the function returns NULL.
KLF_SUBSTITUTE_OK | Substitutes the specified keyboard layout with another layout preferred by the user. The system starts with this flag set, and it is recommended that your application always use this flag. The substitution occurs only if the registry key HKEY_CURRENT_USER\Keyboard Layout\Substitutes explicitly defines a substitution layout. For example, if the key includes the value name "00000409" with value "00010409", loading the U.S. English layout ("00000409") causes the Dvorak U.S. English layout ("00010409") to be loaded instead. The system uses KLF_SUBSTITUTE_OK when booting, and it is recommended that all applications use this value when loading layouts to ensure that the user's preference is selected.
KLF_SETFORPROCESS | Windows NT 5.0 and later:: This flag is valid only with KLF_ACTIVATE. Activates the specified keyboard layout for the entire process and sends the WM_INPUTLANGCHANGE message to all threads in the current process. Typically, LoadKeyboardLayout activates a layout only for the current thread.
KLF_UNLOADPREVIOUS | Unsupported in Windows NT 5.0, Windows 95, and Windows 98: This flag is only valid with KLF_ACTIVATE. Unloads the previous layout only if loading and activating the specified layout succeeds. It is recommended that your application use the UnloadKeyboardLayout function instead.

Return Values

If the function succeeds, the return value is the keyboard layout handle to the layout matched with the requested name. If no matching keyboard layout is available, the return value is NULL. To get extended error information, call GetLastError.

Remarks

An application can and will typically load the default layout or IME for a language and can do so by specifying only a string version of the language identifier. If an application wants to load a specific layout or IME, it should read the registry to determine the specific layout identifier to pass to LoadKeyboardLayout. In this case, a request to activate the default keyboard layout handle for a locale will activate the first matching one. A specific IME should be activated using an explicit keyboard layout handle returned from GetKeyboardLayout, GetKeyboardLayoutList, or LoadKeyboardLayout.

Windows 95 and Windows 98: If a layout is to be loaded with the same language as a previously loaded layout and the KLF_REPLACELANG flag is not set, the call fails. Only one loaded layout may be associated with a given language. (It is acceptable for multiple IMEs to be loaded with associations to the same language.)

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Keyboard Input Overview, Keyboard Input Functions, ActivateKeyboardLayout, GetKeyboardLayoutName, MAKELANGID, UnloadKeyboardLayout


MapVirtualKey

The MapVirtualKey function translates (maps) a virtual-key code into a scan code or character value, or translates a scan code into a virtual-key code.

UINT MapVirtualKey(
  UINT uCode,     // virtual-key code or scan code
  UINT uMapType   // translation to perform
);

Parameters

uCode
Specifies the virtual-key code or scan code for a key. How this value is interpreted depends on the value of the uMapType parameter.
uMapType
Specifies the translation to perform. The value of this parameter depends on the value of the uCode parameter:
Value | Meaning
0 | uCode is a virtual-key code and is translated into a scan code. If it is a virtual-key code that does not distinguish between left- and right-hand keys, the left-hand scan code is returned. If there is no translation, the function returns 0.
1 | uCode is a scan code and is translated into a virtual-key code that does not distinguish between left- and right-hand keys. If there is no translation, the function returns 0.
2 | uCode is a virtual-key code and is translated into an unshifted character value in the low-order word of the return value. Dead keys (diacritics) are indicated by setting the top bit of the return value. If there is no translation, the function returns 0.
3 | uCode is a scan code and is translated into a virtual-key code that distinguishes between left- and right-hand keys. If there is no translation, the function returns 0.

Return Values

The return value is either a scan code, a virtual-key code, or a character value, depending on the value of uCode and uMapType. If there is no translation, the return value is zero.

Remarks

An application can use MapVirtualKey to translate scan codes to the virtual-key code constants VK_SHIFT, VK_CONTROL, and VK_MENU, and vice versa. These translations do not distinguish between the left and right instances of the shift, ctrl, or alt keys. An application can get the scan code corresponding to the left or right instance of one of these keys by calling MapVirtualKey with uCode set to one of the following virtual-key code constants.

VK_LSHIFT | VK_RSHIFT
VK_LCONTROL | VK_RCONTROL
VK_LMENU | VK_RMENU

These left- and right-distinguishing constants are available to an application only through the GetKeyboardState, SetKeyboardState, GetAsyncKeyState, GetKeyState, and MapVirtualKey functions.

Windows CE: Windows CE supports only a value of 2 for the uMapType parameter – mapping from virtual keys to unshifted characters.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Keyboard Input Overview, Keyboard Input Functions, GetAsyncKeyState, GetKeyboardState, GetKeyState, SetKeyboardState


MapVirtualKeyEx

The MapVirtualKeyEx function translates (maps) a virtual-key code into a scan code or character value, or translates a scan code into a virtual-key code. The function translates the codes using the input language and physical keyboard layout identified by the given keyboard layout handle.

UINT MapVirtualKeyEx(
  UINT uCode,     // virtual-key code or scan code
  UINT uMapType,  // translation to perform
  HKL dwhkl       // keyboard layout handle
);

Parameters

uCode
Specifies the virtual-key code or scan code for a key. How this value is interpreted depends on the value of the uMapType parameter.
uMapType
Specifies the translation to perform. The value of this parameter depends on the value of the uCode parameter:
Value | Meaning
0 | uCode is a virtual-key code and is translated into a scan code. If it is a virtual-key code that does not distinguish between left- and right-hand keys, the left-hand scan code is returned. If there is no translation, the function returns 0.
1 | uCode is a scan code and is translated into a virtual-key code that does not distinguish between left- and right-hand keys. If there is no translation, the function returns 0.
2 | uCode is a virtual-key code and is translated into an unshifted character value in the low order word of the return value. Dead keys (diacritics) are indicated by setting the top bit of the return value. If there is no translation, the function returns 0.
3 | uCode is a scan code and is translated into a virtual-key code that distinguishes between left- and right-hand keys. If there is no translation, the function returns 0.

dwhkl
Handle to the keyboard layout to use for translating the given code. This parameter can be any keyboard layout handle previously returned by the LoadKeyboardLayout function.

Return Values

The return value is either a scan code, a virtual-key code, or a character value, depending on the value of uCode and uMapType. If there is no translation, the return value is zero.

Remarks

An application can use MapVirtualKeyEx to translate scan codes to the virtual-key code constants VK_SHIFT, VK_CONTROL, and VK_MENU, and vice versa. These translations do not distinguish between the left and right instances of the shift, ctrl, or alt keys. An application can get the scan code corresponding to the left or right instance of one of these keys by calling MapVirtualKeyEx with uCode set to one of the following virtual-key code constants.

VK_LSHIFT | VK_RSHIFT
VK_LCONTROL | VK_RCONTROL
VK_LMENU | VK_RMENU

These left- and right-distinguishing constants are available to an application only through the GetKeyboardState, SetKeyboardState, GetAsyncKeyState, GetKeyState, MapVirtualKey, and MapVirtualKeyEx functions. For list complete table of virtual key codes, see Virtual-Key Codes.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Keyboard Input Overview, Keyboard Input Functions, GetAsyncKeyState, GetKeyboardState, GetKeyState, LoadKeyboardLayout, MapVirtualKey, SetKeyboardState


OemKeyScan

The OemKeyScan function maps OEM ASCII codes 0 through 0x0FF into the OEM scan codes and shift states. The function provides information that allows a program to send OEM text to another program by simulating keyboard input.

DWORD OemKeyScan(
  WORD wOemChar   // ASCII value of OEM character
);

Parameters

wOemChar
Specifies the ASCII value of the OEM character.

Return Values

The low-order word of the return value contains the scan code of the given OEM character, and the high-order word contains the shift state, which can be a combination of the following flag bits.

Bit | Meaning
1 | Either shift key is pressed.
2 | Either ctrl key is pressed.
4 | Either alt key is pressed.
8 | The Hankaku key is pressed
16 | Reserved (defined by the keyboard layout driver).
32 | Reserved (defined by the keyboard layout driver).

If the character cannot be produced by a single keystroke using the current keyboard layout, the return value is 0xFFFFFFFF.

Remarks

This function does not provide translations for characters that require ctrl+alt or dead keys. Characters not translated by this function must be copied by simulating input using the alt+ keypad mechanism. The numlock key must be off.

This function does not provide translations for characters that cannot be typed with one keystroke using the current keyboard layout, such as characters with diacritics requiring dead keys. Characters not translated by this function may be simulated using the alt+ keypad mechanism. The numlock key must be on.

This function is implemented using the VkKeyScan function.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, VkKeyScan


RegisterHotKey

The RegisterHotKey function defines a system-wide hot key.

BOOL RegisterHotKey(
  HWND hWnd,         // window to receive hot-key notification
  int id,            // identifier of hot key
  UINT fsModifiers,  // key-modifier flags
  UINT vk            // virtual-key code
);

Parameters

hWnd
Handle to the window that will receive WM_HOTKEY messages generated by the hot key. If this parameter is NULL, WM_HOTKEY messages are posted to the message queue of the calling thread and must be processed in the message loop.
id
Specifies the identifier of the hot key. No other hot key in the calling thread should have the same identifier. An application must specify a value in the range 0x0000 through 0xBFFF. A shared dynamic-link library (DLL) must specify a value in the range 0xC000 through 0xFFFF (the range returned by the GlobalAddAtom function). To avoid conflicts with hot-key identifiers defined by other shared DLLs, a DLL should use the GlobalAddAtom function to obtain the hot-key identifier.
fsModifiers
Specifies keys that must be pressed in combination with the key specified by the nVirtKey parameter in order to generate the WM_HOTKEY message. The fsModifiers parameter can be a combination of the following values.
Value | Meaning
MOD_ALT | Either alt key must be held down.
MOD_CONTROL | Either ctrl key must be held down.
MOD_SHIFT | Either shift key must be held down.
MOD_WIN | Either WINDOWS key was held down. These keys are labeled with the Microsoft Windows logo.

vk
Specifies the virtual-key code of the hot key.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

When a key is pressed, the system looks for a match against all hot keys. Upon finding a match, the system posts the WM_HOTKEY message to the message queue of the thread that registered the hot key. This message is posted to the beginning of the queue so it is removed by the next iteration of the message loop.

This function cannot associate a hot key with a window created by another thread.

RegisterHotKey fails if the keystrokes specified for the hot key have already been registered by another hot key.

If the window identified by the hWnd parameter already registered a hot key with the same identifier as that specified by the id parameter, the new values for the fsModifiers and vk parameters replace the previously specified values for these parameters.

Windows CE: Windows CE versions 2.0 and later support an additional flag, called MOD_KEYUP, for the fsModifiers parameter. If you set the MOD_KEYUP flag, the window will be sent a WM_HOTKEY message on a key up event as well as on a key down event.

RegisterHotKey can be used to register hot keys across threads.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, GlobalAddAtom, UnregisterHotKey, WM_HOTKEY


SendInput

The SendInput function synthesizes keystrokes, mouse motions, and button clicks.

UINT SendInput(
  UINT nInputs,     // count of input events
  LPINPUT pInputs,  // array of input events to insert
  int cbSize        // size of an INPUT structure
);

Parameters

nInputs
Specifies how many structures pInputs points to.
pInputs
Pointer to an array of INPUT structures. Each structure represents an event to be inserted into the keyboard or mouse input stream.
cbSize
Specifies the size of an INPUT structure. If cbSize is not the size of an INPUT structure, the function will fail.

Return Values

The function returns the number of events that it successfully inserted into the keyboard or mouse input stream.

To get extended error information, call GetLastError.

Remarks

The SendInput function inserts the events in the INPUT structures serially into the keyboard or mouse input stream. These events aren't interspersed with other keyboard or mouse input events inserted either by the user (with the keyboard or mouse) or by calls to keybd_event, mouse_event, or other calls to SendInput.

Windows CE: Windows CE does not support the INPUT_HARDWARE value in the type field of the INPUT structure referred to by the pInputs parameter.

QuickInfo

Windows NT: Requires version 4.0 SP3 or later.
Windows: Requires Windows 98 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, INPUT, keybd_event, mouse_event


SetActiveWindow

The SetActiveWindow function activates a window. The window must be associated with the calling thread's message queue.

HWND SetActiveWindow(
  HWND hWnd   // handle to window to activate
);

Parameters

hWnd
Handle to the top-level window to be activated.

Return Values

If the function succeeds, the return value is the handle to the window that was previously active.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The SetActiveWindow function activates a window, but not if the application is in the background. The window will be brought into the foreground (top of Z order) if the application is in the foreground when it sets the activation.

If the window identified by the hWnd parameter was created by the calling thread, the active window status of the calling thread is set to hWnd. Otherwise, the active window status of the calling thread is set to NULL.

The SetForegroundWindow window function, on the other hand, activates a window and forces it into the foreground. An application should only call SetForegroundWindow if it needs to display critical errors or information that needs the user's immediate attention .

By using the AttachThreadInput function, a thread can attach its input processing to another thread. This allows a thread to call SetActiveWindow to activate a window associated with another thread's message queue.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, GetActiveWindow, SetForegroundWindow, WM_ACTIVATE


SetFocus

The SetFocus function sets the keyboard focus to the specified window. The window must be associated with the calling thread's message queue.

HWND SetFocus(
  HWND hWnd   // handle to window to receive focus
);

Parameters

hWnd
Handle to the window that will receive the keyboard input. If this parameter is NULL, keystrokes are ignored.

Return Values

If the function succeeds, the return value is the handle to the window that previously had the keyboard focus. If the hWnd parameter is invalid or the window is not associated with the calling thread's message queue, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The SetFocus function sends a WM_KILLFOCUS message to the window that loses the keyboard focus and a WM_SETFOCUS message to the window that receives the keyboard focus. It also activates either the window that receives the focus or the parent of the window that receives the focus.

If a window is active but does not have the focus, any key pressed will produce the WM_SYSCHAR, WM_SYSKEYDOWN, or WM_SYSKEYUP message. If the VK_MENU key is also pressed, the lParam parameter of the message will have bit 30 set. Otherwise, the messages produced do not have this bit set.

By using the AttachThreadInput function, a thread can attach its input processing to another thread. This allows a thread to call SetFocus to set the keyboard focus to a window associated with another thread's message queue.

Windows CE: Do not use the SetFocus function to set the keyboard focus to a window associated with another thread's message queue. There is one exception. If a window on one thread is the child of the window on the other thread, or if the windows are siblings of the same parent, the thread associated with one window can set the focus to the other window even though it belongs to a different thread. In this case, there is no need to call AttachThreadInput first.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, AttachThreadInput, GetFocus, WM_KILLFOCUS, WM_SETFOCUS, WM_SYSCHAR, WM_SYSKEYDOWN, WM_SYSKEYUP


SetKeyboardState

The SetKeyboardState function copies a 256-byte array of keyboard key states into the calling thread's keyboard-input state table. This is the same table accessed by the GetKeyboardState and GetKeyState functions. Changes made to this table do not affect keyboard input to any other thread.

BOOL SetKeyboardState(
  LPBYTE lpKeyState   // array with virtual-key codes
);

Parameters

lpKeyState
Pointer to a 256-byte array that contains keyboard key states.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Because the SetKeyboardState function alters the input state of the calling thread and not the global input state of the system, an application cannot use SetKeyboardState to set the num lock, caps lock, or scroll lock indicator lights on the keyboard.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, GetAsyncKeyState, GetKeyboardState, GetKeyState, MapVirtualKey


ToAscii

The ToAscii function translates the specified virtual-key code and keyboard state to the corresponding character or characters. The function translates the code using the input language and physical keyboard layout identified by the given keyboard layout handle.

int ToAscii(
  UINT uVirtKey,     // virtual-key code
  UINT uScanCode,    // scan code
  PBYTE lpKeyState,  // key-state array
  LPWORD lpChar,     // buffer for translated key
  UINT uFlags        // active-menu flag
);

Parameters

uVirtKey
Specifies the virtual-key code to be translated.
uScanCode
Specifies the hardware scan code of the key to be translated. The high-order bit of this value is set if the key is up (not pressed).
lpKeyState
Pointer to a 256-byte array that contains the current keyboard state. Each element (byte) in the array contains the state of one key. If the high-order bit of a byte is set, the key is down (pressed).

The low bit, if set, indicates that the key is toggled on. In this function, only the toggle bit of the caps lock key is relevant. The toggle state of the num lock and scroll lock keys is ignored.

lpChar
Pointer to the buffer that will receive the translated character or characters.
uFlags
Specifies whether a menu is active. This parameter must be 1 if a menu is active, or 0 otherwise.

Return Values

If the specified key is a dead key, the return value is negative. Otherwise, it is one of the following values.

Value | Meaning
0 | The specified virtual key has no translation for the current state of the keyboard.
1 | One character was copied to the buffer.
2 | Two characters were copied to the buffer. This usually happens when a dead-key character (accent or diacritic) stored in the keyboard layout cannot be composed with the specified virtual key to form a single character.

Remarks

The parameters supplied to the ToAscii function might not be sufficient to translate the virtual-key code, because a previous dead key is stored in the keyboard layout.

Typically, ToAscii performs the translation based on the virtual-key code. In some cases, however, bit 15 of the uScanCode parameter may be used to distinguish between a key press and a key release. The scan code is used for translating ALT+number key combinations.

Although num lock is a toggle key that affects keyboard behavior, ToAscii ignores the toggle setting (the low bit) of lpKeyState (VK_NUMLOCK, because the uVirtKey parameter alone is sufficient to distinguish the cursor movement keys (VK_HOME, VK_INSERT, and so on) from the numeric keys (VK_DECIMAL, VK_NUMPAD0 - VK_NUMPAD9).

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, OemKeyScan, ToUnicode, VkKeyScan


ToAsciiEx

The ToAsciiEx function translates the specified virtual-key code and keyboard state to the corresponding character or characters. The function translates the code using the input language and physical keyboard layout identified by the given keyboard layout handle.

int ToAsciiEx(
  UINT uVirtKey,     // virtual-key code
  UINT uScanCode,    // scan code
  PBYTE lpKeyState,  // key-state array
  LPWORD lpChar,     // buffer for translated key
  UINT uFlags,       // active-menu flag
  HKL dwhkl          // keyboard layout handle
);

Parameters

uVirtKey
Specifies the virtual-key code to be translated.
uScanCode
Specifies the hardware scan code of the key to be translated. The high-order bit of this value is set if the key is up (not pressed).
lpKeyState
Pointer to a 256-byte array that contains the current keyboard state. Each element (byte) in the array contains the state of one key. If the high-order bit of a byte is set, the key is down (pressed).

The low bit, if set, indicates that the key is toggled on. In this function, only the toggle bit of the caps lock key is relevant. The toggle state of the num lock and scroll lock keys is ignored.

lpChar
Pointer to the buffer that will receive the translated character or characters.
uFlags
Specifies whether a menu is active. This parameter must be 1 if a menu is active, zero otherwise.
dwhkl
Handle to the keyboard layout to use to translate the given code. This parameter can be any keyboard layout handle previously returned by the LoadKeyboardLayout function.

Return Values

If the specified key is a dead key, the return value is negative. Otherwise, it is one of the following values.

Value | Meaning
0 | The specified virtual key has no translation for the current state of the keyboard.
1 | One character was copied to the buffer.
2 | Two characters were copied to the buffer. This usually happens when a dead-key character (accent or diacritic) stored in the keyboard layout cannot be composed with the specified virtual key to form a single character.

Remarks

The parameters supplied to the ToAsciiEx function might not be sufficient to translate the virtual-key code, because a previous dead key is stored in the keyboard layout.

Typically, ToAsciiEx performs the translation based on the virtual-key code. In some cases, however, bit 15 of the uScanCode parameter may be used to distinguish between a key press and a key release. The scan code is used for translating ALT+number key combinations.

Although num lock is a toggle key that affects keyboard behavior, ToAsciiEx ignores the toggle setting (the low bit) of lpKeyState (VK_NUMLOCK, because the uVirtKey parameter alone is sufficient to distinguish the cursor movement keys (VK_HOME, VK_INSERT, and so on) from the numeric keys (VK_DECIMAL, VK_NUMPAD0 - VK_NUMPAD9).

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, LoadKeyboardLayout, MapVirtualKeyEx, OemKeyScan, ToAscii, VkKeyScan


ToUnicode

The ToUnicode function translates the specified virtual-key code and keyboard state to the corresponding Unicode character or characters.

int ToUnicode(
  UINT wVirtKey,    // virtual-key code
  UINT wScanCode,   // scan code
  PBYTE lpKeyState, // address of key-state array
  LPWSTR pwszBuff,  // buffer for translated key
  int cchBuff,      // size of translated key buffer
  UINT wFlags       // set of function-conditioning flags
);

Parameters

wVirtKey
Specifies the virtual-key code to be translated.
wScanCode
Specifies the hardware scan code of the key to be translated. The high-order bit of this value is set if the key is up.
lpKeyState
Pointer to a 256-byte array that contains the current keyboard state. Each element (byte) in the array contains the state of one key. If the high-order bit of a byte is set, the key is down.
pwszBuff
Pointer to the buffer that receives the translated Unicode character or characters.
cchBuff
Specifies the size in characters of the buffer pointed to by the pwszBuff parameter.
wFlags
A set of bit flags that condition the behavior of the function. Set bit 0 if a menu is active. Bits 1 through 31 are reserved.

Return Values

The function returns one of the following values.

Value | Meaning
– 1 | The specified virtual key is a dead-key character (accent or diacritic). This value is returned regardless of the keyboard layout, even if several characters have been typed and are stored in the keyboard state. If possible, even with Unicode keyboard layouts, the function has written a spacing version of the dead-key character to the buffer specified by pwszBuffer. For example, the function writes the character SPACING ACUTE (0x00B4), rather than the character NON_SPACING ACUTE (0x0301).
0 | The specified virtual key has no translation for the current state of the keyboard. Nothing was written to the buffer specified by pwszBuffer.
1 | One character was written to the buffer specified by pwszBuffer.
2 or more | Two or more characters were written to the buffer specified by pwszBuff. The most common cause for this is that a dead-key character (accent or diacritic) stored in the keyboard layout could not be combined with the specified virtual key to form a single character.

Remarks

The parameters supplied to the ToUnicode function might not be sufficient to translate the virtual-key code because a previous dead key is stored in the keyboard layout.

Typically, ToUnicode performs the translation based on the virtual-key code. In some cases, however, bit 15 of the wScanCode parameter can be used to distinguish between a key press and a key release.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Unsupported.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, ToAscii, VkKeyScan


ToUnicodeEx

The ToUnicodeEx function translates the specified virtual-key code and keyboard state to the corresponding Unicode character or characters.

int ToUnicodeEx(
  UINT wVirtKey,    // virtual-key code
  UINT wScanCode,   // scan code
  PBYTE lpKeyState, // key-state array
  LPWSTR pwszBuff,  // buffer for translated key
  int cchBuff,      // size of translated key buffer
  UINT wFlags,      // set of function-conditioning flags
  HKL dwhkl         // keyboard layout handle
);

Parameters

wVirtKey
Specifies the virtual-key code to be translated.
wScanCode
Specifies the hardware scan code of the key to be translated. The high-order bit of this value is set if the key is up.
lpKeyState
Pointer to a 256-byte array that contains the current keyboard state. Each element (byte) in the array contains the state of one key. If the high-order bit of a byte is set, the key is down.
pwszBuff
Pointer to the buffer that receives the translated Unicode character or characters.
cchBuff
Specifies the size in characters of the buffer pointed to by the pwszBuff parameter.
wFlags
A set of bit flags that condition the behavior of the function. Set bit 0 if a menu is active. Bits 1 through 31 are reserved.
dwhkl
Handle to the keyboard layout to use to translate the given code. This parameter can be any keyboard layout handle previously returned by the LoadKeyboardLayout function.

Return Values

The function returns one of the following values.

Value | Meaning
– 1 | The specified virtual key is a dead-key character (accent or diacritic). This value is returned regardless of the keyboard layout, even if several characters have been typed and are stored in the keyboard state. If possible, even with Unicode keyboard layouts, the function has written a spacing version of the dead-key character to the buffer specified by pwszBuffer. For example, the function writes the character SPACING ACUTE (0x00B4), rather than the character NON_SPACING ACUTE (0x0301).
0 | The specified virtual key has no translation for the current state of the keyboard. Nothing was written to the buffer specified by pwszBuffer.
1 | One character was written to the buffer specified by pwszBuffer.
2 or more | Two or more characters were written to the buffer specified by pwszBuff. The most common cause for this is that a dead-key character (accent or diacritic) stored in the keyboard layout could not be combined with the specified virtual key to form a single character.

Remarks

The parameters supplied to the ToUnicodeEx function might not be sufficient to translate the virtual-key code because a previous dead key is stored in the keyboard layout.

Typically, ToUnicodeEx performs the translation based on the virtual-key code. In some cases, however, bit 15 of the wScanCode parameter can be used to distinguish between a key press and a key release.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Unsupported.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, ToAscii, ToUnicode, VkKeyScan


UnloadKeyboardLayout

The UnloadKeyboardLayout function removes a keyboard layout.

BOOL UnloadKeyboardLayout(
  HKL hkl   // handle to keyboard layout
);

Parameters

hkl
Handle to the keyboard layout to unload.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. The function can fail for the following reasons:

  • An invalid keyboard layout handle was passed.
  • The layout was preloaded.
  • The layout is in use.

To get extended error information, call GetLastError.

Remarks

Windows 95: UnloadKeyboardLayout cannot unload the system default keyboard layout. This ensures that an appropriate character set is always available for the user to type commands for the shell or names for the file system.

Windows NT: UnloadKeyboardLayout can unload the system default keyboard layout.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, ActivateKeyboardLayout, GetKeyboardLayoutName, LoadKeyboardLayout


UnregisterHotKey

The UnregisterHotKey function frees a hot key previously registered by the calling thread.

BOOL UnregisterHotKey(
  HWND hWnd,  // window associated with hot key
  int id      // identifier of hot key
);

Parameters

hWnd
Handle to the window associated with the hot key to be freed. This parameter should be NULL if the hot key is not associated with a window.
id
Specifies the identifier of the hot key to be freed.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, RegisterHotKey, WM_HOTKEY


VkKeyScan

The VkKeyScan function translates a character to the corresponding virtual-key code and shift state for the current keyboard.

This function has been superseded by the VkKeyScanEx function. You can still use VkKeyScan, however, if you do not need to specify a keyboard layout.

SHORT VkKeyScan(
  TCHAR ch   // character to translate
);

Parameters

ch
Specifies the character to be translated into a virtual-key code.

Return Values

If the function succeeds, the low-order byte of the return value contains the virtual-key code and the high-order byte contains the shift state, which can be a combination of the following flag bits.

Bit |  | Meaning
1 |  | Either shift key is pressed.
2 |  | Either CTRL key is pressed.
4 |  | Either ALT key is pressed.
8 | The Hankaku key is pressed
16 | Reserved (defined by the keyboard layout driver).
32 | Reserved (defined by the keyboard layout driver).

If the function finds no key that translates to the passed character code, both the low-order and high-order bytes contain –1.

Remarks

For keyboard layouts that use the right-hand alt key as a shift key (for example, the French keyboard layout), the shift state is represented by the value 6, because the right-hand alt key is converted internally into ctrl+alt.

Translations for the numeric keypad (VK_NUMPAD0 through VK_DIVIDE) are ignored. This function is intended to translate characters into keystrokes from the main keyboard section only. For example, the character "7" is translated into VK_7, not VK_NUMPAD7.

VkKeyScan is used by applications that send characters by using the WM_KEYUP and WM_KEYDOWN messages.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Keyboard Input Overview, Keyboard Input Functions, GetAsyncKeyState, GetKeyboardState, GetKeyNameText, GetKeyState, SetKeyboardState, VkKeyScanEx, WM_KEYDOWN, WM_KEYUP


VkKeyScanEx

The VkKeyScanEx function translates a character to the corresponding virtual-key code and shift state. The function translates the character using the input language and physical keyboard layout identified by the given keyboard layout handle.

SHORT VkKeyScanEx(
  TCHAR ch,  // character to translate
  HKL dwhkl  // keyboard layout handle
);

Parameters

ch
Specifies the character to be translated into a virtual-key code.
dwhkl
Handle to the keyboard layout to use to translate the character. This parameter can be any keyboard layout handle previously returned by the LoadKeyboardLayout function.

Return Values

If the function succeeds, the low-order byte of the return value contains the virtual-key code and the high-order byte contains the shift state, which can be a combination of the following flag bits.

Bit |  | Meaning
1 |  | Either shift key is pressed.
2 |  | Either CTRL key is pressed.
4 |  | Either ALT key is pressed.
8 | The Hankaku key is pressed
16 | Reserved (defined by the keyboard layout driver).
32 | Reserved (defined by the keyboard layout driver).

If the function finds no key that translates to the passed character code, both the low-order and high-order bytes contain –1.

Remarks

For keyboard layouts that use the right-hand alt key as a shift key (for example, the French keyboard layout), the shift state is represented by the value 6, because the right-hand alt key is converted internally into ctrl+alt.

Translations for the numeric keypad (VK_NUMPAD0 through VK_DIVIDE) are ignored. This function is intended to translate characters into keystrokes from the main keyboard section only. For example, the character "7" is translated into VK_7, not VK_NUMPAD7.

VkKeyScanEx is used by applications that send characters by using the WM_KEYUP and WM_KEYDOWN messages.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Keyboard Input Overview, Keyboard Input Functions, GetAsyncKeyState, GetKeyboardState, GetKeyNameText, GetKeyState, LoadKeyboardLayout, SetKeyboardState, ToAsciiEx


Keyboard Input Structures

The following structure is used to receive and process keyboard input.

INPUT


INPUT

The INPUT structure is used by SendInput to synthesize keystrokes, mouse motions, and button clicks.

typedef struct tagINPUT {
    DWORD   type;
    union
    {
        MOUSEINPUT      mi;
        KEYBDINPUT      ki;
        HARDWAREINPUT   hi;
    };
} INPUT, *PINPUT, FAR* LPINPUT;

Members

type
Specifies the type of the input event. It can be one of the following values.
Value | Meaning
INPUT_MOUSE | The event is a mouse event. Use the mi structure of the union.
INPUT_KEYBOARD | The event is a keyboard event. Use the ki structure of the union.
INPUT_HARDWARE | Windows 95: The event is from input hardware other than a keyboard or mouse. Use the hi structure of the union.

mi
Specifies a mouse event.
typedef struct tagMOUSEINPUT {
    LONG    dx;
    LONG    dy;
    DWORD   mouseData;
    DWORD   dwFlags;
    DWORD   time;
    DWORD   dwExtraInfo;
} MOUSEINPUT, *PMOUSEINPUT, FAR* LPMOUSEINPUT;
dx, dy
Specifies the mouse's absolute position or its amount of motion since the last mouse event was generated, depending on the setting of MOUSEEVENTF_ABSOLUTE in dwFlags. Absolute data is given as the mouse's actual x- and y-coordinates; relative data is given as the number of pixels moved.
mouseData
If dwFlags contains MOUSEEVENTF_WHEEL, then mouseData specifies the amount of wheel movement. A positive value indicates that the wheel was rotated forward, away from the user; a negative value indicates that the wheel was rotated backward, toward the user. One wheel click is defined as WHEEL_DELTA, which is 120.

If dwFlags does not contain MOUSEEVENTF_WHEEL, then mouseData should be zero.

dwFlags
A set of bit flags that specify various aspects of mouse motion and button clicks. The bits in this member can be any reasonable combination of the following values.
Value | Meaning
MOUSEEVENTF_ABSOLUTE | Specifies that the dx and dy members contain normalized absolute coordinates. If the flag is not set, the dx and dy members contain relative data: the change in position since the last reported position. This flag can be set, or not set, regardless of what kind of mouse or other pointing device, if any, is connected to the system. For further information about relative mouse motion, see the following Remarks section.
MOUSEEVENTF_MOVE | Specifies that movement occurred.
MOUSEEVENTF_LEFTDOWN | Specifies that the left button was pressed.
MOUSEEVENTF_LEFTUP | Specifies that the left button was released.
MOUSEEVENTF_RIGHTDOWN | Specifies that the right button was pressed.
MOUSEEVENTF_RIGHTUP | Specifies that the right button was released.
MOUSEEVENTF_MIDDLEDOWN | Specifies that the middle button was pressed.
MOUSEEVENTF_MIDDLEUP | Specifies that the middle button was released.
MOUSEEVENTF_WHEEL | Windows NT: Specifies that the wheel was moved, if the mouse has a wheel. The amount of movement is specified in mouseData.

The bit flags that specify mouse button status are set to indicate changes in status, not ongoing conditions. For example, if the left mouse button is pressed and held down, MOUSEEVENTF_LEFTDOWN is set when the left button is first pressed, but not for subsequent motions. Similarly, MOUSEEVENTF_LEFTUP is set only when the button is first released.

time
Time stamp for the event.
dwExtraInfo
Specifies an additional 32-bit value associated with the mouse event. An application calls GetMessageExtraInfo to obtain this extra information.
ki
Specifies a keyboard event.
typedef struct tagKEYBDINPUT {
    WORD    wVk;
    WORD    wScan;
    DWORD   dwFlags;
    DWORD   time;
    DWORD   dwExtraInfo;
} KEYBDINPUT, *PKEYBDINPUT, FAR* LPKEYBDINPUT;
wVk
Specifies a virtual-key code. The code must be a value in the range 1 to 254.
wScan
Specifies a hardware scan code for the key.
dwFlags
A set of bit flags that specify various aspects of a keystroke. The bits in this member can be any combination of the following predefined constant values.
Value | Meaning
KEYEVENTF_EXTENDEDKEY | If specified, the scan code was preceded by a prefix byte that has the value 0xE0 (224).
KEYEVENTF_KEYUP | If specified, the key is being released. If not specified, the key is being pressed.

time
Time stamp for the event.
dwExtraInfo
Specifies an additional 32-bit value associated with the keystroke. An application calls GetMessageExtraInfo to obtain this extra information.
hi
Windows 95: Specifies an event from input hardware other than a keyboard or mouse.
typedef struct tagHARDWAREINPUT {
    DWORD   uMsg;
    WORD    wParamL;
    WORD    wParamH;
    DWORD   dwExtraInfo;
} HARDWAREINPUT, *PHARDWAREINPUT, FAR* LPHARDWAREINPUT;
uMsg
The message generated by the input hardware.
wParamL
Parameter for uMsg.
wParamH
Parameter for uMsg.
dwExtraInfo
Specifies an additional 32-bit value associated with the event. An application calls GetMessageExtraInfo to obtain this extra information.

Remarks

If the mouse has moved, indicated by MOUSEEVENTF_MOVE being set, dx and dy specify information about that motion. The information is given as absolute or relative integer values.

If MOUSEEVENTF_ABSOLUTE value is specified, dx and dy contain normalized absolute coordinates between 0 and 65,535. The event procedure maps these coordinates onto the display surface. Coordinate (0,0) maps onto the upper-left corner of the display surface; coordinate (65535,65535) maps onto the lower-right corner.

If the MOUSEEVENTF_ABSOLUTE value is not specified, dx and dy specify motions relative to the previous mouse event (the last reported position). Positive values mean the mouse moved right (or down); negative values mean the mouse moved left (or up).

Relative mouse motion is subject to the effects of the mouse speed and the two mouse threshold values. A user sets these three values with the Pointer Speed slider of the Control Panel's Mouse Properties sheet. An application obtains and sets these values with the SystemParametersInfo function.

The operating system applies two tests to the specified relative mouse motion. If the specified distance along either the x or y axis is greater than the first mouse threshold value, and the mouse speed is not zero, the operating system doubles the distance. If the specified distance along either the x or y axis is greater than the second mouse threshold value, and the mouse speed is equal to two, the operating system doubles the distance that resulted from applying the first threshold test. It is thus possible for the operating system to multiply specified relative mouse motion along the x or y axis by up to four times.

QuickInfo

Windows NT: Requires version 4.0 SP3 or later.
Windows: Requires Windows 98 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Keyboard Input Overview, Keyboard Input Structures, GetMessageExtraInfo, SendInput, SystemParametersInfo


Keyboard Input Messages

The following messages are used to receive and process keyboard input.

WM_ACTIVATE
WM_CHAR
WM_DEADCHAR
WM_GETHOTKEY
WM_HOTKEY
WM_KEYDOWN
WM_KEYUP
WM_KILLFOCUS
WM_SETFOCUS
WM_SETHOTKEY
WM_SYSCHAR
WM_SYSDEADCHAR
WM_SYSKEYDOWN
WM_SYSKEYUP


WM_ACTIVATE

The WM_ACTIVATE message is sent to both the window being activated and the window being deactivated. If the windows use the same input queue, the message is sent synchronously, first to the window procedure of the top-level window being deactivated, then to the window procedure of the top-level window being activated. If the windows use different input queues, the message is sent asynchronously, so the window is activated immediately.

WM_ACTIVATE
fActive = LOWORD(wParam);           // activation flag
fMinimized = (BOOL) HIWORD(wParam); // minimized flag
hwndPrevious = (HWND) lParam;       // window handle

Parameters

fActive
Value of the low-order word of wParam. Specifies whether the window is being activated or deactivated. This parameter can be one of the following values.
Value | Meaning
WA_ACTIVE | Activated by some method other than a mouse click (for example, by a call to the SetActiveWindow function or by use of the keyboard interface to select the window).
WA_CLICKACTIVE | Activated by a mouse click.
WA_INACTIVE | Deactivated.

fMinimized
Value of the high-order word of wParam. Specifies the minimized state of the window being activated or deactivated. A nonzero value indicates the window is minimized.
hwndPrevious
Value of lParam. Handle to the window being activated or deactivated, depending on the value of the fActive parameter. If the value of fActive is WA_INACTIVE, hwndPrevious is the handle to the window being activated. If the value of fActive is WA_ACTIVE or WA_CLICKACTIVE, hwndPrevious is the handle to the window being deactivated. This handle can be NULL.

Return Values

If an application processes this message, it should return zero.

Default Action

If the window is being activated and is not minimized, the DefWindowProc function sets the keyboard focus to the window.

Remarks

If the window is activated by a mouse click, it also receives a WM_MOUSEACTIVATE message.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Keyboard Input Overview, Keyboard Input Messages, DefWindowProc, SetActiveWindow, WM_MOUSEACTIVATE, WM_NCACTIVATE


WM_CHAR

The WM_CHAR message is posted to the window with the keyboard focus when a WM_KEYDOWN message is translated by the TranslateMessage function. WM_CHAR contains the character code of the key that was pressed.

WM_CHAR
chCharCode = (TCHAR) wParam;    // character code
lKeyData = lParam;              // key data

Parameters

chCharCode
Value of wParam. Specifies the character code of the key.
lKeyData
Value of lParam. Specifies the repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag, as shown in the following table.
Value | Description
0–15 | Specifies the repeat count for the current message. The value is the number of times the keystroke is auto-repeated as a result of the user holding down the key. If the keystroke is held long enough, multiple messages are sent. However, the repeat count is not cumulative.
16–23 | Specifies the scan code. The value depends on the original equipment manufacturer (OEM).
24 | Specifies whether the key is an extended key, such as the right-hand alt and ctrl keys that appear on an enhanced 101- or 102-key keyboard. The value is 1 if it is an extended key; otherwise, it is 0.
25–28 | Reserved; do not use.
29 | Specifies the context code. The value is 1 if the alt key is held down while the key is pressed; otherwise, the value is 0.
30 | Specifies the previous key state. The value is 1 if the key is down before the message is sent, or it is 0 if the key is up.
31 | Specifies the transition state. The value is 1 if the key is being released, or it is 0 if the key is being pressed.

Return Values

An application should return zero if it processes this message.

Remarks

Because there is not necessarily a one-to-one correspondence between keys pressed and character messages generated, the information in the high-order word of the lKeyData parameter is generally not useful to applications. The information in the high-order word applies only to the most recent WM_KEYDOWN message that precedes the posting of the WM_CHAR message.

For enhanced 101- and 102-key keyboards, extended keys are the right alt and the right ctrl keys on the main section of the keyboard; the ins, del, home, end, page up, page down and arrow keys in the clusters to the left of the numeric keypad; and the divide (/) and enter keys in the numeric keypad. Some other keyboards may support the extended-key bit in the lKeyData parameter.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Keyboard Input Overview, Keyboard Input Messages, TranslateMessage, WM_KEYDOWN


WM_DEADCHAR

The WM_DEADCHAR message is posted to the window with the keyboard focus when a WM_KEYUP message is translated by the TranslateMessage function. WM_DEADCHAR specifies a character code generated by a dead key. A dead key is a key that generates a character, such as the umlaut (double-dot), that is combined with another character to form a composite character. For example, the umlaut-O character (Ö) is generated by typing the dead key for the umlaut character, and then typing the O key.

WM_DEADCHAR
chCharCode = (TCHAR) wParam;    // character code
lKeyData = lParam;              // key data

Parameters

chCharCode
Value of wParam. Specifies the character code generated by the dead key.
lKeyData
Value of lParam. Specifies the repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag, as shown in the following table.
Value | Description
0–15 | Specifies the repeat count for the current message. The value is the number of times the keystroke is auto-repeated as a result of the user holding down the key. If the keystroke is held long enough, multiple messages are sent. However, the repeat count is not cumulative.
16–23 | Specifies the scan code. The value depends on the original equipment manufacturer (OEM).
24 | Specifies whether the key is an extended key, such as the right-hand alt and ctrl keys that appear on an enhanced 101- or 102-key keyboard. The value is 1 if it is an extended key; otherwise, it is 0.
25–28 | Reserved; do not use.
29 | Specifies the context code. The value is 1 if the alt key is held down while the key is pressed; otherwise, the value is 0.
30 | Specifies the previous key state. The value is 1 if the key is down before the message is sent, or it is 0 if the key is up.
31 | Specifies the transition state. The value is 1 if the key is being released, or it is 0 if the key is being pressed.

Return Values

An application should return zero if it processes this message.

Remarks

The WM_DEADCHAR message typically is used by applications to give the user feedback about each key pressed. For example, an application can display the accent in the current character position without moving the caret.

Because there is not necessarily a one-to-one correspondence between keys pressed and character messages generated, the information in the high-order word of the lKeyData parameter is generally not useful to applications. The information in the high-order word applies only to the most recent WM_KEYDOWN message that precedes the posting of the WM_DEADCHAR message.

For enhanced 101- and 102-key keyboards, extended keys are the right alt and the right ctrl keys on the main section of the keyboard; the ins, del, home, end, page up, page down and arrow keys in the clusters to the left of the numeric keypad; and the divide (/) and enter keys in the numeric keypad. Some other keyboards may support the extended-key bit in the lKeyData parameter.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Keyboard Input Overview, Keyboard Input Messages, TranslateMessage, WM_KEYDOWN, WM_KEYUP, WM_SYSDEADCHAR


WM_GETHOTKEY

An application sends a WM_GETHOTKEY message to determine the hot key associated with a window.

WM_GETHOTKEY
wParam = 0; // not used; must be zero
lParam = 0; // not used; must be zero

Parameters

This message has no parameters.

Return Values

The return value is the virtual-key code and modifiers for the hot key, or NULL if no hot key is associated with the window. The virtual-key code is in the low byte of the return value and the modifiers are in the high byte. The modifiers can be a combination of the following flags.

Value | Meaning
HOTKEYF_ALT | ALT key
HOTKEYF_CONTROL | CTRL key
HOTKEYF_EXT | Extended key
HOTKEYF_SHIFT | SHIFT key

Remarks

These hot keys are unrelated to the hot keys set by the RegisterHotKey function.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Keyboard Input Overview, Keyboard Input Messages, RegisterHotKey, WM_SETHOTKEY


WM_HOTKEY

The WM_HOTKEY message is posted when the user presses a hot key registered by the RegisterHotKey function. The message is placed at the top of the message queue associated with the thread that registered the hot key.

WM_HOTKEY
idHotKey = (int) wParam;              // identifier of hot key
fuModifiers = (UINT) LOWORD(lParam);  // key-modifier flags
uVirtKey = (UINT) HIWORD(lParam);     // virtual-key code

Parameters

idHotKey
Value of wParam. Specifies the identifier of the hot key that generated the message. If the message was generated by a system-defined hot key, the idHotKey parameter will be one of the following values.
Value | Meaning
IDHOT_SNAPDESKTOP | The "snap desktop" hot key was pressed.
IDHOT_SNAPWINDOW | The "snap window" hot key was pressed.

fuModifiers
Specifies the keys that were to be pressed in combination with the key specified by the nVirtKey parameter to generate the WM_HOTKEY message. The fuModifiers parameter can be a combination of the following values.
Value | Meaning
MOD_ALT | Either ALT key was held down.
MOD_CONTROL | Either CTRL key was held down.
MOD_SHIFT | Either SHIFT key was held down.
MOD_WIN | Either WINDOWS key was held down. These keys are labeled with the Microsoft Windows logo.

uVirtKey
Specifies the virtual key code of the hot key.

Remarks

WM_HOTKEY is unrelated to the WM_GETHOTKEY and WM_SETHOTKEY hot keys. The WM_HOTKEY message is sent for generic hot keys while the WM_SET\GETHOTKEY messages relate to window activation hot keys.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Keyboard Input Overview, Keyboard Input Messages, RegisterHotKey, WM_GETHOTKEY, WM_SETHOTKEY


WM_KEYDOWN

The WM_KEYDOWN message is posted to the window with the keyboard focus when a nonsystem key is pressed. A nonsystem key is a key that is pressed when the alt key is not pressed.

WM_KEYDOWN
nVirtKey = (int) wParam;    // virtual-key code
lKeyData = lParam;          // key data

Parameters

nVirtKey
Value of wParam. Specifies the virtual-key code of the nonsystem key.
lKeyData
Value of lParam. Specifies the repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag, as shown in the following table.
Value | Description
0–15 | Specifies the repeat count for the current message. The value is the number of times the keystroke is auto-repeated as a result of the user holding down the key. If the keystroke is held long enough, multiple messages are sent. However, the repeat count is not cumulative.
16–23 | Specifies the scan code. The value depends on the original equipment manufacturer (OEM).
24 | Specifies whether the key is an extended key, such as the right-hand alt and ctrl keys that appear on an enhanced 101- or 102-key keyboard. The value is 1 if it is an extended key; otherwise, it is 0.
25–28 | Reserved; do not use.
29 | Specifies the context code. The value is always 0 for a WM_KEYDOWN message.
30 | Specifies the previous key state. The value is 1 if the key is down before the message is sent, or it is 0 if the key is up.
31 | Specifies the transition state. The value is always 0 for a WM_KEYDOWN message.

Return Values

An application should return zero if it processes this message.

Default Action

If the f10 key is pressed, the DefWindowProc function sets an internal flag. When DefWindowProc receives the WM_KEYUP message, the function checks whether the internal flag is set and, if so, sends a WM_SYSCOMMAND message to the top-level window. The wParam parameter of the message is set to SC_KEYMENU.

Remarks

Because of the autorepeat feature, more than one WM_KEYDOWN message may be posted before a WM_KEYUP message is posted. The previous key state (bit 30) can be used to determine whether the WM_KEYDOWN message indicates the first down transition or a repeated down transition.

For enhanced 101- and 102-key keyboards, extended keys are the right alt and ctrl keys on the main section of the keyboard; the ins, del, home, end, page up, page down and arrow keys in the clusters to the left of the numeric keypad; and the divide (/) and enter keys in the numeric keypad. Other keyboards may support the extended-key bit in the lKeyData parameter.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Keyboard Input Overview, Keyboard Input Messages, DefWindowProc, WM_CHAR, WM_KEYUP, WM_SYSCOMMAND


WM_KEYUP

The WM_KEYUP message is posted to the window with the keyboard focus when a nonsystem key is released. A nonsystem key is a key that is pressed when the alt key is not pressed, or a keyboard key that is pressed when a window has the keyboard focus.

WM_KEYUP
nVirtKey = (int) wParam;    // virtual-key code
lKeyData = lParam;          // key data

Parameters

nVirtKey
Value of wParam. Specifies the virtual-key code of the nonsystem key.
lKeyData
Value of lParam. Specifies the repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag, as shown in the following table.
Value | Description
0–15 | Specifies the repeat count for the current message. The value is the number of times the keystroke is auto-repeated as a result of the user holding down the key. The repeat count is always one for a WM_KEYUP message.
16–23 | Specifies the scan code. The value depends on the original equipment manufacturer (OEM).
24 | Specifies whether the key is an extended key, such as the right-hand alt and ctrl keys that appear on an enhanced 101- or 102-key keyboard. The value is 1 if it is an extended key; otherwise, it is 0.
25–28 | Reserved; do not use.
29 | Specifies the context code. The value is always 0 for a WM_KEYUP message.
30 | Specifies the previous key state. The value is always 1 for a WM_KEYUP message.
31 | Specifies the transition state. The value is always 1 for a WM_KEYUP message.

Return Values

An application should return zero if it processes this message.

Default Action

The DefWindowProc function sends a WM_SYSCOMMAND message to the top-level window if the f10 key or the alt key was released. The wParam parameter of the message is set to SC_KEYMENU.

Remarks

For enhanced 101- and 102-key keyboards, extended keys are the right alt and ctrl keys on the main section of the keyboard; the ins, del, home, end, page up, page down and arrow keys in the clusters to the left of the numeric keypad; and the divide (/) and enter keys in the numeric keypad. Other keyboards may support the extended-key bit in the lKeyData parameter.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Keyboard Input Overview, Keyboard Input Messages, DefWindowProc, WM_KEYDOWN, WM_SYSCOMMAND


WM_KILLFOCUS

The WM_KILLFOCUS message is sent to a window immediately before it loses the keyboard focus.

WM_KILLFOCUS
hwndGetFocus = (HWND) wParam; // handle to window receiving focus

Parameters

hwndGetFocus
Value of wParam. Handle to the window that receives the keyboard focus (may be NULL).

Return Values

An application should return zero if it processes this message.

Remarks

If an application is displaying a caret, the caret should be destroyed at this point.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Keyboard Input Overview, Keyboard Input Messages, SetFocus, WM_SETFOCUS


WM_SETFOCUS

The WM_SETFOCUS message is sent to a window after it has gained the keyboard focus.

WM_SETFOCUS
hwndLoseFocus = (HWND) wParam; // handle to window losing focus

Parameters

hwndLoseFocus
Value of wParam. Handle to the window that has lost the keyboard focus (may be NULL).

Return Values

An application should return zero if it processes this message.

Remarks

To display a caret, an application should call the appropriate caret functions when it receives the WM_SETFOCUS message.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Keyboard Input Overview, Keyboard Input Messages, SetFocus, WM_KILLFOCUS


WM_SETHOTKEY

An application sends a WM_SETHOTKEY message to a window to associate a hot key with the window. When the user presses the hot key, the system activates the window.

WM_SETHOTKEY
wParam = (WPARAM) MAKEWORD(vkey, modifiers)   // virtual-key code and modifiers of hot key
lParam = 0;                                   // not used; must be zero

Parameters

vkey
Value of wParam. Specifies the virtual-key code and modifiers of the hot key to associate with the window. The virtual-key code is in the low byte of the parameter and the modifier flags are in the high byte. Setting this parameter to NULL removes the hot key associated with a window. The modifier byte can be a combination of the following flags.
Value | Meaning
HOTKEYF_ALT | ALT key
HOTKEYF_CONTROL | CTRL key
HOTKEYF_EXT | Extended key
HOTKEYF_SHIFT | SHIFT key

Return Values

The return value is one of the following:

Value | Meaning
–1 | The function is unsuccessful — the hot key is invalid.
..0 | The function is unsuccessful — the window is invalid.
..1 | The function is successful, and no other window has the same hot key.
..2 | The function is successful, but another window already has the same hot key.

Remarks

A hot key cannot be associated with a child window.

VK_ESCAPE, VK_SPACE, and VK_TAB are invalid hot keys.

When the user presses the hot key, the system generates a WM_SYSCOMMAND message with wParam equal to SC_HOTKEY and lParam equal to the window's handle. If this message is passed on to DefWindowProc, the system will bring the window's last active popup (if it exists) or the window itself (if there is no popup window) to the foreground.

A window can only have one hot key. If the window already has a hot key associated with it, the new hot key replaces the old one. If more than one window has the same hot key, the window that is activated by the hot key is random.

These hot keys are unrelated to the hot keys set by RegisterHotKey.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Keyboard Input Overview, Keyboard Input Messages, RegisterHotKey, WM_GETHOTKEY, WM_SYSCOMMAND


WM_SYSDEADCHAR

The WM_SYSDEADCHAR message is sent to the window with the keyboard focus when a WM_SYSKEYDOWN message is translated by the TranslateMessage function. WM_SYSDEADCHAR specifies the character code of a system dead key — that is, a dead key that is pressed while holding down the alt key.

WM_SYSDEADCHAR
chCharCode = (TCHAR) wParam;    // character code
lKeyData = lParam;              // key data

Parameters

chCharCode
Value of wParam. Specifies the character code generated by the system dead key — that is, a dead key that is pressed while holding down the alt key.
lKeyData
Value of lParam. Specifies the repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag, as shown in the following table.
Value | Description
0–15 | Specifies the repeat count for the current message. The value is the number of times the keystroke is auto-repeated as a result of the user holding down the key. If the keystroke is held long enough, multiple messages are sent. However, the repeat count is not cumulative.
16–23 | Specifies the scan code. The value depends on the original equipment manufacturer (OEM).
24 | Specifies whether the key is an extended key, such as the right-hand alt and ctrl keys that appear on an enhanced 101- or 102-key keyboard. The value is 1 if it is an extended key; otherwise, it is 0.
25–28 | Reserved; do not use.
29 | Specifies the context code. The value is 1 if the alt key is held down while the key is pressed; otherwise, the value is 0.
30 | Specifies the previous key state. The value is 1 if the key is down before the message is sent, or it is 0 if the key is up.
31 | Specifies the transition state. The value is 1 if the key is being released, or it is 0 if the key is being pressed.

Return Values

An application should return zero if it processes this message.

Remarks

For enhanced 101- and 102-key keyboards, extended keys are the right alt and ctrl keys on the main section of the keyboard; the ins, del, home, end, page up, page down and arrow keys in the clusters to the left of the numeric keypad; and the divide (/) and enter keys in the numeric keypad. Other keyboards may support the extended-key bit in the lKeyData parameter.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Keyboard Input Overview, Keyboard Input Messages, TranslateMessage, WM_DEADCHAR, WM_SYSKEYDOWN


WM_SYSKEYDOWN

The WM_SYSKEYDOWN message is posted to the window with the keyboard focus when the user presses the F10 key (which activates the menu bar) or holds down the alt key and then presses another key. It also occurs when no window currently has the keyboard focus; in this case, the WM_SYSKEYDOWN message is sent to the active window. The window that receives the message can distinguish between these two contexts by checking the context code in the lKeyData parameter.

WM_SYSKEYDOWN
nVirtKey = (int) wParam;    // virtual-key code
lKeyData = lParam;          // key data

Parameters

nVirtKey
Value of wParam. Specifies the virtual-key code of the key being pressed.
lKeyData
Value of lParam. Specifies the repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag, as shown in the following table.
Value | Description
0–15 | Specifies the repeat count for the current message. The value is the number of times the keystroke is auto-repeated as a result of the user holding down the key. If the keystroke is held long enough, multiple messages are sent. However, the repeat count is not cumulative.
16–23 | Specifies the scan code. The value depends on the original equipment manufacturer (OEM).
24 | Specifies whether the key is an extended key, such as the right-hand alt and ctrl keys that appear on an enhanced 101- or 102-key keyboard. The value is 1 if it is an extended key; otherwise, it is 0.
25–28 | Reserved; do not use.
29 | Specifies the context code. The value is 1 if the ALT key is down while the key is pressed; it is 0 if the WM_SYSKEYDOWN message is posted to the active window because no window has the keyboard focus.
30 | Specifies the previous key state. The value is 1 if the key is down before the message is sent, or it is 0 if the key is up.
31 | Specifies the transition state. The value is always 0 for a WM_SYSKEYDOWN message.

Return Values

An application should return zero if it processes this message.

Default Action

The DefWindowProc function examines the given key and generates a WM_SYSCOMMAND message if the key is either tab or enter.

Remarks

When the context code is zero, the message can be passed to the TranslateAccelerator function, which will handle it as though it were a normal key message instead of a character-key message. This allows accelerator keys to be used with the active window even if the active window does not have the keyboard focus.

Because of automatic repeat, more than one WM_SYSKEYDOWN message may occur before a WM_SYSKEYUP message is sent. The previous key state (bit 30) can be used to determine whether the WM_SYSKEYDOWN message indicates the first down transition or a repeated down transition.

For enhanced 101- and 102-key keyboards, enhanced keys are the right alt and ctrl keys on the main section of the keyboard; the ins, del, home, end, page up, page down and arrow keys in the clusters to the left of the numeric keypad; and the divide (/) and enter keys in the numeric keypad. Other keyboards may support the extended-key bit in the lParam parameter.

This message is also sent whenever the user presses the F10 key without the ALT key.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Keyboard Input Overview, Keyboard Input Messages, DefWindowProc, TranslateAccelerator, WM_SYSCOMMAND, WM_SYSKEYUP


WM_SYSKEYUP

The WM_SYSKEYUP message is posted to the window with the keyboard focus when the user releases a key that was pressed while the alt key was held down. It also occurs when no window currently has the keyboard focus; in this case, the WM_SYSKEYUP message is sent to the active window. The window that receives the message can distinguish between these two contexts by checking the context code in the lKeyData parameter.

WM_SYSKEYUP
nVirtKey = (int) wParam;    // virtual-key code
lKeyData = lParam;          // key data

Parameters

nVirtKey
Value of wParam. Specifies the virtual-key code of the key being released.
lKeyData
Value of lParam. Specifies the repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag, as shown in the following table.
Value | Description
0–15 | Specifies the repeat count for the current message. The value is the number of times the keystroke is auto-repeated as a result of the user holding down the key. The repeat count is always one for a WM_SYSKEYUP message.
16–23 | Specifies the scan code. The value depends on the original equipment manufacturer (OEM).
24 | Specifies whether the key is an extended key, such as the right-hand alt and ctrl keys that appear on an enhanced 101- or 102-key keyboard. The value is 1 if it is an extended key; otherwise, it is 0.
25–28 | Reserved; do not use.
29 | Specifies the context code. The value is 1 if the ALT key is down while the key is released; it is 0 if the WM_SYSKEYDOWN message is posted to the active window because no window has the keyboard focus.
30 | Specifies the previous key state. The value is always 1 for a WM_SYSKEYUP message.
31 | Specifies the transition state. The value is always 1 for a WM_SYSKEYUP message.

Return Values

An application should return zero if it processes this message.

Default Action

The DefWindowProc function sends a WM_SYSCOMMAND message to the top-level window if the f10 key or the alt key was released. The wParam parameter of the message is set to SC_KEYMENU.

Remarks

When the context code is zero, the message can be passed to the TranslateAccelerator function, which will handle it as though it were a normal key message instead of a character-key message. This allows accelerator keys to be used with the active window even if the active window does not have the keyboard focus.

For enhanced 101- and 102-key keyboards, extended keys are the right alt and ctrl keys on the main section of the keyboard; the ins, del, home, end, page up, page down and arrow keys in the clusters to the left of the numeric keypad; and the divide (/) and enter keys in the numeric keypad. Other keyboards may support the extended-key bit in the lKeyData parameter.

For non-U.S. enhanced 102-key keyboards, the right alt key is handled as a ctrl+alt key. The following table shows the sequence of messages that result when the user presses and releases this key.

Message | Virtual-key code
WM_KEYDOWN | VK_CONTROL
WM_KEYDOWN | VK_MENU
WM_KEYUP | VK_CONTROL
WM_SYSKEYUP | VK_MENU

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Keyboard Input Overview, Keyboard Input Messages, DefWindowProc, TranslateAccelerator, WM_SYSCOMMAND, WM_SYSKEYDOWN


Virtual-Key Codes

The following table shows the symbolic constant names, hexadecimal values, and mouse or keyboard equivalents for the virtual-key codes used by the system. The codes are listed in numeric order.

Symbolic constant name | Value (hexadecimal) | Mouse or keyboard equivalent
VK_LBUTTON | 01 | Left mouse button
VK_RBUTTON | 02 | Right mouse button
VK_CANCEL | 03 | Control-break processing
VK_MBUTTON | 04 | Middle mouse button (three-button mouse)
— | 05–07 | Undefined
VK_BACK | 08 | backspace key
VK_TAB | 09 | tab key
— | 0A–0B | Undefined
VK_CLEAR | 0C | clear key
VK_RETURN | 0D | enter key
— | 0E–0F | Undefined
VK_SHIFT | 10 | shift key
VK_CONTROL | 11 | ctrl key
VK_MENU | 12 | alt key
VK_PAUSE | 13 | pause key
VK_CAPITAL | 14 | caps lock key
— | 15–19 | Reserved for Kanji systems
— | 1A | Undefined
VK_ESCAPE | 1B | esc key
— | 1C–1F | Reserved for Kanji systems
VK_SPACE | 20 | spacebar
VK_PRIOR | 21 | page up key
VK_NEXT | 22 | page down key
VK_END | 23 | end key
VK_HOME | 24 | home key
VK_LEFT | 25 | left arrow key
VK_UP | 26 | up arrow key
VK_RIGHT | 27 | right arrow key
VK_DOWN | 28 | down arrow key
VK_SELECT | 29 | select key
— | 2A | Original equipment manufacturer (OEM) specific
VK_EXECUTE | 2B | execute key
VK_SNAPSHOT | 2C | print screen key
VK_INSERT | 2D | ins key
VK_DELETE | 2E | del key
VK_HELP | 2F | help key
VK_0 | 30 | 0 key
VK_1 | 31 | 1 key
VK_2 | 32 | 2 key
VK_3 | 33 | 3 key
VK_4 | 34 | 4 key
VK_5 | 35 | 5 key
VK_6 | 36 | 6 key
VK_7 | 37 | 7 key
VK_8 | 38 | 8 key
VK_9 | 39 | 9 key
— | 3A–40 | Undefined
VK_A | 41 | a key
VK_B | 42 | b key
VK_C | 43 | c key
VK_D | 44 | d key
VK_E | 45 | e key
VK_F | 46 | f key
VK_G | 47 | g key
VK_H | 48 | h key
VK_I | 49 | i key
VK_J | 4A | j key
VK_K | 4B | k key
VK_L | 4C | l key
VK_M | 4D | m key
VK_N | 4E | n key
VK_O | 4F | o key
VK_P | 50 | p key
VK_Q | 51 | q key
VK_R | 52 | r key
VK_S | 53 | s key
VK_T | 54 | t key
VK_U | 55 | u key
VK_V | 56 | v key
VK_W | 57 | w key
VK_X | 58 | x key
VK_Y | 59 | y key
VK_Z | 5A | z key
VK_LWIN | 5B | Left Windows key (Microsoft Natural Keyboard)
VK_RWIN | 5C | Right Windows key (Microsoft Natural Keyboard)
VK_APPS | 5D | Applications key (Microsoft Natural Keyboard)
— | 5E–5F | Undefined
VK_NUMPAD0 | 60 | Numeric keypad 0 key
VK_NUMPAD1 | 61 | Numeric keypad 1 key
VK_NUMPAD2 | 62 | Numeric keypad 2 key
VK_NUMPAD3 | 63 | Numeric keypad 3 key
VK_NUMPAD4 | 64 | Numeric keypad 4 key
VK_NUMPAD5 | 65 | Numeric keypad 5 key
VK_NUMPAD6 | 66 | Numeric keypad 6 key
VK_NUMPAD7 | 67 | Numeric keypad 7 key
VK_NUMPAD8 | 68 | Numeric keypad 8 key
VK_NUMPAD9 | 69 | Numeric keypad 9 key
VK_MULTIPLY | 6A | Multiply key
VK_ADD | 6B | Add key
VK_SEPARATOR | 6C | Separator key
VK_SUBTRACT | 6D | Subtract key
VK_DECIMAL | 6E | Decimal key
VK_DIVIDE | 6F | Divide key
VK_F1 | 70 | f1 key
VK_F2 | 71 | f2 key
VK_F3 | 72 | f3 key
VK_F4 | 73 | f4 key
VK_F5 | 74 | f5 key
VK_F6 | 75 | f6 key
VK_F7 | 76 | f7 key
VK_F8 | 77 | f8 key
VK_F9 | 78 | f9 key
VK_F10 | 79 | f10 key
VK_F11 | 7A | f11 key
VK_F12 | 7B | f12 key
VK_F13 | 7C | f13 key
VK_F14 | 7D | f14 key
VK_F15 | 7E | f15 key
VK_F16 | 7F | f16 key
VK_F17 | 80H | f17 key
VK_F18 | 81H | f18 key
VK_F19 | 82H | f19 key
VK_F20 | 83H | f20 key
VK_F21 | 84H | f21 key
VK_F22 | 85H | f22 key
VK_F23 | 86H | f23 key
VK_F24 | 87H | f24 key
— | 88–8F | Unassigned
VK_NUMLOCK | 90 | num lock key
VK_SCROLL | 91 | scroll lock key
— | 92–B9 | Unassigned
— | BA–C0 | OEM specific
— | C1–DA | Unassigned
— | DB–E4 | OEM specific
— | E5 | Unassigned
— | E6 | OEM specific
— | E7–E8 | Unassigned
— | E9–F5 | OEM specific
VK_ATTN | F6 | Attn key
VK_CRSEL | F7 | CrSel key
VK_EXSEL | F8 | ExSel key
VK_EREOF | F9 | Erase EOF key
VK_PLAY | FA | Play key
VK_ZOOM | FB | Zoom key
VK_NONAME | FC | Reserved for future use.
VK_PA1 | FD | PA1 key
VK_OEM_CLEAR | FE | Clear key


Dialog Boxes

A dialog box is a temporary window an application creates to retrieve user input. An application typically uses dialog boxes to prompt the user for additional information for commands. A dialog box usually contains one or more controls (child windows) with which the user enters text, chooses options, or directs the action of the command.


About Dialog Boxes

The Win32 API provides many functions, messages, and predefined controls to help create and manage dialog boxes, thus making it easier to develop the user interface for an application. This overview describes the dialog box functions and messages and explains how to use them to create and use dialog boxes.

The Win32 API also provides many predefined, or "common," dialog boxes that support commands, such as File Open and File Print. Applications that use these commands should use the common dialog boxes to prompt for the same user input, regardless of the type of application carrying out the commands. For more information about using common dialog boxes in your applications, see Common Dialog Box Library.


When to Use a Dialog Box

Most applications use dialog boxes to prompt for additional information for commands that require user input. Using a dialog box is the only recommended way for an application to retrieve the input. For example, the File Open command 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 chooses the command 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 command. 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 chooses a command 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, the Win32 API provides 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 commands 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 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, 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.


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 command in a menu, 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.

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.


Message Boxes

A message box is a special dialog box that an application can use to display messages and prompt for simple input. A message box typically contains a text message and one or more buttons. An application creates the message box by using the MessageBox or MessageBoxEx function, specifying the text and the number and types of buttons to display. The MessageBoxEx function also allows you to specify the language to use for the text of any predefined push buttons in the message box.

Although the message box is a dialog box, the system takes complete control of the creation and management of the message box. This means the application does not provide a dialog box template and dialog box procedure. The system creates its own template based on the text and buttons specified for the message box and supplies its own dialog box procedure.

A message box is a modal dialog box and the system creates it by using the same internal functions that DialogBox uses. If the application specifies an owner window when calling MessageBox or MessageBoxEx, the system disables the owner. An application can also direct the system to disable all top-level windows belonging to the current thread by specifying the MB_TASKMODAL value when creating the dialog box.

The system can send messages to the owner, such as WM_CANCELMODE and WM_ENABLE, just as it does when creating a modal dialog box. The owner window should carry out any actions requested by these messages.


Modal Dialog Boxes

A modal dialog box should be a pop-up window having a System menu, a title bar, and a thick border; that is, the dialog box template should specify the WS_POPUP, WS_SYSMENU, WS_CAPTION, and DS_MODALFRAME styles. Although an application can designate the WS_VISIBLE style, the system always displays a modal dialog box regardless of whether the dialog box template specifies the WS_VISIBLE style. An application must not create a modal dialog box having the WS_CHILD style. A modal dialog box with this style disables itself, preventing any subsequent input from reaching the application.

An application creates a modal dialog box by using either the DialogBox or DialogBoxIndirect function. DialogBox requires the name or identifier of a resource containing a dialog box template; DialogBoxIndirect requires the handle of a memory object containing a dialog box template. The DialogBoxParam and DialogBoxIndirectParam functions also create modal dialog boxes; they are identical to the previously mentioned functions but pass a specified parameter to the dialog box procedure when the dialog box is created.

When creating the modal dialog box, the system makes it the active window. The dialog box remains active until the dialog box procedure calls the EndDialog function or the system activates a window in another application. Neither the user nor the application can make the owner window active until the modal dialog box is destroyed.

When the owner window is not already disabled, the system automatically disables the window and any child windows belonging to it when it creates the modal dialog box. The owner window remains disabled until the dialog box is destroyed. Although a dialog box procedure could potentially enable the owner window at any time, enabling the owner defeats the purpose of the modal dialog box and is not recommended. When the dialog box procedure is destroyed, the system enables the owner window again, but only if the modal dialog box caused the owner to be disabled.

As the system creates the modal dialog box, it sends the WM_CANCELMODE message to the window (if any) currently capturing mouse input. An application that receives this message should release the mouse capture so that the user can move the mouse in the modal dialog box. Because the system disables the owner window, all mouse input is lost if the owner fails to release the mouse upon receiving this message.

To process messages for the modal dialog box, the system starts its own message loop, taking temporary control of the message queue for the entire application. When the system retrieves a message that is not explicitly for the dialog box, it dispatches the message to the appropriate window. If it retrieves a WM_QUIT message, it posts the message back to the application message queue so that the application's main message loop can eventually retrieve the message.

The system sends the WM_ENTERIDLE message to the owner window whenever the application message queue is empty. The application can use this message to carry out a background task while the dialog box remains on the screen. When an application uses the message in this way, the application must frequently yield control (for example, by using the PeekMessage function) so that the modal dialog box can receive any user input. To prevent the modal dialog box from sending the WM_ENTERIDLE messages, the application can specify the DS_NOIDLEMSG style when creating the dialog box.

An application destroys a modal dialog box by using the EndDialog function. In most cases, the dialog box procedure calls EndDialog when the user chooses the Close command from the dialog box's System menu or chooses the OK or Cancel button in the dialog box. The dialog box can return a value through the DialogBox function (or other creation functions) by specifying a value when calling the EndDialog function. The system returns this value after destroying the dialog box. Most applications use this return value to determine whether the dialog box completed its task successfully or was canceled by the user. The system does not return control from the function that creates the dialog box until the dialog box procedure has called the EndDialog function.


Modeless Dialog Boxes

A modeless dialog box should be a pop-up window having a System menu, a title bar, and a thin border; that is, the dialog box template should specify the WS_POPUP, WS_CAPTION, WS_BORDER, and WS_SYSMENU styles. The system does not automatically display the dialog box unless the template specifies the WS_VISIBLE style.

An application creates a modeless dialog box by using the CreateDialog or CreateDialogIndirect function. CreateDialog requires the name or identifier of a resource containing a dialog box template; CreateDialogIndirect requires the handle of a memory object containing a dialog box template. Two other functions, CreateDialogParam and CreateDialogIndirectParam, also create modeless dialog boxes; they pass a specified parameter to the dialog box procedure when the dialog box is created.

CreateDialog and other creation functions return a window handle for the dialog box. The application and the dialog box procedure can use this handle to manage the dialog box. For example, if WS_VISIBLE is not specified in the dialog box template, the application can display the dialog box by passing the window handle to the ShowWindow function.

A modeless dialog box neither disables the owner window nor sends messages to it. When creating the dialog box, the system makes it the active window, but the user or the application can change the active window at any time. If the dialog box does become inactive, it remains above the owner window in the Z order, even if the owner window is active.

The application is responsible for retrieving and dispatching input messages to the dialog box. Most applications use the main message loop for this. To permit the user to move to and select controls by using the keyboard, however, the application must call the IsDialogMessage function. For more information about this function, see Dialog Box Keyboard Interface.

A modeless dialog box cannot return a value to the application as a modal dialog box does, but the dialog box procedure can send information to the owner window by using the SendMessage function.

An application must destroy all modeless dialog boxes before terminating. It can destroy a modeless dialog box by using the DestroyWindow function. In most cases, the dialog box procedure calls DestroyWindow in response to user input, such as choosing the Cancel button. If the user never closes the dialog box in this way, the application must call DestroyWindow.

DestroyWindow invalidates the window handle for the dialog box, so any subsequent calls to functions that use the handle return error values. To prevent errors, the dialog box procedure should notify the owner that the dialog box has been destroyed. Many applications maintain a global variable containing the handle for the dialog box. When the dialog box procedure destroys the dialog box, it also sets the global variable to NULL, indicating that the dialog box is no longer valid.

The dialog box procedure must not call the EndDialog function to destroy a modeless dialog box.


Dialog Box Template

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.

Note An explanation of how to create template resources and add them to the application's executable file is beyond the scope of this overview. For more information about creating template resources and adding them to an executable file, see the documentation provided with your application development tools.

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, then modify the loaded resource to create a new memory template. For more information about creating a dialog box template in memory, see Templates in Memory.

The following sections describe the styles, measurements, and other values used in a dialog box template.


Dialog Box Template 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 given in the template to the CreateWindowEx function when creating the dialog box. The system may pass one or more extended styles depending on the given dialog box styles. For example, when the template specifies DS_MODALFRAME, the system uses WS_EX_DLGMODALFRAME when creating the dialog box. When the template specifies DS_SYSMODAL, the system uses WS_EX_TOPMOST. All other dialog box styles affect how the system manages the dialog box.

Most dialog boxes are pop-up windows that have a System 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 given. 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 template can specify the DS_SETFOREGROUND style to force the system to bring the dialog box to the foreground. This is especially useful for modal dialog boxes that require immediate attention from the user regardless of whether the owner window is the foreground window.

Using the DS_ABSALIGN style, the system interprets dialog box measurements as screen coordinates; using the DS_SETFONT style, the system uses a given font, instead of the system font, to draw text in the dialog box client area and in the controls in the dialog box; the DS_NOIDLEMSG style prevents a modal dialog box from sending WM_ENTERIDLE messages to the owner window. These styles are described in more detail in later in this topics.

The DS_LOCALEDIT style does not apply to Win32-based applications.

Dialog boxes with the DS_SYSMODAL style receive the WS_EX_TOPMOST window style but no other special properties or styles. This means the user still has access to other windows on the desktop even though you specified DS_SYSMODAL.


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 given 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 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.


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 given 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 command 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.

The template specifies the window class for each control. A 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 given message. The only exception to this rule are 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 command 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 given by other data. For example, an application can use creation data to set the initial setting and range for a scroll bar control.


System Menu

The system gives a dialog box a System menu when the template specifies the WS_SYSMENU style. To prevent inappropriate command input, the system automatically disables all commands in the menu except the Move and Close commands. The user can use the Move command to move the dialog box. When the user chooses the Close command, 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 chooses it. The recommended action for this message is to close the dialog box and cancel the requested command or 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.


Dialog Box Fonts

The system draws all text in a dialog box using the system font by default. An application can direct the system to use another font by setting the DS_SETFONT style for the dialog box and specifying a point size and typeface name. Although a dialog box template can specify a font, the system always uses the system font for the title and menus of the dialog box; the DS_SETFONT style does not change this.

When the DS_SETFONT style is specified, 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.

When the DS_SETFONT style is given, the system uses the average character width of the font to calculate the position and dimensions of the dialog box. Otherwise, it uses the average character width of the system font.


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 are aligned on DWORD boundaries. In addition, any creation data that follows a control definition 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.

The 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 null-terminated 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 that identifies the dialog box window when the system sends a WM_HELP message.
  • If the dialog box has the DS_SETFONT style, the header specifies the font weight and indicates whether the font is italic.

The 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:

  • 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 that identifies the control when the system sends a WM_HELP message.


Dialog Box Procedure

A dialog box procedure is similar to a window procedure in that the system sends messages to the procedure when it has information to give or tasks to carry out. Unlike a window procedure, a dialog box procedure never calls the DefWindowProc function. Instead, it returns the Boolean value TRUE if it processes a message or FALSE if it does not.

Every dialog box procedure has the following form:

BOOL APIENTRY DlgProc(hwndDlg, message, wParam, lParam)
HWND hwndDlg;
UINT message;
WPARAM wParam;
LPARAM lParam;
{
    switch (message)
    {

        // Place message cases here.

        default:
            return FALSE;
    }
}

The procedure parameters serve the same purpose as in a window procedure, with the hwndDlg parameter receiving the window handle of the dialog box.

Most dialog box procedures process the WM_INITDIALOG message and the WM_COMMAND messages sent by the controls, but process few if any other messages. If a dialog box procedure does not process a message, it must return FALSE to direct the system to process the messages internally. The only exception to this rule is the WM_INITDIALOG message. The dialog box procedure must return TRUE to direct the system to further process the WM_INITDIALOG message. In any case, the procedure must not call DefWindowProc.


The WM_INITDIALOG Message

The system does not send a WM_CREATE message to the dialog box procedure. Instead, it sends a WM_INITDIALOG message when it creates the dialog box and all its controls but before it displays the dialog box. The procedure should carry out any initialization required to ensure that the dialog box displays the current settings associated with the command or task. For example, when a dialog box contains a control to show the current drive and directory, the procedure must determine the current drive and directory and set the control to that value.

The procedure can initialize controls by using functions such as SetDlgItemText and CheckDlgButton. Because controls are windows, the procedure can also manipulate them by using window-management functions such as EnableWindow and SetFocus. The procedure can retrieve the window handle for a control by using the GetDlgItem function.

The dialog box procedure can change the contents, state, and position of any control as needed. For example, in a dialog box that contains a list box of filenames and an Open button, the procedure can disable the Open button until the user selects a file from the list. In this example, the dialog box template specifies the WS_DISABLED style for the Open button and the system automatically disables the button when creating it. When the dialog box procedure receives a notification message from the list box indicating that the user has selected a file, the procedure calls the EnableWindow function to enable the Open button.

To display a custom icon on the caption bar of the dialog box, your WM_INITDIALOG handler can send the WM_SETICON message to the dialog box.

If the application creates the dialog box by using one of the functions DialogBoxParam, DialogBoxIndirectParam, CreateDialogParam, or CreateDialogIndirectParam, the lParam parameter for the WM_INITDIALOG message contains the extra parameter passed to the function. Applications typically use this extra parameter to pass the address of additional initialization information to the dialog box procedure, but the dialog box procedure must determine the meaning of the parameter. If the application uses another function to create the dialog box, the system sets the lParam parameter to NULL.

Before returning from the WM_INITDIALOG message, the procedure should determine whether it should set the input focus to a given control. If the dialog box procedure returns TRUE, the system automatically sets the input focus to the control whose window handle is in the wParam parameter. If the control receiving the default focus is not appropriate, it can set the focus to the appropriate control by using the SetFocus function. If the procedure sets the input focus, it must return FALSE to prevent the system from setting the default focus. The control receiving the default input focus is always the first control given in the template that is visible, not disabled, and has the WS_TABSTOP style. If no such control exists, the system sets the default input focus to the first control in the template.


The WM_COMMAND Message

A control can send a WM_COMMAND message to the dialog box procedure when the user carries out an action in the control. These messages, called notification messages, inform the procedure of user input and permit it to carry out appropriate responses.

All predefined controls, except static controls, send notification messages for selected user actions. For example, a push button sends the BN_CLICKED notification message whenever the user chooses the button. In all cases, 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.

The dialog box procedure should monitor and process notification messages. In particular, the procedure must process messages having the IDOK or IDCANCEL identifiers; these messages represent a request by the user to close the dialog box. The procedure should close the dialog box by using the EndDialog function for modal dialog boxes and the DestroyWindow function for modeless dialog boxes.

The system also sends WM_COMMAND messages to the dialog box procedure if the dialog box has a menu, such as the System menu, and the user chooses a command. In particular, the system sends a WM_COMMAND message with the wParam parameter set to IDCANCEL whenever the user chooses the Close command in the dialog box's System menu. The message is nearly identical to the notification message sent by the Cancel button and should be processed in exactly the same way.


The WM_PARENTNOTIFY Message

A control sends a WM_PARENTNOTIFY message whenever the user presses a mouse button while pointing to the control. Some applications interpret this message as a signal to carry out an action related to the control, such as displaying a line of text describing the purpose of the control.

The system also sends WM_PARENTNOTIFY messages when it creates and destroys a window, but not for controls created from a dialog box template. The system prevents these messages by specifying the WS_EX_NOPARENTNOTIFY style when creating the controls. An application cannot override this default behavior unless it creates its own controls for the dialog box.


Control-Color Messages

Controls and the system can send control-color messages when they want the dialog box procedure to paint the background of a control or other window by using a specific brush and colors. This can be useful when applications override the default colors used in dialog boxes and their controls. Following are the control-color messages, which have replaced the WM_CTLCOLOR message.

WM_CTLCOLORBTN
WM_CTLCOLORDLG
WM_CTLCOLOREDIT
WM_CTLCOLORLISTBOX
WM_CTLCOLORMSGBOX
WM_CTLCOLORSCROLLBAR
WM_CTLCOLORSTATIC

A control sends a control-color message to the dialog box procedure just before it paints its own background. The message allows the procedure to specify which brush to use and to set the background and foreground colors. The procedure specifies a brush by returning the brush handle. To set the background and foreground colors, the procedure uses the SetBkColor and SetTextColor functions with the control's display device context. The control-color message passes a handle of the display device context to the procedure in the message's wParam parameter.

The system sends a WM_CTLCOLORDLG message to the dialog box procedure if the procedure does not process the WM_ERASEBKGND message. The predefined dialog box class does not have a class background brush, so this message lets the procedure define its own background without having to include the code to carry out the work.

In any case, when a dialog box procedure does not process a control-color message, the system uses a brush with the default window color to paint the background for all controls and windows except scroll bars. An application can retrieve the default window color by passing the COLOR_WINDOW value to the GetSysColor function. While the background is painted, the foreground color for the display device context is set to the default text color (COLOR_WINDOWTEXT). For scroll bars, the system uses a brush having the default scroll bar color (COLOR_SCROLLBAR). In this case, the background and foreground colors for the display device context are set to white and black, respectively.


Dialog Box Default Message Processing

The window procedure for the predefined dialog box class carries out default processing for all messages that the dialog box procedure does not process. When the dialog box procedure returns FALSE for any message, the predefined window procedure checks the messages and carries out the following default actions:

Message | Default action
DM_GETDEFID | You can send this message to a dialog box. The dialog box returns the control identifier of the default push button, if the dialog box has one; otherwise, it returns zero.
DM_REPOSITION | You can send this message to a top-level dialog box. The dialog box repositions itself so it fits within the desktop area.
DM_SETDEFID | You can send this message to a dialog box. The dialog box sets the default push button to the control specified by the control identifier in the wParam parameter.
WM_ACTIVATE | Restores the input focus to the control identified by the previously saved handle if the dialog box is activated. Otherwise, the procedure saves the handle of the control having the input focus.
WM_CHARTOITEM | Returns zero.
WM_CLOSE | Posts the BN_CLICKED notification message to the dialog box, specifying IDCANCEL as the control identifier. If the dialog box has an IDCANCEL control identifier and the control is currently disabled, the procedure sounds a warning and does not post the message.
WM_COMPAREITEM | Returns zero.
WM_ERASEBKGND | Fills the dialog box client area by using either the brush returned from the WM_CTLCOLORDLG message or with the default window color.
WM_GETFONT | Returns the handle of the application-defined dialog box font.
WM_INITDIALOG | Returns zero.
WM_LBUTTONDOWN | Sends a CB_SHOWDROPDOWN message to the combo box having the input focus, directing the control to hide its drop-down list box. The procedure calls DefWindowProc to complete the default action.
WM_NCDESTROY | Releases global memory allocated for edit controls in the dialog box (applies to dialog boxes in Windows-based applications that specify the DS_LOCALEDIT style) and frees any application-defined font (applies to dialog boxes that specify the DS_SETFONT style). The procedure calls the DefWindowProc function to complete the default action.
WM_NCLBUTTONDOWN | Sends a CB_SHOWDROPDOWN message to the combo box having the input focus, directing the control to hide its drop-down list box. The procedure calls DefWindowProc to complete the default action.
WM_NEXTDLGCTL | Sets the input focus to the next or previous control in the dialog box, to the control identified by the handle in the wParam parameter, or to the first control in the dialog box that is visible, not disabled, and has the WS_TABSTOP style. The procedure ignores this message if the current window with the input focus is not a control.
WM_SETFOCUS | Sets the input focus to the control identified by a previously saved control window handle. If no such handle exists, the procedure sets the input focus to the first control in the dialog box template that is visible, not disabled, and has the WS_TABSTOP style. If no such control exists, the procedure sets the input focus to the first control in the template.
WM_SHOWWINDOW | Saves the handle of the control having the input focus if the dialog box is being hidden, then calls DefWindowProc to complete the default action.
WM_SYSCOMMAND | Saves the handle of the control having the input focus if the dialog box is being minimized, then calls DefWindowProc to complete the default action.
WM_VKEYTOITEM | Returns zero.

The predefined window procedure passes all other messages to DefWindowProc for default processing.


Dialog Box Keyboard Interface

The system provides a special keyboard interface for dialog boxes that carries out special processing for several keys. The interface generates messages that correspond to certain buttons in the dialog box or changes the input focus from one control to another. Following are the keys used in this interface and their respective actions.

Key | Action
alt+mnemonic | Moves the input focus to the first control (having the WS_TABSTOP style) after the static control containing the given mnemonic.
down | Moves the input focus to the next control in the group.
enter | Sends a WM_COMMAND message to the dialog box procedure. The wParam parameter is set to IDOK or control identifier of the default push button.
esc | Sends a WM_COMMAND message to the dialog box procedure. The wParam parameter is set to IDCANCEL.
left | Moves the input focus to the previous control in the group.
mnemonic | Moves the input focus to the first control (having the WS_TABSTOP style) after the static control containing the given mnemonic.
right | Moves the input focus to the next control in the group.
shift+tab | Moves the input focus to the previous control that has the WS_TABSTOP style.
tab | Moves the input focus to the next control that has the WS_TABSTOP style.
up | Moves the input focus to the previous control in the group.

The system automatically provides the keyboard interface for all modal dialog boxes. It does not provide the interface for modeless dialog boxes unless the application calls the IsDialogMessage function to filter messages in its main message loop. This means that the application must pass the message to IsDialogMessage immediately after retrieving the message from the message queue. The function processes the messages if it is for the dialog box and returns a nonzero value to indicate that the message has been processed and must not be passed to the TranslateMessage or DispatchMessage function.

Because the dialog box keyboard interface uses direction keys to move between controls in a dialog box, an application cannot use these keys to scroll the contents of any modal dialog box or any modeless dialog box for which IsDialogMessage is called. When a dialog box has scroll bars, the application must provide an alternate keyboard interface for the scroll bars. Note that the mouse interface for scrolling is available when the system includes a mouse.


The WS_TABSTOP Style

The tab key and shift+tab keys have no effect when the controls in the dialog box do not have the WS_TABSTOP style. The system looks for this style as it searches for the next control in the dialog box to receive the input focus.

When the user presses tab or shift+tab, the system first determines whether the control having the input focus processes these keys. It sends the control a WM_GETDLGCODE message, and if the control returns DLGC_WANTTAB, the system passes the keys to the control. Otherwise, the system uses the GetNextDlgTabItem function to locate the next control that is visible, not disabled, and that has the WS_TABSTOP style. The search starts with the control currently having the input focus and proceeds in the order in which the controls were created — that is, the order in which they are defined in the dialog box template. When the system locates a control having the required characteristics, the system moves the input focus to it.

An application can also use GetNextDlgTabItem to locate controls having the WS_TABSTOP style. The function retrieves the window handle of the next or previous control having the WS_TABSTOP style without moving the input focus.


The WS_GROUP Style

By default, the system moves the input focus to the next or previous control whenever the user presses a direction key. As long as the current control with the input focus does not process these keys and the next or previous control is not a static control, the system continues to move the input focus through all controls in the dialog box as the user continues to press the direction keys.

An application can use the WS_GROUP style to modify this default behavior. The style marks the beginning of a group of controls. If a control in the group has the input focus when the user begins pressing direction keys, the focus remains in the group. In general, the first control in a group must have the WS_GROUP style and all other controls in the group must not have this style. All controls in the group must be contiguous — that is, they must have been created consecutively with no intervening controls.

When the user presses a direction key, the system first determines whether the current control having the input focus processes the direction keys. The system sends a WM_GETDLGCODE message to the control and if the control returns the DLGC_WANTARROWS value, passes the key to the control. Otherwise, the system uses the GetNextDlgGroupItem function to determine the next control in the group.

GetNextDlgGroupItem searches controls in the order (or reverse order) they were created. If the user presses the right or down key, GetNextDlgGroupItem returns the next control if that control does not have WS_GROUP style. Otherwise, the function reverses the order of the search and returns the first control that has the WS_GROUP style. If the user presses the left or up key, the function returns the previous control unless the current control already has the WS_GROUP style. If the current control has this style, the function reverses the order of the search, locates the first control having the WS_GROUP style, and returns the control that immediately precedes the located control.

Once the system has the next or previous control, it sends a WM_GETDLGCODE message to the control to determine the control type. The system then moves the input focus to control if it is not a static control. If the control is an automatic radio button, the system sends a BM_CLICK message to it. An application can also use GetNextDlgGroupItem to locate controls in a group.

Generally, the first control in the group combines the WS_GROUP and WS_TABSTOP styles so that the user can move from group to group by using the tab key. If the group contains radio buttons, the application should apply the WS_TABSTOP style only to the first control in the group. The system automatically moves the style when the user moves between controls in the group. This ensures that the input focus will always be on the most recently selected control when the user moves to the group using the tab key.


Mnemonics

A mnemonic is a selected letter or digit in the label of a button or in the text of a static control. The system moves the input focus to the control associated with the mnemonic whenever the user either presses the key that corresponds to the mnemonic or presses this key and the alt key in combination. Mnemonics provide a quick way for the user to move to a given control by using the keyboard.

An application creates a mnemonic for a control by inserting the ampersand (&) immediately before the selected letter or digit in the label or text for the control. In most cases, the null-terminated string provided with the control in the dialog box template contains the ampersand. However, an application can create a mnemonic at any time by replacing a control's existing label or text by using the SetDlgItemText function. Only one mnemonic can be given for each control. Although it is recommended, mnemonics in a dialog box need not be unique.

When the user presses a letter or digit key, the system first determines whether the current control having the input focus processes the key. The system sends a WM_GETDLGCODE message to the control, and if the control returns the DLGC_WANTALLKEYS or DLG_WANTMESSAGE value, the system passes the key to the control. Otherwise, it searches for a control whose mnemonic matches the given letter or digit. It continues to search until it locates a control or has examined all controls. During the search, it skips any static controls that have the SS_NOPREFIX style.

If the system locates a static control and the control is not disabled, the system moves the input focus to the first control after the static control that is visible, not disabled, and that has the WS_TABSTOP style. If the system locates some other control that has a matching mnemonic, it moves the input focus to that control. If the control is a default push button, the system sends a BN_CLICKED notification message to the dialog box procedure. If the control is another style of button and there is no other control in the dialog box having the same mnemonic, the system sends the BM_CLICK message to the control.


Dialog Box Settings

The dialog box settings are the current selections and values for the controls in the dialog box. The dialog box procedure is responsible for initializing the controls to these settings when creating the dialog box. It is also responsible for retrieving the current settings from the controls before destroying the dialog box. The methods used to initialize and retrieve settings depend on the type of control.


Radio Buttons and Check Boxes

Dialog boxes use radio buttons and check boxes to let the user choose from a list of options. Radio buttons let the user choose from mutually exclusive options; check boxes let the user pick a combination of options.

The dialog box procedure can set the initial state of a check box by using the CheckDlgButton function, which sets or clears the check box. For radio buttons in a group of mutually exclusive radio buttons, the dialog box procedure can use the CheckRadioButton function to set the appropriate radio button and automatically clear any other radio button.

Before a dialog box terminates, the dialog box procedure can check the state of each radio button and check box by using the IsDlgButtonChecked function, which returns the current state of the button. A dialog box typically saves this information to initialize the buttons the next time it creates the dialog box.


Dialog Box Edit Controls

Many dialog boxes have edit controls that let the user supply text as input. Most dialog box procedures initialize an edit control when the dialog box first starts. For example, the dialog box procedure may place a proposed filename in the control that the user can then select, modify, or replace. The dialog box procedure can set the text in an edit control by using the SetDlgItemText function, which copies text from a given buffer to the edit control. When the edit control receives the input focus, it automatically selects the complete text for editing.

Because edit controls do not automatically return their text to the dialog box, the dialog box procedure must retrieve the text before it terminates. It can retrieve the text by using the GetDlgItemText function, which copies the edit control text to a buffer. The dialog box procedure typically saves this text to initialize the edit control later or passes it on to the parent window for processing.

Some dialog boxes use edit controls that let the user enter numbers. The dialog box procedure can retrieve a number from an edit control by using the GetDlgItemInt function, which retrieves the text from the edit control and converts the text to a decimal value. The user types the number in decimal digits. It can be either signed or unsigned. The dialog box procedure can display an integer by using the SetDlgItemInt function. SetDlgItemInt converts a signed or unsigned integer to a string of decimal digits.


List Boxes, Combo Boxes, and Directory Listings

Some dialog boxes display lists of names from which the user can select one or more names. To display a list of filenames, for example, a dialog box typically uses a list box and the DlgDirList and DlgDirSelectEx functions. The DlgDirList function automatically fills a list box with the filenames in the current directory. The DlgDirSelect function retrieves the selected filename from the list box. Together, these two functions provide a convenient way for a dialog box to display a directory listing so the user can select a file without having to type its name and location.

A dialog box can also use a combo box to display a list of filenames. The DlgDirListComboBox function automatically fills a list box portion of the combo box with the filenames in the current directory. The DlgDirSelectComboBoxEx function retrieves a selected filename from the list box portion.


Dialog Box Control Messages

Many controls recognize predefined messages that, when received by controls, cause them to carry out some action. For example, the BM_SETCHECK message sets the check in a check box and the EM_GETSEL message retrieves the portion of the control's text that is currently selected. The control messages give a dialog procedure greater and more flexible access to the controls than the standard functions, so they are often used when the dialog box requires complex interactions with the user.

A dialog box procedure can send a message to a control by supplying the control identifier and using the SendDlgItemMessage function, which is identical to the SendMessage function, except that it uses a control identifier instead of a window handle to identify the control that is to receive the message. A given message may require that the dialog procedure send parameters with the message, and the message may have corresponding return values. The operation and requirements of each control message depends on the purpose of the message and the control that processes it.

For more information about the control messages, see Controls.


Custom Dialog Boxes

An application can create custom dialog boxes by using an application-defined window class for the dialog boxes instead of using the predefined dialog box class. Applications typically use this method when a dialog box is their main window, but it is also useful for creating modal and modeless dialog boxes for applications that have standard overlapping windows.

The application-defined window class allows the application to define a window procedure for the dialog box and process messages before sending them to the dialog box procedure. It also lets the application define a class icon, a class background brush, and a class menu for the dialog box. The application must register the window class before attempting to create a dialog box and must provide the dialog box template with the atom value or name of the window class.

Many applications create a new dialog box class by first retrieving the class information for the predefined dialog box class, and passing it to the GetClassInfo function, which fills a WNDCLASS structure with the information. The application modifies individual members of the structure, such as the class name, brush, and icon, then registers the new class by using the RegisterClass function. If an application fills the WNDCLASS structure on its own, it must set the cbWndExtra member to the DLGWINDOWEXTRA, which is the number of extra bytes the system requires for each dialog box. If an application also uses extra bytes for each dialog box, they must be beyond the extra bytes required by the system.

The window procedure for the custom dialog box has the same parameters and requirements as any other window procedure. Unlike other window procedures, however, the window procedure for this dialog box should call the DefDlgProc function instead of the DefWindowProc function for any messages it does not process. DefDlgProc carries out the same default message processing as the window procedure for the predefined dialog box, which includes calling the dialog box procedure.

An application can also create custom dialog boxes by subclassing the window procedure of the predefined dialog box. The SetWindowLong function lets an application set the address of the window procedure for a given window. The application may also attempt to subclass by using the SetClassLong function, but doing so affects all dialog boxes in the system, not just those belonging to the application.

Applications that create custom dialog boxes sometimes provide an alternate keyboard interface for the dialog boxes. For modeless dialog boxes, this may mean the application does not call the IsDialogMessage function and instead processes all keyboard input in the custom window procedure. In such cases, the application can use the WM_NEXTDLGCTL message to minimize the code needed to move the input focus from one control to another. This message, when passed to DefDlgProc, moves the input focus to a specified control and updates the appearance of the controls, such as moving the default push button border or setting an automatic radio button.


Using Dialog Boxes

You use dialog boxes to display information and prompt for input from the user. Your application loads and initializes the dialog box, processes user input, and destroys the dialog box when the user finishes the task. The process for handling dialog boxes varies, depending on whether the dialog box is modal or modeless. A modal dialog box requires the user to close the dialog box before activating another window in the application. However, the user can activate windows in different applications. A modeless dialog box does not require an immediate response from the user. It is similar to a main window containing controls. The following sections discuss how to use both types of dialog boxes.

  • Displaying a message box
  • Creating a modal dialog box
  • Creating a modeless dialog box
  • Initializing a dialog box
  • Creating a template in memory


Displaying a Message Box

The simplest form of modal dialog box is the message box. Most applications use message boxes to warn the user of errors and to prompt for directions on how to proceed after an error has occurred. You create a message box by using the MessageBox or MessageBoxEx function, specifying the message and the number and type of buttons to display. The system creates a modal dialog box, providing its own dialog box template and procedure. After the user closes the message box, MessageBox or MessageBoxEx returns a value identifying the button chosen by the user to close the message box.

In the following example, the application displays a message box if the fError variable is TRUE. The message box displays the message describing the error. The MB_OKCANCEL style directs MessageBox to provide two buttons with which the user can choose how to proceed:

if (fError)
{
    if (MessageBox(hwndDlg, SZNOTFOUND, SZDELETEITEM,
        MB_OKCANCEL)==IDOK)
    {

         // Prompt for a new item name and repeat the command.

    }
    else
    {

         // Cancel the command.

    }
}

In this example, SZNOTFOUND and SZDELETEITEM are application-defined, null-terminated strings that represent the message text and the title for the message box.


Creating a Modal Dialog Box

You create a modal dialog box by using the DialogBox function. You must specify the identifier or name of a dialog box template resource and the address of the dialog box procedure. The DialogBox function loads the template, displays the dialog box, and processes all user input until the user closes the dialog box.

In the following example, the application displays a modal dialog box when the user chooses a Delete Item command from an application menu. The dialog box contains an edit control (in which the user enters the name of an item) and OK and Cancel buttons. The control identifiers for these controls are ID_ITEMNAME, IDOK, and IDCANCEL, respectively.

The first part of the example consists of the statements that create the modal dialog box. These statements, in the window procedure for the application's main window, create the dialog box when the system receives a WM_COMMAND message having the IDM_DELETEITEM command identifier. The second part of the example is the dialog box procedure, which retrieves the contents of the edit control and closes the dialog box upon receiving a WM_COMMAND message.

The following statements create the modal dialog box. The dialog box template is a resource in the application's executable file and has the resource identifier DLG_DELETEITEM:

case WM_COMMAND:
        switch (LOWORD(wParam))
        {
            case IDM_DELETEITEM:
                if (DialogBox(hinst,
                     MAKEINTRESOURCE(DLG_DELETEITEM),
                     hwnd, (DLGPROC)DeleteItemProc)==IDOK)
                {

                    // Complete the command; szItemName
                    // contains the name of the item to
                    // delete.

                }

                else
                {

                    // Cancel the command.

                }
                break;
        }
        return 0L;

In this example, the application identifies its main window as the owner window for the dialog box. When the system initially displays the dialog box, its position is relative to the upper left corner of the owner window's client area. The application uses the return value from DialogBox to determine whether to proceed with the command or cancel it. The following statements define the dialog box procedure.

char szItemName[80]; // receives name of item to delete.

BOOL CALLBACK DeleteItemProc(hwndDlg, message, wParam, lParam)
HWND hwndDlg;
UINT message;
WPARAM wParam;
LPARAM lParam;
{
    switch (message)
    {
        case WM_COMMAND:
            switch (LOWORD(wParam))
            {
                case IDOK:
                    if (!GetDlgItemText(hwndDlg, ID_ITEMNAME,
                             szItemName, 80))
                         *szItemName=0;

                    // Fall through.

                case IDCANCEL:
                    EndDialog(hwndDlg, wParam);
                    return TRUE;
            }
    }
    return FALSE;
}

In this example, the procedure uses GetDlgItemText to retrieve the current text from the edit control identified by ID_ITEMNAME. The procedure then calls the EndDialog function to set the dialog box's return value to either IDOK or IDCANCEL, depending on the message received, and to begin the process of closing the dialog box. The IDOK and IDCANCEL identifiers correspond to the OK and Cancel buttons. After the procedure calls EndDialog, the system sends additional messages to the procedure to destroy the dialog box and returns the dialog box's return value back to the function that created the dialog box.


Creating a Modeless Dialog Box

You create a modeless dialog box by using the CreateDialog function, specifying the identifier or name of a dialog box template resource and the address of the dialog box procedure. CreateDialog loads the template, creates the dialog box, and optionally displays it. Your application is responsible for retrieving and dispatching user input messages to the dialog box procedure.

In the following example, the application displays a modeless dialog box — if it is not already displayed — when the user chooses a Go To command from an application menu. The dialog box contains an edit control, a check box, and OK and Cancel buttons. The dialog box template is a resource in the application's executable file and has the resource identifier DLG_GOTO. The user enters a line number in the edit control and checks the check box to specify that the line number is relative to the current line. The control identifiers are ID_LINE, ID_ABSREL, IDOK, and IDCANCEL.

The statements in the first part of the example create the modeless dialog box. These statements, in the window procedure for the application's main window, create the dialog box when the window procedure receives a WM_COMMAND message having the IDM_GOTO command identifier, but only if the global variable hwndGoto does not already contain a valid handle. The second part of the example is the application's main message loop. The loop includes the IsDialogMessage function to ensure that the user can use the dialog box keyboard interface in this modeless dialog box. The third part of the example is the dialog box procedure. The procedure retrieves the contents of the edit control and check box when the user chooses the OK button. The procedure destroys the dialog box when the user chooses the Cancel button.

HWND hwndGoto = NULL;  // window handle of dialog box

    .
    .
    .

    case WM_COMMAND:
        switch (LOWORD(wParam))
        {
            case IDM_GOTO:
                if (!IsWindow(hwndGoto))
                {
                    hwndGoto = CreateDialog(hinst,
                         MAKEINTRESOURCE(DLG_GOTO),
                         hwnd, (DLGPROC) GoToProc);
                    ShowWindow(hwndGoto, SW_SHOW);
                }
                break;
        }
        return 0L;

In the preceding statements, CreateDialog is called only if hwndGoto does not contain a valid window handle. This ensures that the application does not display two dialog boxes at the same time. To support this method of checking, the dialog procedure must set hwndGoto to NULL when it destroys the dialog box.

The message loop for an application consists of the following statements:

while (GetMessage(&msg, NULL, NULL, NULL))
{
    if (!IsWindow(hwndGoto) || !IsDialogMessage(hwndGoto, &msg))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}

The loop checks the validity of the window handle for the dialog box and only calls the IsDialogMessage function if the handle is valid. IsDialogMessage only processes the message if it belongs to the dialog box. Otherwise, it returns FALSE and the loop dispatches the message to the appropriate window.

The following statements define the dialog box procedure:

int iLine;             // receives line number
BOOL fRelative;        // receives check box status

BOOL CALLBACK GoToProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
    BOOL fError;

    switch (message)
    {
        case WM_INITDIALOG:
            CheckDlgButton(hwndDlg, ID_ABSREL, fRelative);
            return TRUE;

        case WM_COMMAND:
            switch (LOWORD(wParam))
            {
                case IDOK:
                    fRelative = IsDlgButtonChecked(hwndDlg,
                        ID_ABSREL);
                    iLine = GetDlgItemInt(hwndDlg, ID_LINE,
                        &fError, fRelative);
                    if (fError)
                    {
                        MessageBox(hwndDlg, SZINVALIDNUMBER,
                            SZGOTOERR, MB_OK);
                        SendDlgItemMessage(hwndDlg, ID_LINE,
                            EM_SETSEL, 0, -1L);
                    }
                    else

                        // Notify the owner window to carry
                        // out the command.

                    return TRUE;

                case IDCANCEL:
                    DestroyWindow(hwndDlg);
                    hwndGoto = NULL;
                    return TRUE;
            }
    }
    return FALSE;
}

In the preceding statements, the procedure processes the WM_INITDIALOG and WM_COMMAND messages. During WM_INITDIALOG processing, the procedure initializes the check box by passing the current value of the global variable fRelative to CheckDlgButton. The procedure then returns TRUE to direct the system to set the default input focus.

During WM_COMMAND processing, the procedure closes the dialog box only if the user chooses the Cancel button — that is, the button having the IDCANCEL identifier. The procedure must call DestroyWindow to close a modeless dialog box. Notice that the procedure also sets the hwndGoto variable to NULL to ensure that other statements that depend on this variable operate correctly.

If the user chooses the OK button, the procedure retrieves the current state of the check box and assigns it to the fRelative variable. It then uses the variable to retrieve the line number from the edit control. GetDlgItemInt translates the text in the edit control into an integer. The value of fRelative determines whether the function interprets the number as a signed or unsigned value. If the edit control text is not a valid number, GetDlgItemInt sets the value of the fError variable to nonzero. The procedure checks this value to determine whether to display an error message or carry out the command. In the event of an error, the dialog box procedure sends a message to the edit control, directing it to select the text in the control so that the user can easily replace it. If GetDlgItemInt does not return an error, the procedure can either carry out the requested command itself or send a message to the owner window, directing it to carry out the command.


Initializing a Dialog Box

You initialize the dialog box and its contents while processing the WM_INITDIALOG message. The most common task is to initialize the controls to reflect the current dialog box settings. Another common task is to center a dialog box on the screen or within its owner window. A useful task for some dialog boxes is to set the input focus to a given control rather than accept the default input focus.

In the following example, the dialog box procedure centers the dialog box and sets the input focus while processing the WM_INITDIALOG message. To center the dialog box, the procedure retrieves the window rectangles for the dialog box and the owner window and calculates a new position for the dialog box. To set the input focus, the procedure checks the wParam parameter to determine the identifier of the default input focus:

HWND hwndOwner;
RECT rc, rcDlg, rcOwner;

    case WM_INITDIALOG:

        // Get the owner window and dialog box rectangles.

        if ((hwndOwner = GetParent(hwndDlg)) == NULL)
        {
            hwndOwner = GetDesktopWindow();
        }

        GetWindowRect(hwndOwner, &rcOwner);
        GetWindowRect(hwndDlg, &rcDlg);
        CopyRect(&rc, &rcOwner);

         // Offset the owner and dialog box rectangles so that
         // right and bottom values represent the width and
         // height, and then offset the owner again to discard
         // space taken up by the dialog box.

        OffsetRect(&rcDlg, -rcDlg.left, -rcDlg.top);
        OffsetRect(&rc, -rc.left, -rc.top);
        OffsetRect(&rc, -rcDlg.right, -rcDlg.bottom);

         // The new position is the sum of half the remaining
         // space and the owner's original position.

        SetWindowPos(hwndDlg,
            HWND_TOP,
            rcOwner.left + (rc.right / 2),
            rcOwner.top + (rc.bottom / 2),
            0, 0,          // ignores size arguments
            SWP_NOSIZE);

        if (GetDlgCtrlID((HWND) wParam) != ID_ITEMNAME)
        {
            SetFocus(GetDlgItem(hwndDlg, ID_ITEMNAME));
            return FALSE;
        }
        return TRUE;

In the preceding statements, the procedure uses the GetParent function to retrieve the owner window handle for a dialog box. The function returns the owner window handle for dialog boxes, and the parent window handle for child windows. Because an application can create a dialog box that has no owner, the procedure checks the returned handle and uses the GetDesktopWindow function to retrieve the desktop window handle, if necessary. After calculating the new position, the procedure uses the SetWindowPos function to move the dialog box, specifying the HWND_TOP value to ensure that the dialog box remains on top of the owner window.

Before setting the input focus, the procedure checks the control identifier of the default input focus. The system passes the window handle of the default input focus in the wParam parameter. The GetDlgCtrlID function returns the identifier for the control identified by the window handle. If the identifier does not match the correct identifier, the procedure uses the SetFocus function to set the input focus. The GetDlgItem function is required to retrieve the window handle of the desired control.


Creating a Template in Memory

Applications sometimes adapt or modify the content of dialog boxes depending on the current state of the data being processed. In such cases, it is not practical to provide all possible dialog box templates as resources in the application's executable file. But creating templates in memory gives the application more flexibility to adapt to any circumstances.

In the following example, the application creates a template in memory for a modal dialog box that contains a message and OK and Help buttons.

In a dialog template, all character strings, such as the dialog box and button titles, must be Unicode strings. This example uses the MultiByteToWideChar function to generate these Unicode strings, because both Windows and Windows NT support MultiByteToWideChar

The DLGITEMTEMPLATE structures in a dialog template must be aligned on DWORD boundaries. To align these structures, this example uses a helper routine that takes an input pointer and returns the closest pointer that is aligned on a DWORD (4 byte) boundary.

#define ID_HELP   150
#define ID_TEXT   200

LPWORD lpwAlign ( LPWORD lpIn)
{
    ULONG ul;

    ul = (ULONG) lpIn;
    ul +=3;
    ul >>=2;
    ul <<=2;
    return (LPWORD) ul;
}

LRESULT DisplayMyMessage(HINSTANCE hinst, HWND hwndOwner,
    LPSTR lpszMessage)
{
    HGLOBAL hgbl;
    LPDLGTEMPLATE lpdt;
    LPDLGITEMTEMPLATE lpdit;
    LPWORD lpw;
    LPWSTR lpwsz;
    LRESULT ret;
    int nchar;

    hgbl = GlobalAlloc(GMEM_ZEROINIT, 1024);
    if (!hgbl)
        return -1;

    lpdt = (LPDLGTEMPLATE)GlobalLock(hgbl);

    // Define a dialog box.

    lpdt->style = WS_POPUP | WS_BORDER | WS_SYSMENU
                   | DS_MODALFRAME | WS_CAPTION;
    lpdt->cdit = 3;  // number of controls
    lpdt->x  = 10;  lpdt->y  = 10;
    lpdt->cx = 100; lpdt->cy = 100;

    lpw = (LPWORD) (lpdt + 1);
    *lpw++ = 0;   // no menu
    *lpw++ = 0;   // predefined dialog box class (by default)

    lpwsz = (LPWSTR) lpw;
    nchar = 1+ MultiByteToWideChar (CP_ACP, 0, "My Dialog",
                                    -1, lpwsz, 50);
    lpw   += nchar;

    //-----------------------
    // Define an OK button.
    //-----------------------
    lpw = lpwAlign (lpw); // align DLGITEMTEMPLATE on DWORD boundary
    lpdit = (LPDLGITEMTEMPLATE) lpw;
    lpdit->x  = 10; lpdit->y  = 70;
    lpdit->cx = 80; lpdit->cy = 20;
    lpdit->id = IDOK;  // OK button identifier
    lpdit->style = WS_CHILD | WS_VISIBLE | BS_DEFPUSHBUTTON;

    lpw = (LPWORD) (lpdit + 1);
    *lpw++ = 0xFFFF;
    *lpw++ = 0x0080;    // button class

    lpwsz = (LPWSTR) lpw;
    nchar = 1+MultiByteToWideChar (CP_ACP, 0, "OK", -1, lpwsz, 50);
    lpw   += nchar;
    lpw = lpwAlign (lpw); // align creation data on DWORD boundary
    *lpw++ = 0;           // no creation data

    //-----------------------
    // Define a Help button.
    //-----------------------
    lpw = lpwAlign (lpw); // align DLGITEMTEMPLATE on DWORD boundary
    lpdit = (LPDLGITEMTEMPLATE) lpw;
    lpdit->x  = 55; lpdit->y  = 10;
    lpdit->cx = 40; lpdit->cy = 20;
    lpdit->id = ID_HELP;    // Help button identifier
    lpdit->style = WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON;

    lpw = (LPWORD) (lpdit + 1);
    *lpw++ = 0xFFFF;
    *lpw++ = 0x0080;                 // button class atom

    lpwsz = (LPWSTR) lpw;
    nchar = 1+MultiByteToWideChar (CP_ACP, 0, "Help", -1, lpwsz, 50);
    lpw   += nchar;
    lpw = lpwAlign (lpw); // align creation data on DWORD boundary
    *lpw++ = 0;           // no creation data

    //-----------------------
    // Define a static text control.
    //-----------------------
    lpw = lpwAlign (lpw); // align DLGITEMTEMPLATE on DWORD boundary
    lpdit = (LPDLGITEMTEMPLATE) lpw;
    lpdit->x  = 10; lpdit->y  = 10;
    lpdit->cx = 40; lpdit->cy = 20;
    lpdit->id = ID_TEXT;  // text identifier
    lpdit->style = WS_CHILD | WS_VISIBLE | SS_LEFT;

    lpw = (LPWORD) (lpdit + 1);
    *lpw++ = 0xFFFF;
    *lpw++ = 0x0082;                         // static class

    for (lpwsz = (LPWSTR)lpw;
        *lpwsz++ = (WCHAR) *lpszMessage++;
    );
    lpw = (LPWORD)lpwsz;
    lpw = lpwAlign (lpw); // align creation data on DWORD boundary
    *lpw++ = 0;           // no creation data

    GlobalUnlock(hgbl);
    ret = DialogBoxIndirect(hinst, (LPDLGTEMPLATE) hgbl,
        hwndOwner, (DLGPROC) DialogProc);
    GlobalFree(hgbl);
    return ret;
}


Dialog Box Reference

The following elements are associated with dialog boxes.

  • Dialog Box Functions
  • Dialog Box Structures
  • Dialog Box Messages


Dialog Box Functions

The following functions are used to create and manage dialog boxes and controls within dialog boxes.

CreateDialog
CreateDialogIndirect
CreateDialogIndirectParam
CreateDialogParam
DefDlgProc
DialogBox
DialogBoxIndirect
DialogBoxIndirectParam
DialogBoxParam
DialogProc
EndDialog
GetDialogBaseUnits
GetDlgCtrlID
GetDlgItem
GetDlgItemInt
GetDlgItemText
GetNextDlgGroupItem
GetNextDlgTabItem
IsDialogMessage
MapDialogRect
MessageBox
MessageBoxEx
SendDlgItemMessage
SetDlgItemInt
SetDlgItemText
MessageBoxIndirect


CreateDialog

The CreateDialog macro creates a modeless dialog box from a dialog box template resource. The CreateDialog macro uses the CreateDialogParam function.

HWND CreateDialog(
  HINSTANCE hInstance,  // handle to application instance
  LPCTSTR lpTemplate,   // identifies dialog box template name
  HWND hWndParent,      // handle to owner window
  DLGPROC lpDialogFunc  // pointer to dialog box procedure
);

Parameters

hInstance
Identifies an instance of the module whose executable file contains the dialog box template.
lpTemplate
Identifies 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 low-order word must contain the identifier. You can use the MAKEINTRESOURCE macro to create this value.
hWndParent
Identifies the window that owns the dialog box.
lpDialogFunc
Pointer to the dialog box procedure. For more information about the dialog box procedure, see DialogProc.

Return Values

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.

Remarks

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 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.

Windows 95 and later: The system can support a maximum of 255 controls per dialog box template. To place more than 255 controls in a dialog box, create the controls in the WM_INITDIALOG message handler rather than placing them in the template.

Windows CE: Not all styles are supported in the DLGTEMPLATE structure in the dialog template referred to by the lpTemplate parameter.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Dialog Boxes Overview, Dialog Box Functions, CreateDialogIndirect, CreateDialogIndirectParam, CreateDialogParam, CreateWindowEx, DestroyWindow, DialogBox, DialogProc, ShowWindow, WM_INITDIALOG, WM_SETFONT


CreateDialogIndirect

The CreateDialogIndirect macro creates a modeless dialog box from a dialog box template in memory. The CreateDialogIndirect macro uses the CreateDialogIndirectParam function.

HWND CreateDialogIndirect(
  HINSTANCE hInstance,        // handle to application instance
  LPCDLGTEMPLATE lpTemplate,  // pointer to dialog box template
  HWND hWndParent,            // handle to owner window
  DLGPROC lpDialogFunc        // pointer to dialog box procedure
);

Parameters

hInstance
Identifies the instance of the module that creates the dialog box.
lpTemplate
Pointer to a global memory object containing a template that CreateDialogIndirect uses to create the dialog box. A dialog box template 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.

After CreateDialogIndirect returns, you can free the template, which is only used to get the dialog box started.

hWndParent
Identifies the window that owns the dialog box.
lpDialogFunc
Pointer to the dialog box procedure. For more information about the dialog box procedure, see DialogProc.

Return Values

If the function succeeds, the return value is the window handle to the dialog box.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The CreateDialogIndirect macro uses the CreateWindowEx function to create the dialog box. CreateDialogIndirect then sends a WM_INITDIALOG message to the dialog box procedure. If the template specifies the DS_SETFONT style, the function also sends a WM_SETFONT message to the dialog box procedure. The function displays the dialog box if the template specifies the WS_VISIBLE style. Finally, CreateDialogIndirect returns the window handle to the dialog box.

After CreateDialogIndirect returns, you can use the ShowWindow function to display the dialog box (if it is not already visible). To destroy the dialog box, use the DestroyWindow function.

In a standard dialog box template, the DLGTEMPLATE structure and each of the DLGITEMTEMPLATE structures must be aligned on DWORD boundaries. The creation data array that follows a DLGITEMTEMPLATE structure must also be aligned on a DWORD boundary. All of the other variable-length arrays in the template must must be aligned on WORD boundaries.

In an extended dialog box template, the DLGTEMPLATEEX header and each of the DLGITEMTEMPLATEEX control definitions must be aligned on DWORD boundaries. The creation data array, if any, that follows a DLGITEMTEMPLATEEX structure must also be aligned on a DWORD boundary. All of the other variable-length arrays in the template must be aligned on WORD boundaries.

All character strings in the dialog box template, such as titles for the dialog box and buttons, must be Unicode strings. To create code that works on both Windows and Windows NT, use the MultiByteToWideChar function to generate these Unicode strings.

Windows 95 and later: The system can support a maximum of 255 controls per dialog box template. To place more than 255 controls in a dialog box, create the controls in the WM_INITDIALOG message handler rather than placing them in the template.

Windows CE: Not all styles are supported in the DLGTEMPLATE structure in the dialog template referred to by the lpTemplate parameter.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Dialog Boxes Overview, Dialog Box Functions, CreateDialog, CreateDialogIndirectParam, CreateDialogParam, CreateWindowEx, DestroyWindow, DialogProc, DLGITEMTEMPLATE, DLGITEMTEMPLATEEX, DLGTEMPLATE, DLGTEMPLATEEX, MultiByteToWideChar, ShowWindow, WM_INITDIALOG, WM_SETFONT


CreateDialogIndirectParam

The CreateDialogIndirectParam function creates a modeless dialog box from a dialog box template in memory. 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.

HWND CreateDialogIndirectParam(
  HINSTANCE hInstance,        // handle to application instance
  LPCDLGTEMPLATE lpTemplate,  // pointer to dialog box template
  HWND hWndParent,            // handle to owner window
  DLGPROC lpDialogFunc,       // pointer to dialog box procedure
  LPARAM lParamInit           // initialization value
);

Parameters

hInstance
Identifies the instance of the module that will create the dialog box.
lpTemplate
Pointer to a global memory object containing a template that CreateDialogIndirectParam uses to create the dialog box. A dialog box template 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.

After CreateDialogIndirectParam returns, you can free the template, which is only used to get the dialog box started.

hWndParent
Identifies the window that owns the dialog box.
lpDialogFunc
Pointer to the dialog box procedure. For more information about the dialog box procedure, see DialogProc.
lParamInit
Specifies the value to pass to the dialog box in the lParam parameter of the WM_INITDIALOG message.

Return Values

If the function succeeds, the return value is the window handle to the dialog box.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The CreateDialogIndirectParam function uses the CreateWindowEx function to create the dialog box. CreateDialogIndirectParam then sends a WM_INITDIALOG message to the dialog box procedure. If the template specifies the DS_SETFONT style, the function also sends a WM_SETFONT message to the dialog box procedure. The function displays the dialog box if the template specifies the WS_VISIBLE style. Finally, CreateDialogIndirectParam returns the window handle to the dialog box.

After CreateDialogIndirectParam returns, you can use the ShowWindow function to display the dialog box (if it is not already visible). To destroy the dialog box, use the DestroyWindow function.

In a standard dialog box template, the DLGTEMPLATE structure and each of the DLGITEMTEMPLATE structures must be aligned on DWORD boundaries. The creation data array that follows a DLGITEMTEMPLATE structure must also be aligned on a DWORD boundary. All of the other variable-length arrays in the template must must be aligned on WORD boundaries.

In an extended dialog box template, the DLGTEMPLATEEX header and each of the DLGITEMTEMPLATEEX control definitions must be aligned on DWORD boundaries. The creation data array, if any, that follows a DLGITEMTEMPLATEEX structure must also be aligned on a DWORD boundary. All of the other variable-length arrays in the template must be aligned on WORD boundaries.

All character strings in the dialog box template, such as titles for the dialog box and buttons, must be Unicode strings. To create code that works on both Windows and Windows NT, use the MultiByteToWideChar function to generate these Unicode strings.

Windows 95 and later: The system can support a maximum of 255 controls per dialog box template. To place more than 255 controls in a dialog box, create the controls in the WM_INITDIALOG message handler rather than placing them in the template.

Windows CE: Dialog boxes outside the visible area of the screen are not automatically repositioned.

If the user presses ALT+H while the dialog box has the input focus, the system posts a WM_HELP message to the dialog procedure. An application should respond to this message by displaying context-sensitive help for the dialog box.

The following styles are not supported for the style member of the DLGTEMPLATE structure:

  • DS_SETFONT: You cannot set the font inside dialog boxes.
  • DS_3DLOOK
  • DS_RECURSE: Not required. Any child dialog box is automatically considered to be a recursive dialog box.
  • DS_CONTROL: Not required.
  • WS_EX_CONTROLPARENT: All dialog boxes are automatically assumed to be control parents.

To get default positioning, use the DS_CENTER style.

If the WS_CHILD style is not specified, the WS_POPUP style is assumed.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Dialog Boxes Overview, Dialog Box Functions, CreateDialog, CreateDialogIndirect, CreateDialogParam, CreateWindowEx, DestroyWindow, DialogProc, DLGITEMTEMPLATE, DLGITEMTEMPLATEEX, DLGTEMPLATE, DLGTEMPLATEEX, MultiByteToWideChar, ShowWindow, WM_INITDIALOG, WM_SETFONT


CreateDialogParam

The CreateDialogParam function creates a modeless 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 the WM_INITDIALOG message. An application can use this value to initialize dialog box controls.

HWND CreateDialogParam(
  HINSTANCE hInstance,  // handle to application instance
  LPCTSTR lpTemplateName,  // identifies dialog box template
  HWND hWndParent,      // handle to owner window
  DLGPROC lpDialogFunc, // pointer to dialog box procedure
  LPARAM dwInitParam    // initialization value
);

Parameters

hInstance
Identifies an instance of the module whose executable file contains the dialog box template.
lpTemplateName
Identifies 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 low-order word must contain the identifier. You can use the MAKEINTRESOURCE macro to create this value.
hWndParent
Identifies 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 procedure in the lParam parameter in the WM_INITDIALOG message.

Return Values

If the function succeeds, the return value is the window handle to the dialog box.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The CreateDialogParam function uses the CreateWindowEx function to create the dialog box. CreateDialogParam then sends a WM_INITDIALOG message (and a WM_SETFONT message if the template specifies the DS_SETFONT style) to the dialog box procedure. The function displays the dialog box if the template specifies the WS_VISIBLE style. Finally, CreateDialogParam returns the window handle of the dialog box.

After CreateDialogParam 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.

Windows 95 and later: The system can support a maximum of 255 controls per dialog box template. To place more than 255 controls in a dialog box, create the controls in the WM_INITDIALOG message handler rather than placing them in the template.

Windows CE: Not all styles are supported in the DLGTEMPLATE structure in the dialog template referred to by the lpTemplateName parameter.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Dialog Boxes Overview, Dialog Box Functions, CreateDialog, CreateDialogIndirect, CreateDialogIndirectParam, CreateWindowEx, DestroyWindow, DialogProc, MAKEINTRESOURCE, ShowWindow, WM_INITDIALOG, WM_SETFONT


DefDlgProc

The DefDlgProc function carries out default message processing for a window procedure belonging to an application-defined dialog box class.

LRESULT DefDlgProc(
  HWND hDlg,      // handle to dialog box
  UINT Msg,       // message
  WPARAM wParam,  // first message parameter
  LPARAM lParam   // second message parameter
);

Parameters

hDlg
Identifies the dialog box.
Msg
Specifies the message number.
wParam
Specifies additional message-specific information.
lParam
Specifies additional message-specific information.

Return Values

The return value specifies the result of the message processing and depends on the message sent.

Remarks

The DefDlgProc function is the window procedure for the predefined class of dialog box. This procedure provides internal processing for the dialog box by forwarding messages to the dialog box procedure and carrying out default processing for any messages that the dialog box procedure returns as FALSE. Applications that create custom window procedures for their custom dialog boxes often use DefDlgProc instead of the DefWindowProc function to carry out default message processing.

Applications create custom dialog box classes by filling a WNDCLASS structure with appropriate information and registering the class with the RegisterClass function. Some applications fill the structure by using the GetClassInfo function, specifying the name of the predefined dialog box. In such cases, the applications modify at least the lpszClassName member before registering. In all cases, the cbWndExtra member of WNDCLASS for a custom dialog box class must be set to at least DLGWINDOWEXTRA.

The DefDlgProc function must not be called by a dialog box procedure; doing so results in recursive execution.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Dialog Boxes Overview, Dialog Box Functions, DefWindowProc, GetClassInfo, RegisterClass, WNDCLASS


DialogBox

The DialogBox macro creates a modal dialog box from a dialog box template resource. DialogBox does not return control until the specified callback function terminates the modal dialog box by calling the EndDialog function. The DialogBox macro uses the DialogBoxParam function.

int DialogBox(
  HINSTANCE hInstance,  // handle to application instance
  LPCTSTR lpTemplate,   // identifies dialog box template
  HWND hWndParent,      // handle to owner window
  DLGPROC lpDialogFunc  // pointer to dialog box procedure
);

Parameters

hInstance
Identifies an instance of the module whose executable file contains the dialog box template.
lpTemplate
Identifies 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 low-order word must contain the identifier. You can use the MAKEINTRESOURCE macro to create this value.
hWndParent
Identifies the window that owns the dialog box.
lpDialogFunc
Pointer to the dialog box procedure. For more information about the dialog box procedure, see DialogProc.

Return Values

If the function succeeds, the return value is the nResult parameter in the call to the EndDialog function used to terminate the dialog box.

If the function fails, the return value is –1. To get extended error information, call GetLastError.

Remarks

The DialogBox macro uses the CreateWindowEx function to create the dialog box. DialogBox then sends a WM_INITDIALOG message (and a WM_SETFONT message if the template specifies the DS_SETFONT 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, DialogBox 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.

Windows 95 and later: The system can support a maximum of 255 controls per dialog box template. To place more than 255 controls in a dialog box, create the controls in the WM_INITDIALOG message handler rather than placing them in the template.

Windows CE: Not all styles are supported in the DLGTEMPLATE structure in the dialog template referred to by the lpTemplate parameter.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Dialog Boxes Overview, Dialog Box Functions, CreateDialog, CreateWindowEx, DialogBoxIndirect, DialogBoxIndirectParam, DialogBoxParam, DialogProc, EndDialog, MAKEINTRESOURCE, WM_INITDIALOG, WM_SETFONT


DialogBoxIndirect

The DialogBoxIndirect macro creates a modal dialog box from a dialog box template in memory. DialogBoxIndirect does not return control until the specified callback function terminates the modal dialog box by calling the EndDialog function. The DialogBoxIndirect macro uses the DialogBoxIndirectParam function.

int DialogBoxIndirect(
  HINSTANCE hInstance,   // handle to application instance
  LPDLGTEMPLATE lpTemplate,  // identifies dialog box template
  HWND hWndParent,       // handle to owner window
  DLGPROC lpDialogFunc   // pointer to dialog box procedure
);

Parameters

hInstance
Identifies the instance of the module that creates the dialog box.
lpTemplate
Pointer to a global memory object containing a template that DialogBoxIndirect uses to create the dialog box. A dialog box template 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 for a dialog box, 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 template for a dialog box, the header uses the DLGTEMPLATEEX format and the control definitions use the DLGITEMTEMPLATEEX format.

hWndParent
Identifies the window that owns the dialog box.
lpDialogFunc
Pointer to the dialog box procedure. For more information about the dialog box procedure, see DialogProc.

Return Values

If the function succeeds, the return value is the nResult parameter specified in the call to the EndDialog function that was used to terminate the dialog box.

If the function fails, the return value is –1. To get extended error information, call GetLastError.

Remarks

The DialogBoxIndirect macro uses the CreateWindowEx function to create the dialog box. DialogBoxIndirect then sends a WM_INITDIALOG message to the dialog box procedure. If the template specifies the DS_SETFONT style, the function also sends a WM_SETFONT message 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, DialogBoxIndirect 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.

In a standard dialog box template, the DLGTEMPLATE structure and each of the DLGITEMTEMPLATE structures must be aligned on DWORD boundaries. The creation data array that follows a DLGITEMTEMPLATE structure must also be aligned on a DWORD boundary. All of the other variable-length arrays in the template must must be aligned on WORD boundaries.

In an extended dialog box template, the DLGTEMPLATEEX header and each of the DLGITEMTEMPLATEEX control definitions must be aligned on DWORD boundaries. The creation data array, if any, that follows a DLGITEMTEMPLATEEX structure must also be aligned on a DWORD boundary. All of the other variable-length arrays in the template must be aligned on WORD boundaries.

All character strings in the dialog box template, such as titles for the dialog box and buttons, must be Unicode strings. To create code that works on both Windows and Windows NT, use the MultiByteToWideChar function to generate these Unicode strings.

Windows 95 and later: The system can support a maximum of 255 controls per dialog box template. To place more than 255 controls in a dialog box, create the controls in the WM_INITDIALOG message handler rather than placing them in the template.

Windows CE: Not all styles are supported in the DLGTEMPLATE structure in the dialog template referred to by the lpTemplate parameter.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Dialog Boxes Overview, Dialog Box Functions, CreateWindowEx, DialogBox, DialogBoxIndirectParam, DialogBoxParam, DialogProc, DLGITEMTEMPLATE, DLGITEMTEMPLATEEX, DLGTEMPLATE, DLGTEMPLATEEX, EndDialog, MultiByteToWideChar, WM_INITDIALOG, WM_SETFONT


DialogBoxIndirectParam

The DialogBoxIndirectParam function creates a modal dialog box from a dialog box template in memory. 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 DialogBoxIndirectParam(
  HINSTANCE hInstance,  // handle to application instance
  LPCDLGTEMPLATE hDialogTemplate,
                        // identifies dialog box template
  HWND hWndParent,      // handle to owner window
  DLGPROC lpDialogFunc, // pointer to dialog box procedure
  LPARAM dwInitParam    // initialization value
);

Parameters

hInstance
Identifies the instance of the module that creates the dialog box.
hDialogTemplate
Pointer to a global memory object containing a template that DialogBoxIndirectParam uses to create the dialog box. A dialog box template 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 for a dialog box, 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 template for a dialog box, the header uses the DLGTEMPLATEEX format and the control definitions use the DLGITEMTEMPLATEEX format.

hWndParent
Identifies 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 Values

If the function succeeds, the return value is the nResult parameter specified in the call to the EndDialog function that was used to terminate the dialog box.

If the function fails, the return value is –1. To get extended error information, call GetLastError.

Remarks

The DialogBoxIndirectParam function uses the CreateWindowEx function to create the dialog box. DialogBoxIndirectParam then sends a WM_INITDIALOG message to the dialog box procedure. If the template specifies the DS_SETFONT style, the function also sends a WM_SETFONT message 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, DialogBoxIndirectParam 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.

In a standard dialog box template, the DLGTEMPLATE structure and each of the DLGITEMTEMPLATE structures must be aligned on DWORD boundaries. The creation data array that follows a DLGITEMTEMPLATE structure must also be aligned on a DWORD boundary. All of the other variable-length arrays in the template must must be aligned on WORD boundaries.

In an extended dialog box template, the DLGTEMPLATEEX header and each of the DLGITEMTEMPLATEEX control definitions must be aligned on DWORD boundaries. The creation data array, if any, that follows a DLGITEMTEMPLATEEX structure must also be aligned on a DWORD boundary. All of the other variable-length arrays in the template must be aligned on WORD boundaries.

All character strings in the dialog box template, such as titles for the dialog box and buttons, must be Unicode strings. To create code that works on both Windows and Windows NT, use the MultiByteToWideChar function to generate these Unicode strings.

Windows 95 and later: The system can support a maximum of 255 controls per dialog box template. To place more than 255 controls in a dialog box, create the controls in the WM_INITDIALOG message handler rather than placing them in the template.

Windows CE: If the user presses ALT+H while the dialog box has the input focus, the system posts a WM_HELP message to the dialog procedure. An application should respond to this message by displaying context-sensitive Help for the dialog box.

For other dialog restrictions, see CreateDialogIndirectParam.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Dialog Boxes Overview, Dialog Box Functions, CreateWindowEx, DialogBox, DialogBoxIndirect, DialogBoxParam, DialogProc, DLGITEMTEMPLATE, DLGITEMTEMPLATEEX, DLGTEMPLATE, DLGTEMPLATEEX, EndDialog, MultiByteToWideChar, WM_INITDIALOG, WM_SETFONT


DialogBoxParam

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 DialogBoxParam(
  HINSTANCE hInstance,  // handle to application instance
  LPCTSTR lpTemplateName,  // identifies dialog box template
  HWND hWndParent,      // handle to owner window
  DLGPROC lpDialogFunc, // pointer to dialog box procedure
  LPARAM dwInitParam    // initialization value
);

Parameters

hInstance
Identifies an instance of the module whose executable file contains the dialog box template.
lpTemplateName
Identifies 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 low-order word must contain the identifier. You can use the MAKEINTRESOURCE macro to create this value.
hWndParent
Identifies 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 Values

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, the return value is –1. To get extended error information, call GetLastError.

Remarks

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 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.

Windows 95 and later: The system can support a maximum of 255 controls per dialog box template. To place more than 255 controls in a dialog box, create the controls in the WM_INITDIALOG message handler rather than placing them in the template.

Windows CE: Not all styles are supported in the DLGTEMPLATE structure in the dialog template referred to by the lpTemplateName parameter.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Dialog Boxes Overview, Dialog Box Functions, CreateWindowEx, DialogBox, DialogBoxIndirect, DialogBoxIndirectParam, DialogProc, EndDialog, MAKEINTRESOURCE, WM_INITDIALOG, WM_SETFONT


DialogProc

The DialogProc function is an application-defined callback function used with the DialogBox function. 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.

BOOL CALLBACK DialogProc(
  HWND hwndDlg,  // handle to dialog box
  UINT uMsg,     // message
  WPARAM wParam, // first message parameter
  LPARAM lParam  // second message parameter
);

Parameters

hwndDlg
Identifies the dialog box.
uMsg
Specifies the message.
wParam
Specifies additional message-specific information.
lParam
Specifies additional message-specific information.

Return Values

Except in response to the WM_INITDIALOG message, the dialog box procedure should return nonzero if it processes the message, and zero if it does not. In response to a WM_INITDIALOG message, the dialog box procedure should return zero if it calls the SetFocus function to set the focus to one of the controls in the dialog box. Otherwise, it should return nonzero, in which case the system sets the focus to the first control in the dialog box that can be given the focus.

Remarks

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.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: User-defined.

See Also

Dialog Boxes Overview, Dialog Box Functions, CreateDialog, CreateDialogIndirect, CreateDialogIndirectParam, CreateDialogParam, DefWindowProc, DialogBox, DialogBoxIndirect, DialogBoxIndirectParam, DialogBoxParam, SetFocus, WM_INITDIALOG


EndDialog

The EndDialog function destroys a modal dialog box, causing the system to end any processing for the dialog box.

BOOL EndDialog(
  HWND hDlg,    // handle to dialog box
  int nResult   // value to return
);

Parameters

hDlg
Identifies the dialog box to be destroyed.
nResult
Specifies the value to be returned to the application from the function that created the dialog box.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Dialog boxes created by the DialogBox, DialogBoxParam, DialogBoxIndirect, and DialogBoxIndirectParam functions must be destroyed using the EndDialog function. An application calls EndDialog from within the dialog box procedure; the function must not be used for any other purpose.

A dialog box procedure can call EndDialog at any time, even during the processing of the WM_INITDIALOG message. If your application calls the function while WM_INITDIALOG is being processed, the dialog box is destroyed before it is shown and before the input focus is set.

EndDialog does not destroy the dialog box immediately. Instead, it sets a flag and allows the dialog box procedure to return control to the system. The system checks the flag before attempting to retrieve the next message from the application queue. If the flag is set, the system ends the message loop, destroys the dialog box, and uses the value in nResult as the return value from the function that created the dialog box.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Dialog Boxes Overview, Dialog Box Functions, DialogBox, DialogBoxIndirect, DialogBoxIndirectParam, DialogBoxParam, WM_INITDIALOG


GetDialogBaseUnits

The GetDialogBaseUnits function returns the system's dialog base units, which are the average width and height of characters in the system font. For dialog boxes that use the system font, you can use these values to convert between dialog template units, as specified in dialog box templates, and pixels. For dialog boxes that do not use the system font, the conversion from dialog template units to pixels depends on the font used by the dialog box.

For either type of dialog box, it is easier to use the MapDialogRect function to perform the conversion. MapDialogRect takes the font into account and correctly converts a rectangle from dialog template units into pixels.

LONG GetDialogBaseUnits(VOID)

Parameters

This function has no parameters.

Return Values

The return value is a 32-bit value that contains the dialog base units. The low-order word of the return value contains the horizontal dialog box base unit, and the high-order word contains the vertical dialog box base unit.

Remarks

The horizontal base unit returned by GetDialogBaseUnits is equal to the average width, in pixels, of the characters in the system font; the vertical base unit is equal to the height, in pixels, of the font.

For a dialog box that does not use the system font, the base units are the average width and height, in pixels, of the characters in the dialog's font. You can use the GetTextMetrics and GetTextExtentPoint32 functions to calculate these values for a selected font. However, by using the MapDialogRect function, you can avoid errors that might result if your calculations differ from those performed by the system.

Each horizontal base unit is equal to 4 horizontal dialog template units; each vertical base unit is equal to 8 vertical dialog template units. Therefore, to convert dialog template units to pixels, use the following formulas:

pixelX = (templateunitX * baseunitX) / 4
pixelY = (templateunitY * baseunitY) / 8

Similarly, to convert from pixels to dialog template units, use the following formulas:

templateunitX = (pixelX * 4) / baseunitX
templateunitY = (pixelY * 8) / baseunitY

The multiplication is performed before the division to avoid rounding problems if base units are not divisible by 4 or 8.

Windows CE: Windows CE does not support any extended error values for this function.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Dialog Boxes Overview, Dialog Box Functions, MapDialogRect


GetDlgCtrlID

The GetDlgCtrlID function returns the identifier of the specified control.

int GetDlgCtrlID(
  HWND hwndCtl   // handle of control
);

Parameters

hwndCtl
Identifies the control.

Return Values

If the function succeeds, the return value is the identifier of the control.

If the function fails, the return value is zero. An invalid value for the hwndCtl parameter, for example, will cause the function to fail. To get extended error information, call GetLastError.

Remarks

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 identifies a top-level window, top-level windows cannot have identifiers and such a return value is never valid.

Windows CE: Identifiers are only valid for child windows.

The identifier can be set by passing it in as the hMenu parameter to the CreateWindowEx function. It can also be set and retrieved by calling the SetWindowLong and GetWindowLong functions with the nIndex parameter set to GWL_ID.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Dialog Boxes Overview, Dialog Box Functions, CreateWindow, CreateWindowEx, GetDlgItem


GetDlgItem

The GetDlgItem function retrieves the handle of a control in the specified dialog box.

HWND GetDlgItem(
  HWND hDlg,       // handle of dialog box
  int nIDDlgItem   // identifier of control
);

Parameters

hDlg
Identifies the dialog box that contains the control.
nIDDlgItem
Specifies the identifier of the control to be retrieved.

Return Values

If the function succeeds, the return value is the window handle of the given 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.

Remarks

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.

Windows CE: The GetDlgItem function only works for immediate child controls of a dialog box—it will not search through nested dialog boxes.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Dialog Boxes Overview, Dialog Box Functions, CreateWindow, CreateWindowEx, GetDlgItemInt, GetDlgItemText


GetDlgItemInt

The GetDlgItemInt function translates the text of a specified control in a dialog box into an integer value.

UINT GetDlgItemInt(
  HWND hDlg,       // handle to dialog box
  int nIDDlgItem,  // control identifier
  BOOL *lpTranslated,
                   // points to variable to receive success/failure
                   // indicator
  BOOL bSigned     // specifies whether value is signed or unsigned
);

Parameters

hDlg
Handle to the dialog box that contains the control of interest.
nIDDlgItem
Dialog item identifier that specifies the control whose text is to be translated.
lpTranslated
Pointer to a Boolean variable that receives a function success/failure value. TRUE indicates success, FALSE indicates failure.

This parameter is optional: it can be NULL. In that case, the function returns no information about success or failure.

bSigned
Specifies whether the function should examine the text for a minus sign at the beginning and return a signed integer value if it finds one. TRUE specifies that this should be done, FALSE that it should not.

Return Values

If the function succeeds, the variable pointed to by lpTranslated is set to TRUE, and the return value is the translated value of the control text.

If the function fails, the variable pointed to by lpTranslated is set to FALSE, and the return value is zero. Note that, since zero is a possible translated value, a return value of zero does not by itself indicate failure.

If lpTranslated is NULL, the function returns no information about success or failure.

If the bSigned parameter is TRUE, specifying that the value to be retrieved is a signed integer value, cast the return value to an int type. To get extended error information, call GetLastError.

Remarks

The GetDlgItemInt function retrieves the text of the given control by sending the control a WM_GETTEXT message. The function translates the retrieved text by stripping any extra spaces at the beginning of the text and then converting the decimal digits. The function stops translating when it reaches the end of the text or encounters a nonnumeric character.

If the bSigned parameter is TRUE, the GetDlgItemInt function checks for a minus sign (–) at the beginning of the text and translates the text into a signed integer value. Otherwise, the function creates an unsigned integer value.

The GetDlgItemInt function returns zero if the translated value is greater than INT_MAX (for signed numbers) or UINT_MAX (for unsigned numbers).

Windows CE: Text strings with more than 48 characters cannot be translated.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Dialog Boxes Overview, Dialog Box Functions, GetDlgCtrlID, GetDlgItem, GetDlgItemText, SetDlgItemInt


GetDlgItemText

The GetDlgItemText function retrieves the title or text associated with a control in a dialog box.

UINT GetDlgItemText(
  HWND hDlg,       // handle of dialog box
  int nIDDlgItem,  // identifier of control
  LPTSTR lpString, // address of buffer for text
  int nMaxCount    // maximum size of string
);

Parameters

hDlg
Identifies 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 characters, of the string to be copied to the buffer pointed to by lpString. If the length of the string exceeds the limit, the string is truncated.

Return Values

If the function succeeds, the return value specifies the number of characters 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.

Remarks

The GetDlgItemText function sends a WM_GETTEXT message to the control.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Dialog Boxes Overview, Dialog Box Functions, GetDlgItemInt, SetDlgItemInt, SetDlgItemText, WM_GETTEXT


GetNextDlgGroupItem

The GetNextDlgGroupItem function retrieves the handle of the first control in a group of controls that precedes (or follows) the specified control in a dialog box.

HWND GetNextDlgGroupItem(
  HWND hDlg,       // handle of dialog box
  HWND hCtl,       // handle of control
  BOOL bPrevious   // direction flag
);

Parameters

hDlg
Identifies the dialog box being searched.
hCtl
Identifies the control to be used as the starting point for the search. If this parameter is NULL, the function uses the last (or first) control in the dialog box as the starting point for the search.
bPrevious
Specifies how the function is to search the group of controls in the dialog box. If this parameter is TRUE, the function searches for the previous control in the group. If it is FALSE, the function searches for the next control in the group.

Return Values

If GetNextDlgGroupItem succeeds, the return value is the handle of the previous (or next) control in the group of controls.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The GetNextDlgGroupItem function searches controls in the order (or reverse order) they were created in the dialog box template. The first control in the group must have the WS_GROUP style; all other controls in the group must have been consecutively created and must not have the WS_GROUP style.

When searching for the previous control, the function returns the first control it locates that is visible and not disabled. If the control given by hCtl has the WS_GROUP style, the function temporarily reverses the search to locate the first control having the WS_GROUP style, then resumes the search in the original direction, returning the first control it locates that is visible and not disabled, or returning hwndCtrl if no such control is found.

When searching for the next control, the function returns the first control it locates that is visible, not disabled, and does not have the WS_GROUP style. If it encounters a control having the WS_GROUP style, the function reverses the search, locates the first control having the WS_GROUP style, and returns this control if it is visible and not disabled. Otherwise, the function resumes the search in the original direction and returns the first control it locates that is visible and not disabled, or returns hCtl if no such control is found.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Dialog Boxes Overview, Dialog Box Functions, GetNextDlgTabItem


GetNextDlgTabItem

The GetNextDlgTabItem function retrieves the handle of the first control that has the WS_TABSTOP style that precedes (or follows) the specified control.

HWND GetNextDlgTabItem(
  HWND hDlg,       // handle of dialog box
  HWND hCtl,       // handle of known control
  BOOL bPrevious   // direction flag
);

Parameters

hDlg
Identifies the dialog box to be searched.
hCtl
Identifies the control to be used as the starting point for the search. If this parameter is NULL, the function uses the last (or first) control in the dialog box as the starting point for the search.
bPrevious
Specifies how the function is to search the dialog box. If this parameter is TRUE, the function searches for the previous control in the dialog box. If this parameter is FALSE, the function searches for the next control in the dialog box.

Return Values

If the function succeeds, the return value is the window handle of the previous (or next) control that has the WS_TABSTOP style set.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The GetNextDlgTabItem function searches controls in the order (or reverse order) they were created in the dialog box template. The function returns the first control it locates that is visible, not disabled, and has the WS_TABSTOP style. If no such control exists, the function returns hCtl.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Dialog Boxes Overview, Dialog Box Functions, GetDlgItem, GetNextDlgGroupItem


IsDialogMessage

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 of dialog box
  LPMSG lpMsg // address of structure with message
);

Parameters

hDlg
Identifies the dialog box.
lpMsg
Pointer to an MSG structure that contains the message to be checked.

Return Values

If the message has been processed, the return value is nonzero.

If the message has not been processed, the return value is zero.

Remarks

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 selection commands 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.

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.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Dialog Boxes Overview, Dialog Box Functions, DispatchMessage, DM_GETDEFID, DM_SETDEFID, MSG, TranslateMessage, WM_GETDLGCODE, WM_USER


MapDialogRect

The MapDialogRect function converts (maps) the specified dialog box units to screen units (pixels). The function replaces the coordinates in the specified RECT structure with the converted coordinates, which allows the structure to be used to create a dialog box or position a control within a dialog box.

BOOL MapDialogRect(
  HWND hDlg,      // handle of dialog box
  LPRECT lpRect   // address of structure with rectangle
);

Parameters

hDlg
Identifies a dialog box. This function accepts only handles for dialog boxes created by one of the dialog box creation functions; handles for other windows are not valid.
lpRect
Pointer to a RECT structure that contains the dialog box coordinates to be converted.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The MapDialogRect function assumes that the initial coordinates in the RECT structure represent dialog box units. To convert these coordinates from dialog box units to pixels, the function retrieves the current horizontal and vertical base units for the dialog box, then applies the following formulas:

left   = (left   * baseunitX) / 4
right  = (right  * baseunitX) / 4
top    = (top    * baseunitY) / 8
bottom = (bottom * baseunitY) / 8

In most cases, the base units for the dialog box are the same as those retrieved by using the GetDialogBaseUnits function. If the dialog box template has the DS_SETFONT style, however, the base units are the average width and height, in pixels, of the characters in the font given by the template.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Dialog Boxes Overview, Dialog Box Functions, CreateDialog, CreateDialogIndirect, CreateDialogIndirectParam, CreateDialogParam, DialogBox, DialogBoxIndirect, DialogBoxIndirectParam, DialogBoxParam, GetDialogBaseUnits, RECT


MessageBox

The MessageBox function creates, displays, and operates a message box. The message box contains an application-defined message and title, plus any combination of predefined icons and push buttons.

int MessageBox(
  HWND hWnd,          // handle of owner window
  LPCTSTR lpText,     // address of text in message box
  LPCTSTR lpCaption,  // address of title of message box
  UINT uType          // style of message box
);

Parameters

hWnd
Identifies the owner window of the message box to be created. If this parameter is NULL, the message box has no owner window.
lpText
Pointer to a null-terminated string containing the message to be displayed.
lpCaption
Pointer to a null-terminated string used for the dialog box title. If this parameter is NULL, the default title Error is used.
uType
Specifies a set of bit flags that determine the contents and behavior of the dialog box. This parameter can be a combination of flags from the following groups of flags.

Specify one of the following flags to indicate the buttons contained in the message box:
Flag | Meaning
MB_ABORTRETRYIGNORE | The message box contains three push buttons: Abort, Retry, and Ignore.
MB_OK | The message box contains one push button: OK. This is the default.
MB_OKCANCEL | The message box contains two push buttons: OK and Cancel.
MB_RETRYCANCEL | The message box contains two push buttons: Retry and Cancel.
MB_YESNO | The message box contains two push buttons: Yes and No.
MB_YESNOCANCEL | The message box contains three push buttons: Yes, No, and Cancel.

Specify one of the following flags to display an icon in the message box:
Flag | Meaning
MB_ICONEXCLAMATION,
MB_ICONWARNING
 An exclamation-point icon appears in the message box.
MB_ICONINFORMATION, MB_ICONASTERISK
 An icon consisting of a lowercase letter i in a circle appears in the message box.
MB_ICONQUESTION | A question-mark icon appears in the message box.
MB_ICONSTOP,
MB_ICONERROR,
MB_ICONHAND
 A stop-sign icon appears in the message box.

Specify one of the following flags to indicate the default button:
Flag | Meaning
MB_DEFBUTTON1 The first button is the default button.

MB_DEFBUTTON1 is the default unless MB_DEFBUTTON2, MB_DEFBUTTON3, or MB_DEFBUTTON4 is specified.
MB_DEFBUTTON2 | The second button is the default button.
MB_DEFBUTTON3 | The third button is the default button.
MB_DEFBUTTON4 | The fourth button is the default button.

Specify one of the following flags to indicate the modality of the dialog box:
Flag | Meaning
MB_APPLMODAL The user must respond to the message box before continuing work in the window identified by the hWnd parameter. However, the user can move to the windows of other threads and work in those windows.

Depending on the hierarchy of windows in the application, the user may be able to move to other windows within the thread. All child windows of the parent of the message box are automatically disabled, but popup windows are not.

MB_APPLMODAL is the default if neither MB_SYSTEMMODAL nor MB_TASKMODAL is specified.
MB_SYSTEMMODAL | Same as MB_APPLMODAL except that the message box has the WS_EX_TOPMOST style. Use system-modal message boxes to notify the user of serious, potentially damaging errors that require immediate attention (for example, running out of memory). This flag has no effect on the user's ability to interact with windows other than those associated with hWnd.
MB_TASKMODAL | Same as MB_APPLMODAL except that all the top-level windows belonging to the current thread are disabled if the hWnd parameter is NULL. Use this flag when the calling application or library does not have a window handle available but still needs to prevent input to other windows in the calling thread without suspending other threads.

In addition, you can specify the following flags:

MB_DEFAULT_DESKTOP_ONLY
The desktop currently receiving input must be a default desktop; otherwise, the function fails. A default desktop is one an application runs on after the user has logged on.
MB_HELP
Adds a Help button to the message box. Choosing the Help button or pressing F1 generates a Help event.
MB_RIGHT
The text is right-justified.
MB_RTLREADING
Displays message and caption text using right-to-left reading order on Hebrew and Arabic systems.
MB_SETFOREGROUND
The message box becomes the foreground window. Internally, the system calls the SetForegroundWindow function for the message box.
MB_TOPMOST
The message box is created with the WS_EX_TOPMOST window style.
MB_SERVICE_NOTIFICATION
Windows NT: The caller is a service notifying the user of an event. The function displays a message box on the current active desktop, even if there is no user logged on to the computer.

If this flag is set, the hWnd parameter must be NULL. This is so the message box can appear on a desktop other than the desktop corresponding to the hWnd.

For Windows NT version 4.0, the value of MB_SERVICE_NOTIFICATION has changed. See WINUSER.H for the old and new values. Windows NT 4.0 provides backward compatibility for pre-existing services by mapping the old value to the new value in the implementation of MessageBox and MessageBoxEx. This mapping is only done for executables that have a version number, as set by the linker, less than 4.0.

To build a service that uses MB_SERVICE_NOTIFICATION, and can run on both Windows NT 3.x and Windows NT 4.0, you have two choices.
  1. At link-time, specify a version number less than 4.0; or
2. At link-time, specify version 4.0. At run-time, use the GetVersionEx function to check the system version. Then when running on Windows NT 3.x, use MB_SERVICE_NOTIFICATION_NT3X; and on Windows NT 4.0, use MB_SERVICE_NOTIFICATION.

MB_SERVICE_NOTIFICATION_NT3X
Windows NT: This value corresponds to the value defined for MB_SERVICE_NOTIFICATION for Windows NT version 3.51.

Return Values

The return value is zero if there is not enough memory to create the message box.

If the function succeeds, the return value is one of the following menu-item values returned by the dialog box:

Value | Meaning
IDABORT | Abort button was selected.
IDCANCEL | Cancel button was selected.
IDIGNORE | Ignore button was selected.
IDNO | No button was selected.
IDOK | OK button was selected.
IDRETRY | Retry button was selected.
IDYES | Yes button was selected.

If a message box has a Cancel button, the function returns the IDCANCEL value if either the esc key is pressed or the Cancel button is selected. If the message box has no Cancel button, pressing esc has no effect.

Remarks

When you use a system-modal message box to indicate that the system is low on memory, the strings pointed to by the lpText and lpCaption parameters should not be taken from a resource file, because an attempt to load the resource may fail.

When an application calls MessageBox and specifies the MB_ICONHAND and MB_SYSTEMMODAL flags for the uType parameter, the system displays the resulting message box regardless of available memory. When these flags are specified, the system limits the length of the message box text to three lines. The system does not automatically break the lines to fit in the message box, however, so the message string must contain carriage returns to break the lines at the appropriate places.

If you create a message box while a dialog box is present, use the handle of the dialog box as the hWnd parameter. The hWnd parameter should not identify a child window, such as a control in a dialog box.

Windows 95: The system can support a maximum of 16,364 window handles.

Windows CE: Windows CE does not support the following styles for the uType parameter:

MB_SYSTEMMODAL

MB_TASKMODAL

MB_HELP

MB_RIGHT

MB_RTLREADING

MB_DEFAULT_DESKTOP_ONLY

MB_SERVICE_NOTIFICATION

MB_USERICON.

The following return values are not supported:

IDCLOSE

IDHELP

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows and Windows NT.

See Also

Dialog Boxes Overview, Dialog Box Functions, FlashWindow, MessageBeep, MessageBoxEx, MessageBoxIndirect, SetForegroundWindow


MessageBoxEx

The MessageBoxEx function creates, displays, and operates a message box. The message box contains an application-defined message and title, plus any combination of predefined icons and push buttons. The wLanguageId parameter specifies which set of language resources is used for the predefined push buttons. For full descriptions of the other parameters of MessageBoxEx, see MessageBox.

int MessageBoxEx(
  HWND hWnd,         // handle of owner window
  LPCTSTR lpText,    // address of text in message box
  LPCTSTR lpCaption, // address of title of message box
  UINT uType,        // style of message box
  WORD wLanguageId   // language identifier
);

Parameters

hWnd
Identifies the owner window of the message box to be created. If this parameter is NULL, the message box has no owner window.
lpCaption
Pointer to a null-terminated string containing the message to be displayed.
lpszTitle
Pointer to a null-terminated string used for the dialog box title. If this parameter is NULL, the default title Error is used.
uType
Specifies a set of bit flags that determine the contents and behavior of the dialog box. This parameter can be a combination of flags from the following groups of flags.

Specify one of the following flags to indicate the buttons contained in the message box:
Flag | Meaning
MB_ABORTRETRYIGNORE | The message box contains three push buttons: Abort, Retry, and Ignore.
MB_OK | The message box contains one push button: OK. This is the default.
MB_OKCANCEL | The message box contains two push buttons: OK and Cancel.
MB_RETRYCANCEL | The message box contains two push buttons: Retry and Cancel.
MB_YESNO | The message box contains two push buttons: Yes and No.
MB_YESNOCANCEL | The message box contains three push buttons: Yes, No, and Cancel.

Specify one of the following flags to display an icon in the message box:
Flag | Meaning
MB_ICONEXCLAMATION,
MB_ICONWARNING
 An exclamation-point icon appears in the message box.
MB_ICONINFORMATION, MB_ICONASTERISK
 An icon consisting of a lowercase letter i in a circle appears in the message box.
MB_ICONQUESTION | A question-mark icon appears in the message box.
MB_ICONSTOP,
MB_ICONERROR,
MB_ICONHAND
 A stop-sign icon appears in the message box.

Specify one of the following flags to indicate the default button:
Flag | Meaning
MB_DEFBUTTON1 The first button is the default button.

MB_DEFBUTTON1 is the default unless MB_DEFBUTTON2, MB_DEFBUTTON3, or MB_DEFBUTTON4 is specified.
MB_DEFBUTTON2 | The second button is the default button.
MB_DEFBUTTON3 | The third button is the default button.
MB_DEFBUTTON4 | The fourth button is the default button.

Specify one of the following flags to indicate the modality of the dialog box:
Flag | Meaning
MB_APPLMODAL The user must respond to the message box before continuing work in the window identified by the hWnd parameter. However, the user can move to the windows of other threads and work in those windows.

Depending on the hierarchy of windows in the application, the user may be able to move to other windows within the thread. All child windows of the parent of the message box are automatically disabled, but popup windows are not.

MB_APPLMODAL is the default if neither MB_SYSTEMMODAL nor MB_TASKMODAL is specified.
MB_SYSTEMMODAL | Same as MB_APPLMODAL except that the message box has the WS_EX_TOPMOST style. Use system-modal message boxes to notify the user of serious, potentially damaging errors that require immediate attention (for example, running out of memory). This flag has no effect on the user's ability to interact with windows other than those associated with hWnd.
MB_TASKMODAL | Same as MB_APPLMODAL except that all the top-level windows belonging to the current thread are disabled if the hWnd parameter is NULL. Use this flag when the calling application or library does not have a window handle available but still needs to prevent input to other windows in the calling thread without suspending other threads.

In addition, you can specify the following flags:

MB_DEFAULT_DESKTOP_ONLY
The desktop currently receiving input must be a default desktop; otherwise, the function fails. A default desktop is one an application runs on after the user has logged on.
MB_HELP
Adds a Help button to the message box. Choosing the Help button or pressing F1 generates a Help event.
MB_RIGHT
The text is right-justified.
MB_RTLREADING
Displays message and caption text using right-to-left reading order on Hebrew and Arabic systems.
MB_SETFOREGROUND
The message box becomes the foreground window. Internally, the system calls the SetForegroundWindow function for the message box.
MB_TOPMOST
The message box is created with the WS_EX_TOPMOST window style.
MB_SERVICE_NOTIFICATION
Windows NT: The caller is a service notifying the user of an event. The function displays a message box on the current active desktop, even if there is no user logged on to the computer.

If this flag is set, the hWnd parameter must be NULL. This is so the message box can appear on a desktop other than the desktop corresponding to the hWnd.

For Windows NT version 4.0, the value of MB_SERVICE_NOTIFICATION has changed. See WINUSER.H for the old and new values. Windows NT 4.0 provides backward compatibility for pre-existing services by mapping the old value to the new value in the implementation of MessageBox and MessageBoxEx. This mapping is only done for executables that have a version number, as set by the linker, less than 4.0.

To build a service that uses MB_SERVICE_NOTIFICATION, and can run on both Windows NT 3.x and Windows NT 4.0, you have two choices.
  1. At link-time, specify a version number less than 4.0; or
2. At link-time, specify version 4.0. At run-time, use the GetVersionEx function to check the system version. Then when running on Windows NT 3.x, use MB_SERVICE_NOTIFICATION_NT3X; and on Windows NT 4.0, use MB_SERVICE_NOTIFICATION.

MB_SERVICE_NOTIFICATION_NT3X
Windows NT: This value corresponds to the value defined for MB_SERVICE_NOTIFICATION for Windows NT version 3.51.
wLanguageId
Specifies the language in which to display the text contained in the predefined push buttons. This value must be in the form returned by the MAKELANGID macro.

For a list of the language identifiers supported by Win32, see Language Identifiers. Note that each localized release of Windows and Windows NT typically contains resources only for a limited set of languages. Thus, for example, the U.S. version offers LANG_ENGLISH, the French version offers LANG_FRENCH, the German version offers LANG_GERMAN, and the Japanese version offers LANG_JAPANESE. Each version offers LANG_NEUTRAL. This limits the set of values that can be used with the wLanguageId parameter. Before specifying a language identifier, you should enumerate the locales that are installed on a system.

Return Values

If the function succeeds, the return value is a nonzero menu-item value returned by the dialog box.

Value | Meaning
IDABORT | Abort button was selected.
IDCANCEL | Cancel button was selected.
IDIGNORE | Ignore button was selected.
IDNO | No button was selected.
IDOK | OK button was selected.
IDRETRY | Retry button was selected.
IDYES | Yes button was selected.

If a message box has a Cancel button, the function returns the IDCANCEL value when either the esc key or Cancel button is pressed. If the message box has no Cancel button, pressing the esc key has no effect.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

When you create a system-modal message box to indicate that the system is low on memory, the strings passed as the lpText and lpCaption parameters should not be taken from a resource file, because an attempt to load the resource may fail.

When an application calls the MessageBoxEx function and specifies the MB_ICONHAND and MB_SYSTEMMODAL flags for the uType parameter, the Win32 API displays the resulting message box regardless of available memory. When you specify these flags, the system limits the length of the message-box text to one line.

If you create a message box while a dialog box is present, use the handle of the dialog box as the hWnd parameter. The hWnd parameter should not identify a child window, such as a dialog box.

Windows 95: The system can support a maximum of 16,364 window handles.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows and Windows NT.

See Also

Dialog Boxes Overview, Dialog Box Functions, MAKELANGID, MessageBeep, MessageBox, MessageBoxIndirect, SetForegroundWindow


MessageBoxIndirect

The MessageBoxIndirect function creates, displays, and operates a message box. The message box contains application-defined message text and title, any icon, and any combination of predefined push buttons.

int MessageBoxIndirect(
  LPMSGBOXPARAMS lpMsgBoxParams  // address of structure for message
                                 // box parameters
);

Parameters

lpMsgBoxParams
Pointer to a MSGBOXPARAMS structure that contains information used to display the message box.

Return Values

The return value is zero if there is not enough memory to create the message box.

If the function succeeds, the return value is one of the following menu-item values returned by the dialog box:

Value | Meaning
IDABORT | Abort button was selected.
IDCANCEL | Cancel button was selected.
IDIGNORE | Ignore button was selected.
IDNO | No button was selected.
IDOK | OK button was selected.
IDRETRY | Retry button was selected.
IDYES | Yes button was selected.

If a message box has a Cancel button, the function returns the IDCANCEL value if either the esc key is pressed or the Cancel button is selected. If the message box has no Cancel button, pressing esc has no effect.

Remarks

When you use a system-modal message box to indicate that the system is low on memory, the strings pointed to by the lpszText and lpszCaption members of the MSGBOXPARAMS structure should not be taken from a resource file, because an attempt to load the resource may fail.

When an application calls MessageBoxIndirect and specifies the MB_ICONHAND and MB_SYSTEMMODAL flags for the dwStyle member of the MSGBOXPARAMS structure, the system displays the resulting message box regardless of available memory. When these flags are specified, the system limits the length of the message box text to three lines. The system does not automatically break the lines to fit in the message box, however, so the message string must contain carriage returns to break the lines at the appropriate places.

If you create a message box while a dialog box is present, use the handle of the dialog box as the hWnd parameter. The hWnd parameter should not identify a child window, such as a control in a dialog box.

Windows 95: The system can support a maximum of 16,364 window handles.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Dialog Boxes Overview, Dialog Box Functions, MessageBox, MessageBoxEx, MSGBOXPARAMS


SendDlgItemMessage

The SendDlgItemMessage function sends a message to the specified control in a dialog box.

LONG SendDlgItemMessage(
  HWND hDlg,      // handle of dialog box
  int nIDDlgItem, // identifier of control
  UINT Msg,       // message to send
  WPARAM wParam,  // first message parameter
  LPARAM lParam   // second message parameter
);

Parameters

hDlg
Identifies 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 Values

The return value specifies the result of the message processing and depends on the message sent.

Remarks

The SendDlgItemMessage function does not return until the message has been processed.

Using SendDlgItemMessage is identical to retrieving a handle of the specified control and calling the SendMessage function.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Dialog Boxes Overview, Dialog Box Functions, SendMessage


SetDlgItemInt

The SetDlgItemInt function sets the text of a control in a dialog box to the string representation of a specified integer value.

BOOL SetDlgItemInt(
  HWND hDlg,       // handle of dialog box
  int nIDDlgItem,  // identifier of control
  UINT uValue,     // value to set
  BOOL bSigned     // signed or unsigned indicator
);

Parameters

hDlg
Identifies the dialog box that contains the control.
nIDDlgItem
Specifies the control to be changed.
uValue
Specifies the integer value used to generate the item text.
bSigned
Specifies whether the uValue parameter is signed or unsigned. If this parameter is TRUE, uValue is signed. If this parameter is TRUE and uValue is less than zero, a minus sign is placed before the first digit in the string. If this parameter is FALSE, uValue is unsigned.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

To set the new text, this function sends a WM_SETTEXT message to the specified control.

Windows CE: The bSigned parameter is not used. All values passed in the nValue parameter are assumed to be signed.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Dialog Boxes Overview, Dialog Box Functions, GetDlgItemInt, SetDlgItemText, WM_SETTEXT


SetDlgItemText

The SetDlgItemText function sets the title or text of a control in a dialog box.

BOOL SetDlgItemText(
  HWND hDlg,         // handle of dialog box
  int nIDDlgItem,    // identifier of control
  LPCTSTR lpString   // text to set
);

Parameters

hDlg
Identifies the dialog box that contains the control.
nIDDlgItem
Identifies the control with a title or text that is to be set.
lpString
Pointer to the null-terminated string that contains the text to be copied to the control.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The SetDlgItemText function sends a WM_SETTEXT message to the specified control.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Dialog Boxes Overview, Dialog Box Functions, GetDlgItemInt, GetDlgItemText, SetDlgItemInt, WM_SETTEXT


Dialog Box Structures

The following structures are used to create and manage dialog boxes and controls within dialog boxes.

DLGITEMTEMPLATE
DLGTEMPLATE
MSGBOXPARAMS

The following topics describe pseudo-structures that are not defined in any standard header file. These topics are provided to explain the format of an extended template for a dialog box.

DLGITEMTEMPLATEEX
DLGTEMPLATEEX


DLGITEMTEMPLATE

The DLGITEMTEMPLATE structure defines the dimensions and style of a control in a dialog box. One or more of these structures are combined with a DLGTEMPLATE structure to form a standard template for a dialog box.

typedef struct { // dlit
    DWORD style;
    DWORD dwExtendedStyle;
    short x;
    short y;
    short cx;
    short cy;
    WORD  id;
} DLGITEMTEMPLATE;

Members

style
Specifies the style of the control. This member can be a combination of window style values (such as WS_BORDER) and one or more of the control style values (such as BS_PUSHBUTTON and ES_LEFT).
dwExtendedStyle
Specifies extended styles for a window. This member is not used to create controls in dialog boxes, but applications that use dialog box templates can use it to create other types of windows.
x
Specifies the x-coordinate, in dialog box units, of the upper-left corner of the control. This coordinate is always relative to the upper-left corner of the dialog box's client area.
y
Specifies the y-coordinate, in dialog box units, of the upper-left corner of the control. This coordinate is always relative to the upper-left corner of the dialog box's client area.
cx
Specifies the width, in dialog box units, of the control.
cy
Specifies the height, in dialog box units, of the control.
id
Specifies the control identifier.

Remarks

In a standard template for a dialog box, the DLGITEMTEMPLATE structure is always immediately followed by three variable-length arrays specifying the class, title, and creation data for the control. Each array consists of one or more 16-bit elements.

Each DLGITEMTEMPLATE structure in the template must be aligned on a DWORD boundary. The class and title arrays must be aligned on WORD boundaries. The creation data array must be aligned on a WORD boundary.

Immediately following each DLGITEMTEMPLATE structure is a class array that identifies the window class of the control. If the first element of this array is any value other than 0xFFFF, the system treats the array as a null-terminated Unicode string that specifies the name of a registered window class. If the first element is 0xFFFF, the array has one additional element that specifies the ordinal value of a predefined system class. The ordinal can be one of the following atom values.

Value | Meaning
0x0080 | Button
0x0081 | Edit
0x0082 | Static
0x0083 | List box
0x0084 | Scroll bar
0x0085 | Combo box

Following the class array is a title array that contains the initial text or resource identifier of the control. If the first element of this array is 0xFFFF, the array has one additional element that specifies an ordinal value of a resource, such as an icon, in an executable file. You can use a resource identifier for controls, such as static icon controls, that load and display an icon or other resource rather than text. If the first element is any value other than 0xFFFF, the system treats the array as a null-terminated Unicode string that specifies the initial text.

The creation data array begins at the next WORD boundary after the title array. This creation data can be of any size and format. If the first word of the creation data array is nonzero, it indicates the size, in bytes, of the creation data (including the size word). The control's window procedure must be able to interpret the 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.

If you specify character strings in the class and title arrays, you must use Unicode strings. To create code that works on both Windows and Windows NT, use the MultiByteToWideChar function to generate these Unicode strings.

The x, y, cx, and cy members specify values in dialog box units. You can convert these values to screen units (pixels) by using the MapDialogRect function.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Dialog Boxes Overview, Dialog Box Structures, CreateDialogIndirect, CreateDialogIndirectParam, CreateWindowEx, DialogBoxIndirect, DialogBoxIndirectParam, DLGITEMTEMPLATEEX, DLGTEMPLATE, DLGTEMPLATEEX, MapDialogRect, MultiByteToWideChar, WM_CREATE


DLGITEMTEMPLATEEX

The DLGITEMTEMPLATEEX structure is not defined in any standard header file. The structure definition is provided here to explain the format of an extended template for a dialog box.

For each control in a dialog box, an extended dialog box template has a block of data that uses the DLGITEMTEMPLATEEX format to describe the control. For a description of the format of an extended dialog box template, see DLGTEMPLATEEX.

typedef struct {
    DWORD  helpID;
    DWORD  exStyle;
    DWORD  style;
    short  x;
    short  y;
    short  cx;
    short  cy;
    WORD   id;
    sz_Or_Ord windowClass; // name or ordinal of a window class
    sz_Or_Ord title;       // title string or ordinal of a resource
    WORD   extraCount;     // bytes of following creation data
} DLGITEMTEMPLATEEX;

Members

helpID
Specifies the help context identifier for the control. When the system sends a WM_HELP message, it passes the helpID value in the dwContextId member of the HELPINFO structure.
dwExtendedStyle
Specifies extended styles for a window. This member is not used to create controls in dialog boxes, but applications that use dialog box templates can use it to create other types of windows.
style
Specifies the style of the control. This member can be a combination of window style values (such as WS_BORDER) and one or more of the control style values (such as BS_PUSHBUTTON and ES_LEFT).
x
Specifies the x-coordinate, in dialog box units, of the upper-left corner of the control. This coordinate is always relative to the upper-left corner of the dialog box's client area.
y
Specifies the y-coordinate, in dialog box units, of the upper-left corner of the control. This coordinate is always relative to the upper-left corner of the dialog box's client area.
cx
Specifies the width, in dialog box units, of the control.
cy
Specifies the height, in dialog box units, of the control.
id
Specifies the control identifier.
windowClass
Specifies a variable-length array of 16-bit elements that identifies the window class of the control. If the first element of this array is any value other than 0xFFFF, the system treats the array as a null-terminated Unicode string that specifies the name of a registered window class.

If the first element is 0xFFFF, the array has one additional element that specifies the ordinal value of a predefined system class. The ordinal can be one of the following atom values.
Value | Meaning
0x0080 | Button
0x0081 | Edit
0x0082 | Static
0x0083 | List box
0x0084 | Scroll bar
0x0085 | Combo box

title
Specifies a variable-length array of 16-bit elements that contains the initial text or resource identifier of the control. If the first element of this array is 0xFFFF, the array has one additional element that specifies an ordinal value that identifies a resource, such as an icon, in an executable file. You can use a resource identifier for controls, such as static icon controls, that load and display an icon or other resource rather than text.

If the first element is any value other than 0xFFFF, the system treats the array as a null-terminated Unicode string that specifies the initial text.

extraCount
Specifies the number of bytes of creation data that follow this member. If this value is greater than zero, the creation data begins at the next WORD boundary. This creation data can be of any size and format. The control's window procedure must be able to interpret the 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.

Remarks

An extended template for a dialog box consists of a DLGTEMPLATEEX header followed by a DLGITEMTEMPLATEEX structure for each control in the dialog box.

Each DLGITEMTEMPLATEEX structure must be aligned on a DWORD boundary. The variable-length windowClass and title arrays must be aligned on WORD boundaries. The creation data array, if any, must be aligned on a WORD boundary.

If you specify character strings in the windowClass and title arrays, you must use Unicode strings. To create code that works on both Windows and Windows NT, use the MultiByteToWideChar function to generate these Unicode strings.

The x, y, cx, and cy members specify values in dialog box units. You can convert these values to screen units (pixels) by using the MapDialogRect function.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.

See Also

Dialog Boxes Overview, Dialog Box Structures, CreateDialogIndirect, CreateDialogIndirectParam, CreateWindowEx, DialogBoxIndirect, DialogBoxIndirectParam, DLGITEMTEMPLATE, DLGTEMPLATE, DLGTEMPLATEEX, MapDialogRect, MultiByteToWideChar


DLGTEMPLATE

The DLGTEMPLATE structure defines the dimensions and style of a dialog box. This structure, always the first in a standard template for a dialog box, also specifies the number of controls in the dialog box and therefore specifies the number of subsequent DLGITEMTEMPLATE structures in the template.

typedef struct { // dltt
    DWORD style;
    DWORD dwExtendedStyle;
    WORD  cdit;
    short x;
    short y;
    short cx;
    short cy;
} DLGTEMPLATE;

Members

style
Specifies the style of the dialog box. This member can be a combination of window style values (such as WS_CAPTION and WS_SYSMENU) and one or more of the following dialog box style values:
Value | Meaning
DS_3DLOOK Gives the dialog box a nonbold font and draws three-dimensional borders around control windows in the dialog box.

The DS_3DLOOK style is required only by Win32-based applications compiled for system versions earlier than Windows 95 or Windows NT 4.0. The system automatically applies the three-dimensional look to dialog boxes created by applications compiled for current versions of the system.
DS_ABSALIGN | Indicates that the coordinates of the dialog box are screen coordinates. If this style is not specified, The system assumes they are client coordinates.
DS_CENTER | Centers the dialog box in the working area; that is, the area not obscured by the tray.
DS_CENTERMOUSE | Centers the mouse cursor in the dialog box.
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 WinHelp function using the HELP_WM_HELP command. The Help application displays a pop-up window that typically contains help for the control.

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. SYSTEM_FIXED_FONT is a monospace font compatible with the System font in Windows versions 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 System menu by specifying the WS_CAPTION and WS_SYSMENU styles.
DS_NOFAILCREATE | Windows 95: 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 contains additional data specifying the font to use for text in the client area and controls of the dialog box. The font data begins on the WORD boundary that follows the title array. It specifies a 16-bit point size value and a Unicode font name string. If possible, the system creates a font according to the specified values. Then the system passes the handle of the font to the dialog box and to each control by sending them the WM_SETFONT message.

If this style is not 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.
DS_SYSMODAL | This style is obsolete and is included for compatibility with earlier versions of Windows. If you specify this style, the system creates the dialog box with the WS_EX_TOPMOST style. Do not combine this style with the DS_CONTROL style.

dwExtendedStyle
Specifies extended styles for a window. This member is not used to create dialog boxes, but applications that use dialog box templates can use it to create other types of windows.
cdit
Specifies the number of items in the dialog box.
x
Specifies the x-coordinate, in dialog box units, of the upper-left corner of the dialog box.
y
Specifies the y-coordinate, in dialog box units, of the upper-left corner of the dialog box.
cx
Specifies the width, in dialog box units, of the dialog box.
cy
Specifies the height, in dialog box units, of the dialog box.

Remarks

In a standard template for a dialog box, the DLGTEMPLATE structure is always immediately followed by three variable-length arrays that specify the menu, class, and title for the dialog box. When the DS_SETFONT style is given, these arrays are also followed by a 16-bit value specifying point size and another variable-length array specifying a typeface name. Each array consists of one or more 16-bit elements. The menu, class, title, and font arrays must be aligned on WORD boundaries.

Immediately following the DLGTEMPLATE structure is a menu array that identifies a menu resource for the dialog box. If the first element of this array is 0x0000, the dialog box has no menu and the array has no other elements. If the first element is 0xFFFF, the array has one additional element that specifies the ordinal value of a menu resource in an executable file. If the first element has any other value, the system treats the array as a null-terminated Unicode string that specifies the name of a menu resource in an executable file.

Following the menu array is a class array that identifies the window class of the control. If the first element of the array is 0x0000, the system uses the predefined dialog box class for the dialog box and the array has no other elements. If the first element is 0xFFFF, the array has one additional element that specifies the ordinal value of a predefined system window class. If the first element has any other value, the system treats the array as a null-terminated Unicode string that specifies the name of a registered window class.

Following the class array is a title array that specifies a null-terminated Unicode string that contains the title of the dialog box. If the first element of this array is 0x0000, the dialog box has no title and the array has no other elements.

The 16-bit point size value and the typeface array follow the title array, but only if the style member specifies the DS_SETFONT style. The point size value specifies the point size of the font to use for the text in the dialog box and its controls. The typeface array is a null-terminated Unicode string specifying the name of the typeface for the font. When these values are given, The system creates a font having the given size and typeface (if possible) and sends a WM_SETFONT message to the dialog box procedure and the control window procedures as it creates the dialog box and controls.

Following the DLGTEMPLATE header in a standard dialog box template are one or more DLGITEMTEMPLATE structures that define the dimensions and style of the controls in the dialog box. The cdit member specifies the number of DLGITEMTEMPLATE structures in the template. These DLGITEMTEMPLATE structures must be aligned on DWORD boundaries.

If you specify character strings in the menu, class, title, or typeface arrays, you must use Unicode strings. To create code that works on both Windows and Windows NT, use the MultiByteToWideChar function to generate these Unicode strings.

The x, y, cx, and cy members specify values in dialog box units. You can convert these values to screen units (pixels) by using the MapDialogRect function.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Dialog Boxes Overview, Dialog Box Structures, CreateDialogIndirect, CreateDialogIndirectParam, DialogBoxIndirect, DialogBoxIndirectParam, DLGITEMTEMPLATE, DLGITEMTEMPLATEEX, DLGTEMPLATEEX, MapDialogRect, MultiByteToWideChar


DLGTEMPLATEEX

The DLGTEMPLATEEX structure is not defined in any standard header file. The structure definition is provided here to explain the format of an extended template for a dialog box.

An extended dialog box template begins with a DLGTEMPLATEEX header that describes the dialog box and specifies the number of controls in the dialog box. For each control in a dialog box, an extended dialog box template has a block of data that uses the DLGITEMTEMPLATEEX format to describe the control.

typedef struct {
    WORD   dlgVer;
    WORD   signature;
    DWORD  helpID;
    DWORD  exStyle;
    DWORD  style;
    WORD   cDlgItems;
    short  x;
    short  y;
    short  cx;
    short  cy;
    sz_Or_Ord menu;         // name or ordinal of a menu resource
    sz_Or_Ord windowClass;  // name or ordinal of a window class
    WCHAR  title[titleLen]; // title string of the dialog box
    short  pointsize;       // only if DS_SETFONT flag is set
    short  weight;          // only if DS_SETFONT flag is set
    short  bItalic;         // only if DS_SETFONT flag is set
    WCHAR  font[fontLen];   // typeface name, if DS_SETFONT is set
} DLGTEMPLATEEX;

Members

dlgVer
Specifies the version number of the extended dialog box template. This member must specify 1.
signature
Indicates whether a template is an extended dialog box template. A value of 0xFFFF indicates an extended dialog box template. In this case, the dlgVer member specifies the template version number. If signature is any value other than 0xFFFF, this is a standard template that uses the DLGTEMPLATE and DLGITEMTEMPLATE structures.
helpID
Specifies the help context identifier for the dialog box window. When the system sends a WM_HELP message, it passes this value in the dwContextId member of the HELPINFO structure.
exStyle
Specifies extended styles for a window. This member is not used to create dialog boxes, but applications that use dialog box templates can use it to create other types of windows.
style
Specifies the style of the dialog box. This member can be a combination of window style values (such as WS_CAPTION and WS_SYSMENU) and one or more of the following dialog box style values.
Value | Meaning
DS_3DLOOK Gives the dialog box a nonbold font and draws three-dimensional borders around control windows in the dialog box.

The DS_3DLOOK style is required only by Win32-based applications compiled for system versions earlier than Windows 95 or Windows NT 4.0. The system automatically applies the three-dimensional look to dialog boxes created by applications compiled for current versions of the system.
DS_ABSALIGN | Indicates that the coordinates of the dialog box are screen coordinates. If this style is not specified, the system treats them as client coordinates.
DS_CENTER | Centers the dialog box in the working area; that is, the area not obscured by the tray.
DS_CENTERMOUSE | Centers the mouse cursor in the dialog box.
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 procedure, which should call the WinHelp function using the HELP_WM_HELP command. The Help application displays a pop-up window that typically contains help for the control.

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. You cannot use the WS_EX_CONTEXTHELP style 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. SYSTEM_FIXED_FONT is a monospace font compatible with the System font in Windows versions 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 System menu by specifying the WS_CAPTION and WS_SYSMENU styles.
DS_NOFAILCREATE | Windows 95: 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 DLGTEMPLATEEX header of the extended dialog box template contains four additional members (pointsize, weight, bItalic, and font) that describe the font to use for the text in the client area and controls of the dialog box. If possible, the system creates a font according to the values specified in these members. Then the system passes the handle of the font to the dialog box and to each control by sending them the WM_SETFONT message.

If this style is not specified, the extended dialog box template does not include the pointsize, weight, bItalic, and font members.
DS_SETFOREGROUND | Causes the system to use the SetForegroundWindow function to bring the dialog box to the foreground.
DS_SYSMODAL | This style is obsolete and is included for compatibility with earlier versions of Windows. If you specify this style, the system creates the dialog box with the WS_EX_TOPMOST style. Do not combine this style with the DS_CONTROL style.

cDlgItems
Specifies the number of controls in the dialog box.
x
Specifies the x-coordinate, in dialog box units, of the upper-left corner of the dialog box.
y
Specifies the y-coordinate, in dialog box units, of the upper-left corner of the dialog box.
cx
Specifies the width, in dialog box units, of the dialog box.
cy
Specifies the height, in dialog box units, of the dialog box.
menu
Specifies a variable-length array of 16-bit elements that identifies a menu resource for the dialog box. If the first element of this array is 0x0000, the dialog box has no menu and the array has no other elements. If the first element is 0xFFFF, the array has one additional element that specifies the ordinal value of a menu resource in an executable file. If the first element has any other value, the system treats the array as a null-terminated Unicode string that specifies the name of a menu resource in an executable file.
windowClass
Specifies a variable-length array of 16-bit elements that identifies the window class of the dialog box. If the first element of the array is 0x0000, the system uses the predefined dialog box class for the dialog box and the array has no other elements. If the first element is 0xFFFF, the array has one additional element that specifies the ordinal value of a predefined system window class. If the first element has any other value, the system treats the array as a null-terminated Unicode string that specifies the name of a registered window class.
title
Specifies a null-terminated Unicode string that contains the title of the dialog box. If the first element of this array is 0x0000, the dialog box has no title and the array has no other elements.
pointsize
Specifies the point size of the font to use for the text in the dialog box and its controls. The pointsize, weight, bItalic, and font members are present in an extended dialog box template only if the style member specifies the DS_SETFONT style.
weight
Specifies the weight of the font in the range 0 through 1000. This can be any of the values listed for the lfWeight member of the LOGFONT structure. This member is present only if the style member specifies DS_SETFONT.
bItalic
Indicates whether the font is italic. If this value is TRUE, the font is italic. This member is present only if the style member specifies DS_SETFONT.
font
Specifies a null-terminated Unicode string that contains the name of the typeface for the font. This member is present only if the style member specifies DS_SETFONT.

Remarks

You can use an extended dialog box template instead of a standard dialog box template in the CreateDialogIndirectParam and DialogBoxIndirectParam functions and the CreateDialogIndirect and DialogBoxIndirect macros. A standard dialog box template uses the DLGTEMPLATE and DLGITEMTEMPLATE structures.

Following the DLGTEMPLATEEX header in an extended dialog box template is one or more DLGITEMTEMPLATEEX structures that describe the controls of the dialog box. The cDlgItems member specifies the number of DLGITEMTEMPLATEEX structures in the template.

Each DLGITEMTEMPLATEEX structure in the template must be aligned on a DWORD boundary. If the style member specifies the DS_SETFONT style, the first DLGITEMTEMPLATEEX structure begins on the first DWORD boundary after the font string. If DS_SETFONT is not specified, the first structure begins on the first DWORD boundary after the title string.

The menu, windowClass, title, and font arrays must be aligned on WORD boundaries.

If you specify character strings in the menu, windowClass, title, and font arrays, you must use Unicode strings. To create code that works on both Windows and Windows NT, use the MultiByteToWideChar function to generate these Unicode strings.

The x, y, cx, and cy members specify values in dialog box units. You can convert these values to screen units (pixels) by using the MapDialogRect function.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.

See Also

Dialog Boxes Overview, Dialog Box Structures, CreateDialogIndirect, CreateDialogIndirectParam, DialogBoxIndirect, DialogBoxIndirectParam, DLGITEMTEMPLATE, DLGITEMTEMPLATEEX, DLGTEMPLATE, MapDialogRect, MultiByteToWideChar, WM_SETFONT


MSGBOXPARAMS

The MSGBOXPARAMS structure contains information used to display a message box. The MessageBoxIndirect function uses this structure.

typedef struct {
    UINT      cbSize;
    HWND      hwndOwner;
    HINSTANCE hInstance;
    LPCTSTR    lpszText;
    LPCTSTR    lpszCaption;
    DWORD     dwStyle;
    LPCTSTR    lpszIcon;
    DWORD     dwContextHelpId;
    MSGBOXCALLBACK lpfnMsgBoxCallback;
    DWORD     dwLanguageId;
} MSGBOXPARAMS, *PMSGBOXPARAMS, FAR *LPMSGBOXPARAMS;

Members

cbSize
Specifies the structure size, in bytes.
hwndOwner
Identifies the owner window. This member can be NULL.
hInstance
Identifies the instance containing the icon resource identified by the lpszIcon member, and the string resource identified by the lpszText or lpszCaption member.
lpszText
Pointer to a null-terminated string, or the identifier of a string resource, that contains the message to be displayed.
lpszCaption
Pointer to a null-terminated string, or the identifier of a string resource, that contains the message box title. If this member is NULL, the default title Error is used.
dwStyle
Specifies a set of bit flags that determine the contents and behavior of the dialog box. This member can be a combination of flags described for the uType parameter of the MessageBoxEx function.

In addition, you can specify the MB_USERICON flag if you want the message box to display the icon specified by the lpszIcon member.

lpszIcon
Identifies an icon resource. This parameter can be either a null-terminated string or an integer resource identifier passed to the MAKEINTRESOURCE macro.

To load one of the standard system-defined icons, set the hInstance member to NULL and set lpszIcon to one of the values listed with the LoadIcon function.

This member is ignored if the dwStyle member does not specify the MB_USERICON flag.

dwContextHelpId
Identifies a Help context. If a Help event occurs, this value is specified in the HELPINFO structure that the message box sends to the owner window or callback function.
lpfnMsgBoxCallback
Pointer to the callback function that processes Help events for the message box. The callback function has the following form:

VOID CALLBACK MsgBoxCallback(LPHELPINFO lpHelpInfo);

If this member is NULL, the message box sends WM_HELP messages to the owner window when help events occur.

dwLanguageId
Specifies the language in which to display the text contained in the predefined push buttons. This value must be in the form returned by the MAKELANGID macro.

For a list of the language identifiers supported by Win32, see Language Identifiers. Note that each localized release of Windows and Windows NT typically contains resources only for a limited set of languages. Thus, for example, the U.S. version offers LANG_ENGLISH, the French version offers LANG_FRENCH, the German version offers LANG_GERMAN, and the Japanese version offers LANG_JAPANESE. Each version offers LANG_NEUTRAL. This limits the set of values that can be used with the wLanguageId parameter. Before specifying a language identifier, you should enumerate the locales that are installed on a system.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Unicode: Defined as Unicode and ANSI structures.

See Also

Dialog Boxes Overview, Dialog Box Structures, HELPINFO, LoadIcon, MAKEINTRESOURCE, MAKELANGID, MessageBoxEx, MessageBoxIndirect, WM_HELP


Dialog Box Messages

The following messages are used to create and manage dialog boxes and controls within dialog boxes.

DM_GETDEFID
DM_REPOSITION
DM_SETDEFID
WM_CTLCOLORDLG
WM_CTLCOLORMSGBOX
WM_ENTERIDLE
WM_GETDLGCODE
WM_INITDIALOG
WM_NEXTDLGCTL


DM_GETDEFID

An application sends a DM_GETDEFID message to retrieve the identifier of the default push button control for a dialog box.

DM_GETDEFID

Parameters

This message has no parameters.

Return Values

If a default push button exists, the high-order word of the return value contains the value DC_HASDEFID and the low-order word contains the control identifier. Otherwise, the return value is zero.

Remarks

The DefDlgProc function processes this message.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Dialog Boxes Overview, Dialog Box Messages, DefDlgProc, DM_SETDEFID


DM_REPOSITION

The DM_REPOSITION message repositions a top-level dialog box so that it fits within the desktop area. An application can send this message to a dialog box after resizing it to ensure that the entire dialog box remains visible.

DM_REPOSITION
wParam = 0;
lParam = 0;

Parameters

This message has no parameters.

Return Values

This message has no return value.

Remarks

This message has no effect if the dialog box is a child window.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Dialog Boxes Overview, Dialog Box Messages


DM_SETDEFID

An application sends a DM_SETDEFID message to change the identifier of the default push button for a dialog box.

DM_SETDEFID
wParam = idControl; // identifier of new default push button

Parameters

idControl
Value of wParam. Specifies the identifier of a push button control that will become the default.

Remarks

This message is processed by the DefDlgProc function. To set the default push button, the function can send WM_GETDLGCODE and BM_SETSTYLE messages to the given control and the current default push button.

Using the DM_SETDEFID message can result in more than one button appearing to have the default push button state. When the system brings up a dialog, it draws the first push button in the dialog template with the default state border. Sending a DM_SETDEFID message to change the default button will not always remove the default state border from the first push button. In these cases, the application should send a BM_SETSTYLE message to change the first push button border style.

Return Values

The return value is always TRUE.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Dialog Boxes Overview, Dialog Box Messages, BM_SETSTYLE, DefDlgProc, DM_GETDEFID, EM_SETLIMITTEXT, WM_GETDLGCODE


WM_CTLCOLORDLG

The WM_CTLCOLORDLG message is sent to a dialog box before the system draws the dialog box. By responding to this message, the dialog box can set its text and background colors by using the given display device context handle.

WM_CTLCOLORDLG
hdcDlg = (HDC) wParam;   // handle of dialog box display context
hwndDlg = (HWND) lParam; // handle of dialog box

Parameters

hdcDlg
Value of wParam. Identifies the device context for the dialog box.
hwndDlg
Value of lParam. Identifies the dialog box.

Return Values

If an application processes this message, it must return the handle of a brush. The system uses the brush to paint the background of the dialog box.

Default Action

The DefWindowProc function selects the default system colors for the dialog box.

Remarks

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_CTLCOLORDLG message is never sent between threads. It is sent only within one thread.

Note that the WM_CTLCOLORDLG message is sent to the dialog box itself; all of the other WM_CTLCOLOR* messages are sent to the owner of the control.

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.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Dialog Boxes Overview, Dialog Box Messages, DefWindowProc, RealizePalette, SelectPalette, WM_CTLCOLORBTN, WM_CTLCOLOREDIT, WM_CTLCOLORLISTBOX, WM_CTLCOLORMSGBOX, WM_CTLCOLORSCROLLBAR, WM_CTLCOLORSTATIC


WM_CTLCOLORMSGBOX

The WM_CTLCOLORMSGBOX message is obsolete. It is included for compatibility with earlier versions of the system. Current versions of Windows and Windows NT do not send this message.

See Also

Dialog Boxes Overview, Dialog Box Messages


WM_ENTERIDLE

The WM_ENTERIDLE message is sent to the owner window of a modal dialog box or menu that is entering an idle state. A modal dialog box or menu enters an idle state when no messages are waiting in its queue after it has processed one or more previous messages.

WM_ENTERIDLE
fuSource = wParam;    // idle-source flag
hwnd = (HWND) lParam; // handle of dialog box or owner window

Parameters

fuSource
Value of wParam. Specifies whether the message is the result of a dialog box or a menu being displayed. This parameter can be one of the following values:
Value | Meaning
MSGF_DIALOGBOX | The system is idle because a dialog box is displayed.
MSGF_MENU | The system is idle because a menu is displayed.

hwnd
Value of lParam. Contains the handle of the dialog box (if fuSource is MSGF_DIALOGBOX) or of the window containing the displayed menu (if fuSource is MSGF_MENU).

Return Values

An application should return zero if it processes this message.

Remarks

You can suppress the WM_ENTERIDLE message for a dialog box by creating the dialog box with the DS_NOIDLEMSG style.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Dialog Boxes Overview, Dialog Box Messages, DefWindowProc


WM_GETDLGCODE

The WM_GETDLGCODE message is sent to the window procedure associated with a control. By default, the system handles all keyboard input to the control; the system interprets certain types of keyboard input as dialog box navigation keys. To override this default behavior, the control can respond to the WM_GETDLGCODE message to indicate the types of input it wants to process itself.

WM_GETDLGCODE
wParam;                // not used
pMsg = (LPMSG) lParam; // pointer to an MSG structure

Parameters

pMsg
The value of lParam is NULL if the system is performing a query, or lParam is a pointer to an MSG structure.

Return Values

The return value is one or more of the following values, indicating which type of input the application processes.

Value | Meaning
DLGC_BUTTON | Button.
DLGC_DEFPUSHBUTTON | Default push button.
DLGC_HASSETSEL | EM_SETSEL messages.
DLGC_RADIOBUTTON | Radio button.
DLGC_STATIC | Static control.
DLGC_UNDEFPUSHBUTTON | Non-default push button.
DLGC_WANTALLKEYS | All keyboard input.
DLGC_WANTARROWS | Direction keys.
DLGC_WANTCHARS | WM_CHAR messages.
DLGC_WANTMESSAGE | All keyboard input (the application passes this message in the MSG structure to the control).
DLGC_WANTTAB | tab key.

Default Action

The DefWindowProc function returns zero.

Remarks

Although the DefWindowProc function always returns zero in response to the WM_GETDLGCODE message, the window procedure for the predefined control classes return a code appropriate for each class.

The WM_GETDLGCODE message and the returned values are useful only with user-defined dialog box controls or standard controls modified by subclassing.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Dialog Boxes Overview, Dialog Box Messages, DefWindowProc, MSG, EM_SETSEL, WM_CHAR


WM_INITDIALOG

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
hwndFocus = (HWND) wParam; // handle of control to receive focus
lInitParam = lParam;       // initialization parameter

Parameters

hwndFocus
Value of wParam. Identifies the control to receive the default keyboard focus. The system assigns the default keyboard focus only if the dialog box procedure returns TRUE.
lInitParam
Value of lParam. Specifies additional initialization data. This data is passed to the system as the lParamInit 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 Values

The dialog box procedure should return TRUE to direct the system to set the keyboard focus to the control given by hwndFocus. 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.

Remarks

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 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.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Dialog Boxes Overview, Dialog Box Messages, CreateDialogIndirectParam, CreateDialogParam, DialogBoxIndirectParam, DialogBoxParam, PROPSHEETPAGE, SetFocus


WM_NEXTDLGCTL

The WM_NEXTDLGCTL message is sent to a dialog box procedure to set the keyboard focus to a different control in the dialog box.

WM_NEXTDLGCTL
wCtlFocus = wParam;              // identifies control for focus
fHandle = (BOOL) LOWORD(lParam); // wParam handle flag

Parameters

wCtlFocus
Value of wParam. If the fHandle parameter is TRUE, the wCtlFocus parameter identifies the control that receives the focus. If fHandle is FALSE, wCtlFocus is a flag that indicates whether the next or previous control with the WS_TABSTOP style receives the focus. If wCtlFocus is zero, the next control receives the focus; otherwise, the previous control with the WS_TABSTOP style receives the focus.
fHandle
Value of lParam. Contains a flag that indicates how the system uses the wCtlFocus parameter. If the fHandle parameter is TRUE, wCtlFocus is a handle associated with the control that receives the focus; otherwise, wCtlFocus is a flag that indicates whether the next or previous control with the WS_TABSTOP style receives the focus.

Return Values

An application should return zero if it processes this message.

Remarks

The effect of this message differs from that of the SetFocus function because WM_NEXTDLGCTL modifies the border around the control.

Do not use the SendMessage function to send a WM_NEXTDLGCTL message if your application will concurrently process other messages that set the focus. Use the PostMessage function instead.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Dialog Boxes Overview, Dialog Box Messages, PostMessage, SendMessage, SetFocus


Messages and Message Queues

This overview describes messages and message queues and how to use them in your Win32-based application.


About Messages and Message Queues

Unlike MS-DOS-based applications, Win32-based applications are event-driven. They do not make explicit function calls (such as C run-time library calls) to obtain input. Instead, they wait for the system to pass input to them.

The system passes all input for an application to the various windows in the application. Each window has a function, called a window procedure, that the system calls whenever it has input for the window. The window procedure processes the input and returns control to the system. For more information about window procedures, see Window Procedures.


Windows Messages

The system passes input to a window procedure in the form of messages. Messages are generated by both the system and applications. The system generates a message at each input event — for example, when the user types, moves the mouse, or clicks a control such as a scroll bar. The system also generates messages in response to changes in the system brought about by an application, such as when an application changes the pool of system font resources or resizes one of its windows. An application can generate messages to direct its own windows to perform tasks or to communicate with windows in other applications.

The system sends a message to a window procedure with a set of four parameters: a window handle, a message identifier, and two 32-bit values called message parameters. The window handle identifies the window for which the message is intended. The system uses it to determine which window procedure should receive the message.

A message identifier is a named constant that identifies the purpose of a message. When a window procedure receives a message, it uses a message identifier to determine how to process the message. For example, the message identifier WM_PAINT tells the window procedure that the window's client area has changed and must be repainted.

Message parameters specify data or the location of data used by a window procedure when processing a message. The meaning and value of the message parameters depend on the message. A message parameter can contain an integer, packed bit flags, a pointer to a structure containing additional data, and so on. When a message does not use message parameters, they are typically set to NULL. A window procedure must check the message identifier to determine how to interpret the message parameters.


Message Routing

The system uses two methods to route messages to a window procedure: posting messages to a first-in, first-out queue called a message queue, a system-defined memory object that temporarily stores messages, and sending messages directly to a window procedure.

Messages posted to a message queue are called queued messages. They are primarily the result of user input entered through the mouse or keyboard, such as WM_MOUSEMOVE, WM_LBUTTONDOWN, WM_KEYDOWN, and WM_CHAR messages. Other queued messages include the timer, paint, and quit messages: WM_TIMER, WM_PAINT, and WM_QUIT. Most other messages, which are sent directly to a window procedure, are called nonqueued messages.


Queued Messages

The system can display any number of windows at a time. To route mouse and keyboard input to the appropriate window, the system uses message queues.

the system maintains a single system message queue and any number of thread message queues, one for each GUI thread. To avoid the overhead of creating a message queue for non-GUI threads, all threads are created initially without a message queue. The system creates a thread's message queue only when the thread makes its first call to one of the Win32 User or GDI functions.

Whenever the user moves the mouse, clicks the mouse buttons, or types on the keyboard, the device driver for the mouse or keyboard converts the input into messages and places them in the system message queue. The system removes the messages, one at a time, from the system message queue, examines them to determine the destination window, and then posts them to the message queue of the thread that created the destination window. A thread's message queue receives all mouse and keyboard messages for the windows created by the thread. The thread removes messages from its queue and directs the system to send them to the appropriate window procedure for processing.

With the exception of the WM_PAINT message, the system always posts messages at the end of a message queue. This ensures that a window receives its input messages in the proper first-in, first-out (FIFO) sequence. The WM_PAINT message, however, is kept in the queue and is forwarded to the window procedure only when the queue contains no other messages. Multiple WM_PAINT messages for the same window are combined into a single WM_PAINT message, consolidating all invalid parts of the client area into a single area. Combining WM_PAINT messages reduces the number of times a window must redraw the contents of its client area.

The system posts a message to a thread's message queue by filling an MSG structure and then copying it to the message queue. Information in MSG includes: the handle of the window for which the message is intended, the message identifier, the two message parameters, the time the message was posted, and the mouse cursor position. A thread can post a message to its own message queue or to the queue of another thread by using the PostMessage or PostThreadMessage function.

An application can remove a message from its queue by using the GetMessage function. To examine a message without removing it from its queue, an application can use the PeekMessage function. This function fills MSG with information about the message.

After removing a message from its queue, an application can use the DispatchMessage function to direct the system to send the message to a window procedure for processing. DispatchMessage takes a pointer to MSG that was filled by a previous call to the GetMessage or PeekMessage function. DispatchMessage passes the window handle, the message identifier, and the two message parameters to the window procedure, but it does not pass the time the message was posted or mouse cursor position. An application can retrieve this information by calling the GetMessageTime and GetMessagePos functions while processing a message.

A thread can use the WaitMessage function to yield control to other threads when it has no messages in its message queue. The function suspends the thread and does not return until a new message is placed in the thread's message queue.

You can call the SetMessageExtraInfo function to associate a 32-bit value with the current thread's message queue. Then call the GetMessageExtraInfo function to get the value associated with the last message retrieved by the GetMessage or PeekMessage function.


Nonqueued Messages

Nonqueued messages are sent immediately to the destination window procedure, bypassing the system message queue and thread message queue. The system typically sends nonqueued messages to notify a window of events that affect it. For example, when the user activates a new application window, the system sends the window a series of messages, including WM_ACTIVATE, WM_SETFOCUS, and WM_SETCURSOR. These messages notify the window that it has been activated, that keyboard input is being directed to the window, and that the mouse cursor has been moved within the borders of the window. Nonqueued messages can also result when an application calls certain system functions. For example, the system sends the WM_WINDOWPOSCHANGED message after an application uses the SetWindowPos function to move a window.


Message Handling

An application must remove and process messages posted to the message queues of its threads. A single-threaded application usually uses a message loop in its WinMain function to remove and send messages to the appropriate window procedures for processing. Applications with multiple threads can include a message loop in each thread that creates a window. The following sections describe how a message loop works and explain the role of a window procedure:

  • Message Loop
  • Window Procedure


Message Loop

A simple message loop consists of one function call to each of these three functions: GetMessage, TranslateMessage, and DispatchMessage.

MSG msg;

while( GetMessage( &msg, NULL, 0, 0 ) )
{
    TranslateMessage( &msg );
    DispatchMessage( &msg );
}

The GetMessage function retrieves a message from the queue and copies it to a structure of type MSG. It returns a nonzero value, unless it encounters the WM_QUIT message, in which case it returns FALSE and ends the loop. In a single-threaded application, ending the message loop is often the first step in closing the application. An application can end its own loop by using the PostQuitMessage function, typically in response to the WM_DESTROY message in the window procedure of the application's main window.

If you specify a window handle as the second parameter of GetMessage, only messages for the specified window are retrieved from the queue. GetMessage can also filter messages in the queue, retrieving only those messages that fall within a specified range. For more information about filtering messages, see Message Filtering.

A thread's message loop must include TranslateMessage if the thread is to receive character input from the keyboard. The system generates virtual-key messages (WM_KEYDOWN and WM_KEYUP) each time the user presses a key. A virtual-key message contains a virtual-key code that identifies which key was pressed, but not its character value. To retrieve this value, the message loop must contain TranslateMessage, which translates the virtual-key message into a character message (WM_CHAR) and places it back into the application message queue. The character message can then be removed upon a subsequent iteration of the message loop and dispatched to a window procedure.

The DispatchMessage function sends a message to the window procedure associated with the window handle specified in the MSG structure. If the window handle is HWND_TOPMOST, DispatchMessage sends the message to the window procedures of all top-level windows in the system. If the window handle is NULL, DispatchMessage does nothing with the message.

An application's main thread starts its message loop after initializing the application and creating at least one window. Once started, the message loop continues to retrieve messages from the thread's message queue and to dispatch them to the appropriate windows. The message loop ends when the GetMessage function removes the WM_QUIT message from the message queue.

Only one message loop is needed for a message queue, even if an application contains many windows. DispatchMessage always dispatches the message to the proper window; this is because each message in the queue is an MSG structure that contains the handle of the window to which the message belongs.

You can modify a message loop in a variety of ways. For example, you can retrieve messages from the queue without dispatching them to a window. This is useful for applications that post messages not specifying a window. You can also direct GetMessage to search for specific messages, leaving other messages in the queue. This is useful if you must temporarily bypass the usual FIFO order of the message queue.

An application that uses accelerator keys must be able to translate keyboard messages into command messages. To do this, the application's message loop must include a call to the TranslateAccelerator function. For more information about accelerator keys, see Keyboard Accelerators.

If a thread uses a modeless dialog box, the message loop must include the IsDialogMessage function so that the dialog box can receive keyboard input.


Window Procedure

A window procedure is a function that receives and processes all messages sent to the window. Every window class has a window procedure, and every window created with that class uses that same window procedure to respond to messages.

The system sends a message to a window procedure by passing the message data as arguments to the procedure. The window procedure then performs an appropriate action for the message; it checks the message identifier and, while processing the message, uses the information specified by the message parameters.

A window procedure does not usually ignore a message. If it does not process a message, it must send the message back to the system for default processing. The window procedure does this by calling the DefWindowProc function, which performs a default action and returns a message result. The window procedure must then return this value as its own message result. Most window procedures process just a few messages and pass the others on to the system by calling DefWindowProc.

Because a window procedure is shared by all windows belonging to the same class, it can process messages for several different windows. To identify the specific window affected by the message, a window procedure can examine the window handle passed with a message. For more information about window procedures, see Window Procedures.


Posting and Sending Messages

Any application can post and send messages. Like the system, an application posts a message by copying it to a message queue and sends a message by passing the message data as arguments to a window procedure. To post messages, an application uses the PostMessage function. An application can send a message by calling the SendMessage, BroadcastSystemMessage, SendMessageCallback, SendMessageTimeout, SendNotifyMessage, or SendDlgItemMessage function.

An application typically posts a message to notify a specific window to perform a task. PostMessage creates an MSG structure for the message and copies the message to the message queue. The application's message loop eventually retrieves the message and dispatches it to the appropriate window procedure.

An application typically sends a message to notify a window procedure to perform a task immediately. The SendMessage function sends the message to the window procedure corresponding to the given window. The function waits until the window procedure completes processing and then returns the message result. Parent and child windows often communicate by sending messages to each other. For example, a parent window that has an edit control as its child window can set the text of the control by sending a message to it. The control can notify the parent window of changes to the text that are carried out by the user by sending messages back to the parent.

The SendMessageCallback function also sends a message to the window procedure corresponding to the given window. However, this function returns immediately. After the window procedure processes the message, the system calls the specified callback function. For more information about the callback function, see the SendAsyncProc function.

Occasionally, you may want to send or post a message to all top-level windows in the system. For example, if the application changes the system time, it must notify all top-level windows about the change by sending a WM_TIMECHANGE message. An application can send or post a message to all top-level windows by calling the SendMessage or PostMessage function and specifying HWND_TOPMOST in the hwnd parameter. You can also broadcast a message to all applications by calling the BroadcastSystemMessage function and specifying BSM_APPLICATIONS in the lpdwRecipients parameter.

An application can post a message without specifying a window. If the application supplies a NULL window handle when calling PostMessage, the message is posted to the queue associated with the current thread. Because no window handle is specified, the application must process the message in the message loop. This is one way to create a message that applies to the entire application, instead of to a specific window.

By using the InSendMessage or InSendMessageEx function, a window procedure can determine whether it is processing a message sent by another thread. This capability is useful when message processing depends on the origin of the message.

A common programming error is to assume that the PostMessage function always posts a message. This is not true when the message queue is full. An application should check the return value of the PostMessage function to determine whether the message has been posted and, if it has not been, repost it.


Message Types

This section describes the two types of messages:

  • system-defined messages
  • application-defined messages


System-Defined Messages

The system sends or posts a system-defined message when it communicates with an application. It uses these messages to control the operations of applications and to provide input and other information for applications to process. An application can also send or post system-defined messages. Applications generally use these messages to control the operation of control windows created by using preregistered window classes.

Each system message has a unique message identifier and a corresponding symbolic constant (defined in the SDK header files) that states the purpose of the message. For example, the WM_PAINT constant requests that a window paint its contents.

Symbolic constants specify the category to which system-defined messages belong. The prefix of the constant identifies the type of window that can interpret and process the message. Following are the prefixes and their related message categories.

Prefix | Message category
ABM | Application desktop toolbar
BM | Button control
CB | Combo box control
CDM | Common dialog box
DBT | Device
DL | Drag list box
DM | Default push button control
EM | Edit control
HDM | Header control
LB | List box control
LVM | List view control
PBM | Progress bar
PSM | Property sheet
SB | Status bar window
SBM | Scroll bar control
STM | Static control
TB | Toolbar
TBM | Trackbar
TCM | Tab control
TTM | Tooltip control
TVM | Tree-view control
UDM | Up-down control
WM | General window

General window messages cover a wide range of information and requests, including messages for mouse and keyboard input, menu and dialog box input, window creation and management, and dynamic data exchange (DDE).


Application-Defined Messages

An application can create messages to be used by its own windows or to communicate with windows in other processes. If an application creates its own messages, the window procedure that receives them must interpret the messages and provide appropriate processing.

Message-identifier values are used as follows:

  • The system reserves message-identifier values in the range 0x0000 through 0x03FF (the value of WM_USER – 1) for system-defined messages. Applications cannot use these values for private messages.
  • Values in the range 0x0400 (the value of WM_USER) through 0x7FFF are available for message identifiers for private window classes.
  • If your application is marked version 4.0, you can use message-identifier values in the range 0x8000 (WM_APP) through 0xBFFF for private messages.
  • The system returns a message identifier in the range 0xC000 through 0xFFFF when an application calls the RegisterWindowMessage function to register a message. The message identifier returned by this function is guaranteed to be unique throughout the system. Use of this function prevents conflicts that can arise if other applications use the same message identifier for different purposes.


Message Filtering

An application can choose specific messages to retrieve from the message queue (while ignoring other messages) by using the GetMessage or PeekMessage function to specify a message filter. The filter is a range of message identifiers (specified by a first and last identifier), a window handle, or both. GetMessage and PeekMessage use a message filter to select which messages to retrieve from the queue. Message filtering is useful if an application must search the message queue for messages that have arrived later in the queue.

Any application that filters messages must ensure that a message satisfying the message filter can be posted. For example, if an application filters for a WM_CHAR message in a window that does not receive keyboard input, the GetMessage function does not return. This effectively "hangs" the application.

To filter for keyboard, mouse, and DDE messages, an application can use the WM_KEYFIRST and WM_KEYLAST, WM_MOUSEFIRST and WM_MOUSELAST messages, and WM_DDE_FIRST and WM_DDE_LAST constants.


Message Deadlocks

A thread that calls the SendMessage function to send a message to another thread cannot continue executing until the window procedure that receives the message returns. If the receiving thread yields control while processing the message, the sending thread cannot continue executing, because it is waiting for SendMessage to return. If the receiving thread then sends a message to the calling thread while it is blocked, it can cause a deadlock to occur.

Note that the receiving thread need not yield control explicitly; calling any of the following functions can cause a thread to yield control implicitly.

DialogBox
DialogBoxIndirect
DialogBoxIndirectParam
DialogBoxParam
GetMessage
MessageBox
PeekMessage

To avoid potential deadlocks, consider using the SendNotifyMessage or SendMessageTimeout functions. Otherwise, a window procedure can determine whether a message it has received was sent by another thread by calling the InSendMessage function. Before calling any of the functions in the preceding list while processing a message, the window procedure should first call InSendMessage. If this function returns TRUE, the window procedure must call the ReplyMessage function before any function that causes the thread to yield control.


Using Messages and Message Queues

  • Creating a message loop
  • Examining a message queue
  • Posting a message
  • Sending a message


Creating a Message Loop

The system automatically creates a message queue for each thread. If the thread creates one or more windows, a message loop must be provided; this message loop retrieves messages from the thread's message queue and dispatches them to the appropriate window procedures.

Because the system directs messages to individual windows in an application, a thread must create at least one window before starting its message loop. Most Win32-based applications contain a single thread that creates windows. A typical application registers the window class for its main window, creates and shows the main window, and then starts its message loop — all in the WinMain function.

You create a message loop by using the GetMessage and DispatchMessage functions. If your application must obtain character input from the user, include the TranslateMessage function in the loop. TranslateMessage translates virtual-key messages into character messages. The following example shows the message loop in the WinMain function of a simple Win32-based application.

HINSTANCE hinst;
HWND hwndMain;

int PASCAL WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    LPSTR lpszCmdLine, int nCmdShow)
{
    MSG msg;
    WNDCLASS wc;
    UNREFERENCED_PARAMETER(lpszCmdLine);

    // Register the window class for the main window.

    if (!hPrevInstance)
    {
        wc.style = 0;
        wc.lpfnWndProc = (WNDPROC) WndProc;
        wc.cbClsExtra = 0;
        wc.cbWndExtra = 0;
        wc.hInstance = hInstance;
        wc.hIcon = LoadIcon((HINSTANCE) NULL,
            IDI_APPLICATION);
        wc.hCursor = LoadCursor((HINSTANCE) NULL,
            IDC_ARROW);
        wc.hbrBackground = GetStockObject(WHITE_BRUSH);
        wc.lpszMenuName =  "MainMenu";
        wc.lpszClassName = "MainWndClass";

        if (!RegisterClass(&wc))
            return FALSE;
    }

    hinst = hInstance;  // save instance handle

    // Create the main window.

    hwndMain = CreateWindow("MainWndClass", "Sample",
        WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
        CW_USEDEFAULT, CW_USEDEFAULT, (HWND) NULL,
        (HMENU) NULL, hinst, (LPVOID) NULL);

    // If the main window cannot be created, terminate
    // the application.

    if (!hwndMain)
        return FALSE;

    // Show the window and paint its contents.

    ShowWindow(hwndMain, nCmdShow);
    UpdateWindow(hwndMain);

    // Start the message loop.

    while (GetMessage(&msg, (HWND) NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    // Return the exit code to the system.

    return msg.wParam;
}

The following example shows a message loop for a thread that uses accelerators and displays a modeless dialog box. When TranslateAccelerator or IsDialogMessage returns TRUE (indicating that the message has been processed), TranslateMessage and DispatchMessage are not called. The reason for this is that TranslateAccelerator and IsDialogMessage perform all necessary translating and dispatching of messages.

HWND hwndMain;
HWND hwndDlgModeless = NULL;
MSG msg;
HACCEL haccel;
//
// Perform initialization and create a main window.
//

while (GetMessage(&msg, (HWND) NULL, 0, 0))
{
    if (hwndDlgModeless == (HWND) NULL ||
            !IsDialogMessage(hwndDlgModeless, &msg) &&
            !TranslateAccelerator(hwndMain, haccel,
                &msg))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}


Examining a Message Queue

Occasionally, an application needs to examine the contents of a thread's message queue from outside the thread's message loop. For example, if an application's window procedure performs a lengthy drawing operation, you may want the user to be able to interrupt the operation. Unless your application periodically examines the message queue during the operation for mouse and keyboard messages, it will not respond to user input until after the operation has completed. The reason for this is that the DispatchMessage function in the thread's message loop does not return until the window procedure finishes processing a message.

You can use the PeekMessage function to examine a message queue during a lengthy operation. PeekMessage is similar to the GetMessage function; both check a message queue for a message that matches the filter criteria and then copy the message to an MSG structure. The main difference between the two functions is that GetMessage does not return until a message matching the filter criteria is placed in the queue, whereas PeekMessage returns immediately regardless of whether a message is in the queue.

The following example shows how to use PeekMessage to examine a message queue for mouse clicks and keyboard input during a lengthy operation.

HWND hwnd;
BOOL fDone;
MSG msg;

// Begin the operation and continue until it is complete
// or until the user clicks the mouse or presses a key.

fDone = FALSE;
while (!fDone)
{
    fDone = DoLengthyOperation(); // application-defined function

    // Remove any messages that may be in the queue. If the
    // queue contains any mouse or keyboard
    // messages, end the operation.

    while (PeekMessage(&msg, hwnd,  0, 0, PM_REMOVE))
    {
        switch(msg.message)
        {
            case WM_LBUTTONDOWN:
            case WM_RBUTTONDOWN:
            case WM_KEYDOWN:
                //
                // Perform any required cleanup.
                //
                fDone = TRUE;
        }
    }
}

Other functions, including GetQueueStatus and GetInputState, also allow you to examine the contents of a thread's message queue. GetQueueStatus returns an array of flags that indicates the types of messages in the queue; using it is the fastest way to discover whether the queue contains any messages. GetInputState returns TRUE if the queue contains mouse or keyboard messages. Both of these functions can be used to determine whether the queue contains messages that need to be processed.


Posting a Message

You can post a message to a message queue by using the PostMessage function. PostMessage places a message at the end of a thread's message queue and returns immediately, without waiting for the thread to process the message. The function's parameters include a window handle, a message identifier, and two message parameters. The system copies these parameters to an MSG structure, fills the time and pt members of the structure, and places the structure in the message queue.

The system uses the window handle passed with the PostMessage function to determine which thread message queue should receive the message. If the handle is HWND_TOPMOST, the system posts the message to the thread message queues of all top-level windows.

You can use the PostThreadMessage function to post a message to a specific thread message queue. PostThreadMessage is similar to PostMessage, except the first parameter is a thread identifier rather than a window handle. You can retrieve the thread identifier by calling the GetCurrentThreadId function.

Use the PostQuitMessage function to exit a message loop. PostQuitMessage posts the WM_QUIT message to the currently executing thread. The thread's message loop terminates and returns control to the system when it encounters the WM_QUIT message. An application usually calls PostQuitMessage in response to the WM_DESTROY message, as shown in the following example.

case WM_DESTROY:

    // Perform cleanup tasks.

    PostQuitMessage(0);
    break;


Sending a Message

The SendMessage function is used to send a message directly to a window procedure. SendMessage calls a window procedure and waits for that procedure to process the message and return a result.

A message can be sent to any window in the system; all that is required is a window handle. The system uses the handle to determine which window procedure should receive the message.

Before processing a message that may have been sent from another thread, a window procedure should first call the InSendMessage function. If this function returns TRUE, the window procedure should call ReplyMessage before any function that causes the thread to yield control, as shown in the following example.

case WM_USER + 5:
    if (InSendMessage())
        ReplyMessage(TRUE);

    DialogBox(hInst, "MyDialogBox", hwndMain, (DLGPROC) MyDlgProc);
    break;

A number of messages can be sent to controls in a dialog box. These control messages set the appearance, behavior, and content of controls or retrieve information about controls. For example, the CB_ADDSTRING message can add a string to a combo box, and the BM_SETCHECK message can set the check state of a check box or radio button.

Use the SendDlgItemMessage function to send a message to a control, specifying the identifier of the control and the handle of the dialog box window that contains the control. The following example, taken from a dialog box procedure, copies a string from a combo box's edit control into its list box. The example uses SendDlgItemMessage to send a CB_ADDSTRING message to the combo box.

HWND hwndCombo;
int cTxtLen;
PSTR pszMem;

switch (uMsg)
{
    case WM_COMMAND:
        switch (LOWORD(wParam))
        {
            case IDD_ADDCBITEM:
                // Get the handle of the combo box and the
                // length of the string in the edit control
                // of the combo box.

                hwndCombo = GetDlgItem(hwndDlg, IDD_COMBO);
                cTxtLen = GetWindowTextLength(hwndCombo);

                // Allocate memory for the string and copy
                // the string into the memory.

                pszMem = (PSTR) VirtualAlloc((LPVOID) NULL,
                    (DWORD) (cTxtLen + 1), MEM_COMMIT,
                    PAGE_READWRITE);
                GetWindowText(hwndCombo, pszMem,
                    cTxtLen + 1);

                // Add the string to the list box of the
                // combo box and remove the string from the
                // edit control of the combo box.

                if (*pszMem != NULL)
                {
                    SendDlgItemMessage(hwndDlg, IDD_COMBO,
                        CB_ADDSTRING, 0,
                        (DWORD) ((LPSTR) pszMem));
                    SetWindowText(hwndCombo, (LPSTR) NULL);
                }

                // Free the memory and return.

                VirtualFree(pszMem, 0, MEM_RELEASE);
                return TRUE;
            //
            // Process other dialog box commands.
            //

        }
    //
    // Process other dialog box messages.
    //

}


Messages and Message Queues Reference

Message and Message Queue Reference

The following elements are used with messages and message queues.

  • Message and Message Queue Functions
  • Message and Message Queue Structures
  • Message and Message Queue Messages


Messages and Message Queues Functions

Message and Message Queue Functions

The following functions are used with messages and message queues.

BroadcastSystemMessage
DispatchMessage
GetInputState
GetMessage
GetMessageExtraInfo
GetMessagePos
GetMessageTime
GetQueueStatus
InSendMessage
InSendMessageEx
PeekMessage
PostMessage
PostQuitMessage
PostThreadMessage
RegisterWindowMessage
ReplyMessage
SendAsyncProc
SendMessage
SendMessageCallback
SendMessageTimeout
SendNotifyMessage
SetMessageExtraInfo
TranslateMessage
WaitMessage

Obsolete Functions

PostAppMessage
SetMessageQueue


BroadcastSystemMessage

The BroadcastSystemMessage function sends a message to the specified recipients. The recipients can be applications, installable drivers, network drivers, system-level device drivers, or any combination of these system components.

long BroadcastSystemMessage(
  DWORD dwFlags,
  LPDWORD lpdwRecipients,
  UINT uiMessage,
  WPARAM wParam,
  LPARAM lParam
);

Parameters

dwFlags
Option flags. Can be a combination of the following values:
Value | Meaning
BSF_FLUSHDISK | Flush the disk after each recipient processes the message.
BSF_FORCEIFHUNG | Continue to broadcast the message, even if the time-out period elapses or one of the recipients is hung..
BSF_IGNORECURRENTTASK | Do not send the message to windows that belong to the current task. This prevents an application from receiving its own message.
BSF_NOHANG | Force a hung application to time out. If one of the recipients times out, do not continue broadcasting the message.
BSF_NOTIMEOUTIFNOTHUNG | Wait for a response to the message, as long as the recipient is not hung. Do not time out.
BSF_POSTMESSAGE | Post the message. Do not use in combination with BSF_QUERY.
BSF_QUERY | Send the message to one recipient at a time, sending to a subsequent recipient only if the current recipient returns TRUE.

lpdwRecipients
Pointer to a variable that contains and receives information about the recipients of the message. The variable can be a combination of the following values:
Value | Meaning
BSM_ALLCOMPONENTS | Broadcast to all system components.
BSM_ALLDESKTOPS | Windows NT: Broadcast to all desktops. Requires the SE_TCB_NAME privilege.
BSM_APPLICATIONS | Broadcast to applications.
BSM_INSTALLABLEDRIVERS | Windows 95: Broadcast to installable drivers.
BSM_NETDRIVER | Windows 95: Broadcast to network drivers.
BSM_VXDS | Windows 95: Broadcast to all system-level device drivers.

When the function returns, this variable receives a combination of these values identifying which recipients actually received the message.

If this parameter is NULL, the function broadcasts to all components.

uiMessage
Identifier of the system message.
wParam
32-bit message-specific value.
lParam
32-bit message-specific value.

Return Values

If the function succeeds, the return value is a positive value.

If the function is unable to broadcast the message, the return value is –1.

If the dwFlags parameter is BSF_QUERY and at least one recipient returned BROADCAST_QUERY_DENY to the corresponding message, the return value is zero. To get extended error information, call GetLastError.

Remarks

If BSF_QUERY is not specified, the function sends the specified message to all requested recipients, ignoring values returned by those recipients.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions


DispatchMessage

The DispatchMessage function dispatches a message to a window procedure. It is typically used to dispatch a message retrieved by the GetMessage function.

LONG DispatchMessage(
  CONST MSG *lpmsg   // pointer to structure with message
);

Parameters

lpmsg
Pointer to an MSG structure that contains the message.

Return Values

The return value specifies the value returned by the window procedure. Although its meaning depends on the message being dispatched, the return value generally is ignored.

Remarks

The MSG structure must contain valid message values. If the lpmsg parameter points to a WM_TIMER message and the lParam parameter of the WM_TIMER message is not NULL, lParam points to a function that is called instead of the window procedure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, GetMessage, MSG, PeekMessage, TranslateMessage, WM_TIMER


GetInputState

The GetInputState function determines whether there are mouse-button or keyboard messages in the calling thread's message queue.

BOOL GetInputState(VOID)

Parameters

This function has no parameters.

Return Values

If the queue contains one or more new mouse-button or keyboard messages, the return value is nonzero.

If the there are no new mouse-button or keyboard messages in the queue, the return value is zero.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, GetQueueStatus


GetMessage

The GetMessage function retrieves a message from the calling thread's message queue and places it in the specified structure. This function can retrieve both messages associated with a specified window and thread messages posted via the PostThreadMessage function. The function retrieves messages that lie within a specified range of message values. GetMessage does not retrieve messages for windows that belong to other threads or applications.

BOOL GetMessage(
  LPMSG lpMsg,         // address of structure with message
  HWND hWnd,           // handle of window
  UINT wMsgFilterMin,  // first message
  UINT wMsgFilterMax   // last message
);

Parameters

lpMsg
Pointer to an MSG structure that receives message information from the thread's message queue.
hWnd
Handle to the window whose messages are to be retrieved. One value has a special meaning:
Value | Meaning
NULL | GetMessage retrieves messages for any window that belongs to the calling thread and thread messages posted to the calling thread via PostThreadMessage.

wMsgFilterMin
Specifies the integer value of the lowest message value to be retrieved.
wMsgFilterMax
Specifies the integer value of the highest message value to be retrieved.

Return Values

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

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

If there is an error, the return value is -1. For example, the function fails if hWnd is an invalid window handle or lpMsg is an invalid pointer. To get extended error information, call GetLastError.

Remarks

An application typically uses the return value to determine whether to end the main message loop and exit the program.

The GetMessage function only retrieves messages associated with the window identified by the hWnd parameter or any of its children, as specified by the IsChild function, and within the range of message values given by the wMsgFilterMin and wMsgFilterMax parameters. If hWnd is NULL, GetMessage retrieves messages for any window that belongs to the calling thread and thread messages posted to the calling thread via PostThreadMessage. GetMessage does not retrieve messages for windows that belong to other threads nor for threads other than the calling thread, even if hWnd is not NULL. Thread messages, posted by the PostThreadMessage function, have a message hWnd value of NULL. If wMsgFilterMin and wMsgFilterMax are both zero, GetMessage returns all available messages (that is, no range filtering is performed).

The WM_KEYFIRST and WM_KEYLAST constants can be used as filter values to retrieve all messages related to keyboard input; the WM_MOUSEFIRST and WM_MOUSELAST constants can be used to retrieve all mouse messages. If the wMsgFilterMin and wMsgFilterMax parameters are both zero, the GetMessage function returns all available messages (that is, without performing any filtering).

GetMessage does not remove WM_PAINT messages from the queue. The messages remain in the queue until processed.

Note that the function return value can be nonzero, zero, or -1. Thus, you should avoid code like this:

while (GetMessage( lpMsg, hWnd, 0, 0)) ...

The possibility of a -1 return value means that such code can lead to fatal application errors.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, IsChild, MSG, PeekMessage, PostMessage, PostThreadMessage, WaitMessage


GetMessageExtraInfo

The GetMessageExtraInfo function gets the extra message information for the current thread. Extra message information is an application- or driver-defined 32-bit value associated with the current thread's message queue. You can use the SetMessageExtraInfo function to set a thread's extra message information, which will remain until the next call to GetMessage or PeekMessage.

LONG GetMessageExtraInfo(VOID)

Parameters

This function has no parameters.

Return Values

The return value specifies the extra information. The meaning of the extra information is device specific.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, GetMessage, PeekMessage, SetMessageExtraInfo


GetMessagePos

The GetMessagePos function returns a long value that gives the cursor position in screen coordinates. This position is the point occupied by the cursor when the last message retrieved by the GetMessage function occurred.

DWORD GetMessagePos(VOID)

Parameters

This function has no parameters.

Return Values

The return value specifies the x- and y-coordinates of the cursor position. The x-coordinate is the low order int and the y-coordinate is the high-order int.

Remarks

As noted above, the x-coordinate is in the low-order int of the return value; the y-coordinate is in the high-order int (both represent signed values because they can take negative values on systems with multiple monitors). If the return value is assigned to a variable, you can use the MAKEPOINTS macro to obtain a POINTS structure from the return value. You can also use the GET_X_LPARAM or GET_Y_LPARAM macro to extract the x- or y-coordinate.

To determine the current position of the cursor instead of the position when the last message occurred, use the GetCursorPos function.

Important

Do not use the LOWORD or HIWORD macros to extract the x- and y- coordinates of the cursor position because they return incorrect results on systems with multiple monitors. Systems with multiple monitor systems can have negative x- and y- coordinates, and LOWORD and HIWORD treat the coordinates as unsigned quantities.

Windows CE: For devices that use a stylus rather than a mouse, the cursor position is the position of the stylus on the touch screen when the last message retrieved by the GetMessage function occurred.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, GetCursorPos, GetMessage, GetMessageTime, HIWORD, LOWORD, MAKEPOINTS, POINTS


GetMessageTime

The GetMessageTime function returns the message time for the last message retrieved by the GetMessage function from the current thread's message queue. The time is a long integer that specifies the elapsed time, in milliseconds, from the time the system was started to the time the message was created (that is, placed in the thread's message queue).

LONG GetMessageTime(VOID)

Parameters

This function has no parameters.

Return Values

The return value specifies the message time.

Remarks

The return value from the GetMessageTime function does not necessarily increase between subsequent messages, because the value wraps to zero if the timer count exceeds the maximum value for a long integer.

To calculate time delays between messages, verify that the time of the second message is greater than the time of the first message; then, subtract the time of the first message from the time of the second message.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, GetMessage, GetMessagePos


GetQueueStatus

The GetQueueStatus function returns flags that indicate the type of messages found in the calling thread's message queue.

DWORD GetQueueStatus(
  UINT flags   // queue-status flags
);

Parameters

flags
Specifies queue-status flags giving the types of messages to check for. This parameter can be a combination of the following values:
Value | Meaning
QS_ALLEVENTS | An input, WM_TIMER, WM_PAINT, WM_HOTKEY, or posted message is in the queue.
QS_ALLINPUT | Any message is in the queue.
QS_ALLPOSTMESSAGE | A posted message (other than those listed here) is in the queue.
QS_HOTKEY | A WM_HOTKEY message is in the queue.
QS_INPUT | An input message is in the queue.
QS_KEY | A WM_KEYUP, WM_KEYDOWN, WM_SYSKEYUP, or WM_SYSKEYDOWN message is in the queue.
QS_MOUSE | A WM_MOUSEMOVE message or mouse-button message (WM_LBUTTONUP, WM_RBUTTONDOWN, and so on).
QS_MOUSEBUTTON | A mouse-button message (WM_LBUTTONUP, WM_RBUTTONDOWN, and so on).
QS_MOUSEMOVE | A WM_MOUSEMOVE message is in the queue.
QS_PAINT | A WM_PAINT message is in the queue.
QS_POSTMESSAGE | A posted message (other than those listed here) is in the queue.
QS_SENDMESSAGE | A message sent by another thread or application is in the queue.
QS_TIMER | A WM_TIMER message is in the queue.

Return Values

The high-order word of the return value indicates the types of messages currently in the queue. The low-order word indicates the types of messages that have been added to the queue and that are still in the queue since the last call to the GetQueueStatus, GetMessage, or PeekMessage function.

Remarks

The presence of a QS_ flag in the return value does not guarantee that a subsequent call to the GetMessage or PeekMessage function will return a message. GetMessage and PeekMessage perform some internal filtering that may cause the message to be processed internally. For this reason, the return value from GetQueueStatus should be considered only a hint as to whether GetMessage or PeekMessage should be called.

The QS_ALLPOSTMESSAGE and QS_POSTMESSAGE flags differ in when they are cleared. QS_POSTMESSAGE is cleared when you call GetMessage or PeekMessage, whether or not you are filtering messages. QS_ALLPOSTMESSAGE is cleared when you call GetMessage or PeekMessage without filtering messages (wMsgFilterMin and wMsgFilterMax are 0). This can be useful when you call PeekMessage multiple times to get messages in different ranges.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, GetInputState, GetMessage, PeekMessage


InSendMessage

The InSendMessage function determines whether the current window procedure is processing a message that was sent from another thread (in the same process or a different process) by a call to the SendMessage function.

BOOL InSendMessage(VOID);

Parameters

This function has no parameters.

Return Values

If the window procedure is processing a message sent to it from another thread using the SendMessage function, the return value is nonzero.

If the window procedure is not processing a message sent to it from another thread using the SendMessage function, the return value is zero.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, SendMessage


InSendMessageEx

[This is preliminary documentation and subject to change.]

The InSendMessageEx function determines whether the current window procedure is processing a message that was sent from another thread (in the same process or a different process). This function is similar to the InSendMessage function, but provides additional information about how the message was sent.

DWORD InSendMessageEx(
  LPVOID lpReserved      // must be NULL
);

Parameters

lpReserved
Reserved; must be NULL.

Return Values

If the message was not sent, the return value is ISMEX_NOSEND. Otherwise, the return value is one or more of the following values.

Value | Meaning
ISMEX_CALLBACK | The message was sent using the SendMessageCallback function. The thread that sent the message is not blocked.
ISMEX_NOTIFY | The message was sent using the SendNotifyMessage function. The thread that sent the message is not blocked.
ISMEX_REPLIED | The window procedure has processed the message. The thread that sent the message is no longer blocked.
ISMEX_SEND | The message was sent using the SendMessage or SendMessageTimeout function. If ISMEX_REPLIED is not set, the thread that sent the message is blocked.

QuickInfo

Windows NT: Requires version 5.0 or later.
Windows: Requires Windows 98.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, SendMessage, SendMessageCallback, SendMessageTimeout, SendNotifyMessage


PeekMessage

The PeekMessage function checks a thread message queue for a message and places the message (if any) in the specified structure.

BOOL PeekMessage(
  LPMSG lpMsg,         // pointer to structure for message
  HWND hWnd,           // handle to window
  UINT wMsgFilterMin,  // first message
  UINT wMsgFilterMax,  // last message
  UINT wRemoveMsg      // removal flags
);

Parameters

lpMsg
Pointer to an MSG structure that receives message information.
hWnd
Handle to the window whose messages are to be examined.
wMsgFilterMin
Specifies the value of the first message in the range of messages to be examined.
wMsgFilterMax
Specifies the value of the last message in the range of messages to be examined.
wRemoveMsg
Specifies how messages are handled. This parameter can be one of the following values:
Value | Meaning
PM_NOREMOVE | Messages are not removed from the queue after processing by PeekMessage.
PM_REMOVE | Messages are removed from the queue after processing by PeekMessage.

You can optionally combine the value PM_NOYIELD with either PM_NOREMOVE or PM_REMOVE. This flag prevents the system from releasing any thread that is waiting for the caller to go idle (see WaitForInputIdle).

By default, all message types are processed. To specify that only certain message should be processed, specify one of more of the following values:
Value | Meaning
PM_QS_INPUT | Windows NT 5.0 and Windows 98: Process mouse and keyboard messages.
PM_QS_PAINT | Windows NT 5.0 and Windows 98: Process paint messages.
PM_QS_POSTMESSAGE | Windows NT 5.0 and Windows 98: Process all posted messages, including timers and hotkeys.
PM_QS_SENDMESSAGE | Windows NT 5.0 and Windows 98: Process all sent messages.

Return Values

If a message is available, the return value is nonzero.

If no messages are available, the return value is zero.

Remarks

Unlike the GetMessage function, the PeekMessage function does not wait for a message to be placed in the queue before returning.

PeekMessage retrieves only messages associated with the window identified by the hWnd parameter or any of its children as specified by the IsChild function, and within the range of message values given by the wMsgFilterMin and wMsgFilterMax parameters. If hWnd is NULL, PeekMessage retrieves messages for any window that belongs to the current thread making the call. (PeekMessage does not retrieve messages for windows that belong to other threads.) If hWnd is –1, PeekMessage only returns messages with a hWnd value of NULL, as posted by the PostThreadMessage function. If wMsgFilterMin and wMsgFilterMax are both zero, PeekMessage returns all available messages (that is, no range filtering is performed).

The WM_KEYFIRST and WM_KEYLAST constants can be used as filter values to retrieve all keyboard messages; the WM_MOUSEFIRST and WM_MOUSELAST constants can be used to retrieve all mouse messages.

The PeekMessage function normally does not remove WM_PAINT messages from the queue. WM_PAINT messages remain in the queue until they are processed. However, if a WM_PAINT message has a null update region, PeekMessage does remove it from the queue.

Windows CE: WM_PAINT messages with a null update region are not removed from the queue.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, GetMessage, IsChild, MSG, WaitForInputIdle, WaitMessage


PostAppMessage

The PostAppMessage function is obsolete. The function is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should use the PostThreadMessage function.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions


PostMessage

The PostMessage function places (posts) a message in the message queue associated with the thread that created the specified window and then returns without waiting for the thread to process the message. Messages in a message queue are retrieved by calls to the GetMessage or PeekMessage function.

BOOL PostMessage(
  HWND hWnd,      // handle of destination window
  UINT Msg,       // message to post
  WPARAM wParam,  // first message parameter
  LPARAM lParam   // second message parameter
);

Parameters

hWnd
Handle to the window whose window procedure is to receive the message. Two values have special meanings:
Value | Meaning
HWND_BROADCAST | The message is posted to all top-level windows in the system, including disabled or invisible unowned windows, overlapped windows, and pop-up windows. The message is not posted to child windows.
NULL | The function behaves like a call to PostThreadMessage with the dwThreadId parameter set to the identifier of the current thread.

Msg
Specifies the message to be posted.
wParam
Specifies additional message-specific information.
lParam
Specifies additional message-specific information.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Applications that need to communicate using HWND_BROADCAST should use the RegisterWindowMessage function to obtain a unique message for inter-application communication.

If you send a message in the range below WM_USER to the asynchronous message functions (PostMessage, SendNotifyMessage, and SendMessageCallback), its message parameters can not include pointers. Otherwise, the operation will fail. The functions will return before the receiving thread has had a chance to process the message and the sender will free the memory before it is used.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, GetMessage, PeekMessage, SendMessageCallback, SendNotifyMessage


PostQuitMessage

The PostQuitMessage function indicates to the system that a thread has made a request to terminate (quit). It is typically used in response to a WM_DESTROY message.

VOID PostQuitMessage(
  int nExitCode   // exit code
);

Parameters

nExitCode
Specifies an application exit code. This value is used as the wParam parameter of the WM_QUIT message.

Return Values

This function does not return a value.

Remarks

The PostQuitMessage function posts a WM_QUIT message to the thread's message queue and returns immediately; the function simply indicates to the system that the thread is requesting to quit at some time in the future.

When the thread retrieves the WM_QUIT message from its message queue, it should exit its message loop and return control to the system. The exit value returned to the system must be the wParam parameter of the WM_QUIT message.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, GetMessage, PeekMessage, PostMessage, WM_DESTROY, WM_QUIT


PostThreadMessage

The PostThreadMessage function places (posts) a message in the message queue of the specified thread and then returns without waiting for the thread to process the message.

BOOL PostThreadMessage(
  DWORD idThread, // thread identifier
  UINT Msg,       // message to post
  WPARAM wParam,  // first message parameter
  LPARAM lParam   // second message parameter
);

Parameters

idThread
Thread identifier of the thread to which the message will be posted.

The function fails if the specified thread does not have a message queue. The system creates a thread's message queue when the thread makes its first call to one of the Win32 USER or GDI functions. For more information, see the Remarks section.

Msg
Specifies the type of message to be posted.
wParam
Specifies additional message-specific information.
lParam
Specifies additional message-specific information.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError. GetLastError returns ERROR_INVALID_THREAD_ID if idThread is not a valid thread identifier, or if the thread specified by idThread does not have a message queue.

Remarks

The thread to which the message is posted must have created a message queue, or else the call to PostThreadMessage fails. Use one of the following methods to handle this situation:

  • Call PostThreadMessage. If it fails, call the Sleep function and call PostThreadMessage again. Repeat until PostThreadMessage succeeds.
  • Create an event object, then create the thread. Use the WaitForSingleObject function to wait for the event to be set to the signaled state before calling PostThreadMessage. In the thread to which the message will be posted, call PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE) to force the system to create the message queue. Set the event, to indicate that the thread is ready to receive posted messages.

The thread to which the message is posted retrieves the message by calling the GetMessage or PeekMessage function. The hwnd member of the returned MSG structure is NULL.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, GetCurrentThreadId, GetMessage, GetWindowThreadProcessId, MSG, PeekMessage, PostMessage, Sleep, WaitForSingleObject


RegisterWindowMessage

The RegisterWindowMessage function defines a new window message that is guaranteed to be unique throughout the system. The returned message value can be used when calling the SendMessage or PostMessage function.

UINT RegisterWindowMessage(
  LPCTSTR lpString   // address of message string
);

Parameters

lpString
Pointer to a null-terminated string that specifies the message to be registered.

Return Values

If the message is successfully registered, the return value is a message identifier in the range 0xC000 through 0xFFFF.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The RegisterWindowMessage function is typically used to register messages for communicating between two cooperating applications.

If two different applications register the same message string, the applications return the same message value. The message remains registered until the session ends.

Only use RegisterWindowMessage when more than one application must process the same message. For sending private messages within a window class, an application can use any integer in the range WM_USER through 0x7FFF. (Messages in this range are private to a window class, not to an application. For example, predefined control classes such as BUTTON, EDIT, LISTBOX, and COMBOBOX may use values in this range.)

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, PostMessage, SendMessage


ReplyMessage

The ReplyMessage function is used to reply to a message sent through the SendMessage function without returning control to the function that called SendMessage.

BOOL ReplyMessage(
  LRESULT lResult   // message-specific reply
);

Parameters

lResult
Specifies the result of the message processing. The possible values are based on the message sent.

Return Values

If the calling thread was processing a message sent from another thread or process, the return value is nonzero.

If the calling thread was not processing a message sent from another thread or process, the return value is zero.

Remarks

By calling this function, the window procedure that receives the message allows the thread that called SendMessage to continue to run as though the thread receiving the message had returned control. The thread that calls the ReplyMessage function also continues to run.

If the message was not sent through SendMessage or if the message was sent by the same thread, ReplyMessage has no effect.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, InSendMessage, SendMessage


SendAsyncProc

The SendAsyncProc function is an application-defined callback function used with the SendMessageCallback function. The system passes the message to the callback function after passing the message to the destination window procedure. The SENDASYNCPROC type defines a pointer to this callback function. SendAsyncProc is a placeholder for the application-defined function name.

VOID CALLBACK SendAsyncProc(
  HWND hwnd,        // handle of destination window
  UINT uMsg,        // message
  DWORD dwData,     // application-defined value
  LRESULT lResult   // result of message processing
);

Parameters

hwnd
Handle to the window whose window procedure received the message.

If the SendMessageCallback function was called with its hwnd parameter set to HWND_BROADCAST, the system calls the SendAsyncProc function once for each top-level window.

uMsg
Specifies the message.
dwData
Specifies an application-defined value sent from the SendMessageCallback function.
lResult
Specifies the result of the message processing and depends on the message.

Return Values

This callback function does not return a value.

Remarks

You install a SendAsyncProc application-defined callback function by passing a SENDASYNCPROC pointer to the SendMessageCallback function.

The callback function is only called when the thread that called SendMessageCallback calls GetMessage, PeekMessage, or WaitMessage.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: User-defined.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, GetMessage, PeekMessage, SendMessageCallback, WaitMessage


SendMessage

The SendMessage function sends the specified message to a window or windows. The function calls the window procedure for the specified window and does not return until the window procedure has processed the message. The PostMessage function, in contrast, posts a message to a thread's message queue and returns immediately.

LRESULT SendMessage(
  HWND hWnd,      // handle of destination window
  UINT Msg,       // message to send
  WPARAM wParam,  // first message parameter
  LPARAM lParam   // second message parameter
);

Parameters

hWnd
Handle to the window whose window procedure will receive the message. If this parameter is HWND_BROADCAST, the message is sent to all top-level windows in the system, including disabled or invisible unowned windows, overlapped windows, and pop-up windows; but the message is not sent to child windows.
Msg
Specifies the message to be sent.
wParam
Specifies additional message-specific information.
lParam
Specifies additional message-specific information.

Return Values

The return value specifies the result of the message processing and depends on the message sent.

Remarks

Applications that need to communicate using HWND_BROADCAST should use the RegisterWindowMessage function to obtain a unique message for inter-application communication.

If the specified window was created by the calling thread, the window procedure is called immediately as a subroutine. If the specified window was created by a different thread, the system switches to that thread and calls the appropriate window procedure. Messages sent between threads are processed only when the receiving thread executes message retrieval code. The sending thread is blocked until the receiving thread processes the message.

Windows CE: Windows CE does not support all the messages the desktop Windows platforms support. Before using SendMessage, check to make sure the message you are sending is supported.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, InSendMessage, PostMessage, RegisterWindowMessage, SendDlgItemMessage


SendMessageCallback

The SendMessageCallback function sends the specified message to a window or windows. The function calls the window procedure for the specified window and returns immediately. After the window procedure processes the message, the system calls the specified callback function, passing the result of the message processing and an application-defined value to the callback function.

BOOL SendMessageCallback(
  HWND hWnd,     // handle of destination window
  UINT Msg,      // message to send
  WPARAM wParam, // first message parameter
  LPARAM lParam, // second message parameter
  SENDASYNCPROC lpResultCallBack,
                 // function to receive message value
  DWORD dwData   // value to pass to callback function
);

Parameters

hWnd
Handle to the window whose window procedure will receive the message. If this parameter is HWND_BROADCAST, the message is sent to all top-level windows in the system, including disabled or invisible unowned windows, overlapped windows, and pop-up windows; but the message is not sent to child windows.
Msg
Specifies the message to be sent.
wParam
Specifies additional message-specific information.
lParam
Specifies additional message-specific information.
lpResultCallBack
Pointer to a callback function that the system calls after the window procedure processes the message. See SendAsyncProc for information on suitable callback functions.

If hWnd is HWND_BROADCAST, the system calls the SendAsyncProc callback function once for each top-level window.

dwData
Specifies an application-defined value to be sent to the callback function pointed to by the lpfnResultCallBack parameter.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

If you send a message in the range below WM_USER to the asynchronous message functions (PostMessage, SendNotifyMessage, and SendMessageCallback), its message parameters can not include pointers. Otherwise, the operation will fail. The functions will return before the receiving thread has had a chance to process the message and the sender will free the memory before it is used.

Applications that need to communicate using HWND_BROADCAST should use the RegisterWindowMessage function to obtain a unique message for inter-application communication.

The callback function is called only when the thread that called SendMessageCallback also calls GetMessage, PeekMessage, or WaitMessage.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, PostMessage, RegisterWindowMessage, SendAsyncProc, SendMessageCallback, SendNotifyMessage


SendMessageTimeout

The SendMessageTimeout function sends the specified message to a window or windows. The function calls the window procedure for the specified window and, if the specified window belongs to a different thread, does not return until the window procedure has processed the message or the specified time-out period has elapsed. If the window receiving the message belongs to the same queue as the current thread, the window procedure is called directly — the time-out value is ignored.

LRESULT SendMessageTimeout(
  HWND hWnd,           // handle of destination window
  UINT Msg,            // message to send
  WPARAM wParam,       // first message parameter
  LPARAM lParam,       // second message parameter
  UINT fuFlags,        // how to send the message
  UINT uTimeout,       // time-out duration
  LPDWORD lpdwResult   // return value for synchronous call
);

Parameters

hWnd
Handle to the window whose window procedure will receive the message. If this parameter is HWND_BROADCAST, the message is sent to all top-level windows in the system, including disabled or invisible unowned windows.
Msg
Specifies the message to be sent.
wParam
Specifies additional message-specific information.
lParam
Specifies additional message-specific information.
fuFlags
Specifies how to send the message. This parameter can be a combination of the following values:
Value | Meaning
SMTO_ABORTIFHUNG | Returns without waiting for the time-out period to elapse if the receiving process appears to be in a "hung" state.
SMTO_BLOCK | Prevents the calling thread from processing any other requests until the function returns.
SMTO_NORMAL | The calling thread is not prevented from processing other requests while waiting for the function to return.
SMTO_NOTIMEOUTIFNOTHUNG | Windows NT 5.0 and later: Does not return when the time-out period elapses if the receiving thread is not hung.

uTimeout
Specifies the duration, in milliseconds, of the time-out period. If the message is a broadcast message, each window can us the full time-out period. For example, if you specify a 5 second time-out period and there are three top-level windows that fail to process the message, you could have up to a 15 second delay.
lpdwResult
Specifies the result of the message processing and depends on the message sent.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails or time out, the return value is zero. To get extended error information, call GetLastError. If GetLastError returns zero, then the function timed out. SendMessageTimeout does not provide information about individual windows timing out if HWND_BROADCAST is used.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, InSendMessage, PostMessage, SendDlgItemMessage, SendMessage, SendMessageCallback, SendNotifyMessage


SendNotifyMessage

The SendNotifyMessage function sends the specified message to a window. If the window was created by the calling thread, SendNotifyMessage calls the window procedure for the window and does not return until the window procedure has processed the message. If the window was created by a different thread, SendNotifyMessage passes the message to the window procedure and returns immediately; it does not wait for the window procedure to finish processing the message.

BOOL SendNotifyMessage(
  HWND hWnd,      // handle of destination window
  UINT Msg,       // message to send
  WPARAM wParam,  // first message parameter
  LPARAM lParam   // second message parameter
);

Parameters

hWnd
Handle to the window whose window procedure will receive the message. If this parameter is HWND_BROADCAST, the message is sent to all top-level windows in the system, including disabled or invisible unowned windows, overlapped windows, and pop-up windows; but the message is not sent to child windows.
Msg
Specifies the message to be sent.
wParam
Specifies additional message-specific information.
lParam
Specifies additional message-specific information.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

If you send a message in the range below WM_USER to the asynchronous message functions (PostMessage, SendNotifyMessage, and SendMessageCallback), its message parameters can not include pointers. Otherwise, the operation will fail. The functions will return before the receiving thread has had a chance to process the message and the sender will free the memory before it is used.

Applications that need to communicate using HWND_BROADCAST should use the RegisterWindowMessage function to obtain a unique message for inter-application communication.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, PostMessage, PostThreadMessage, RegisterWindowMessage, SendMessage SendMessageCallback, SendNotifyMessage


SetMessageExtraInfo

The SetMessageExtraInfo function sets the extra message information for the current thread. Extra message information is an application- or driver-defined 32-bit value associated with the current thread's message queue. An application can use the GetMessageExtraInfo function to retrieve a thread's extra message information.

LPARAM SetMessageExtraInfo(
  LPARAM lParam  // application-defined 32-bit value
);

Parameters

lParam
Specifies the 32-bit value to associate with the current thread.

Return Values

The return value is the previous 32-bit value.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, GetMessageExtraInfo


SetMessageQueue

The SetMessageQueue function is obsolete. This function is provided only for compatibility for 16-bit versions of Windows. This function does nothing on 32-bit versions of Windows, because message queues are expanded dynamically as necessary.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions


TranslateMessage

The TranslateMessage function translates virtual-key messages into character messages. The character messages are posted to the calling thread's message queue, to be read the next time the thread calls the GetMessage or PeekMessage function.

BOOL TranslateMessage(
  CONST MSG *lpMsg   // address of structure with message
);

Parameters

lpMsg
Pointer to an MSG structure that contains message information retrieved from the calling thread's message queue by using the GetMessage or PeekMessage function.

Return Values

If the message is translated (that is, a character message is posted to the thread's message queue), the return value is nonzero.

If the message is WM_KEYDOWN, WM_KEYUP, WM_SYSKEYDOWN, or WM_SYSKEYUP, the return value is nonzero, regardless of the translation.

If the message is not translated (that is, a character message is not posted to the thread's message queue), the return value is zero.

Remarks

The TranslateMessage function does not modify the message pointed to by the lpMsg parameter.

WM_KEYDOWN and WM_KEYUP combinations produce a WM_CHAR or WM_DEADCHAR message. WM_SYSKEYDOWN and WM_SYSKEYUP combinations produce a WM_SYSCHAR or WM_SYSDEADCHAR message.

TranslateMessage produces WM_CHAR messages only for keys that are mapped to ASCII characters by the keyboard driver.

If applications process virtual-key messages for some other purpose, they should not call TranslateMessage. For instance, an application should not call TranslateMessage if the TranslateAccelerator function returns a nonzero value.

Windows CE: Windows CE does not support scan codes or extended key flags, so it does not support the values 16 - 24 in the lKeyData parameter (lParam) of the WM_CHAR message generated by the TranslateMessage function.

TranslateMessage can only be used to translate messages received from calls to GetMessage or PeekMessage.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, GetMessage, PeekMessage, TranslateAccelerator, WM_CHAR, WM_DEADCHAR, WM_KEYDOWN, WM_KEYUP, WM_SYSCHAR, WM_SYSDEADCHAR, WM_SYSKEYDOWN, WM_SYSKEYUP


WaitMessage

The WaitMessage function yields control to other threads when a thread has no other messages in its message queue. The WaitMessage function suspends the thread and does not return until a new message is placed in the thread's message queue.

BOOL WaitMessage(VOID)

Parameters

This function has no parameters.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Note that WaitMessage does not return if there is unread input in the message queue after the thread has called a function to check the queue. This is because functions such as PeekMessage, GetMessage, GetQueueStatus, WaitMessage, MsgWaitForMultipleObjects, and MsgWaitForMultipleObjectsEx check the queue and then change the state information for the queue so that the input is no longer considered new. A subsequent call to WaitMessage will not return until new input of the specified type arrives. The existing unread input (received prior to the last time the thread checked the queue) is ignored.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, GetMessage, PeekMessage


Message and Message Queue Structures

The following structure is used with messages and message queues.

MSG


MSG

The MSG structure contains message information from a thread's message queue.

typedef struct tagMSG {     // msg
    HWND   hwnd;
    UINT   message;
    WPARAM wParam;
    LPARAM lParam;
    DWORD  time;
    POINT  pt;
} MSG;

Members

hwnd
Handle to the window whose window procedure receives the message.
message
Specifies the message number.
wParam
Specifies additional information about the message. The exact meaning depends on the value of the message member.
lParam
Specifies additional information about the message. The exact meaning depends on the value of the message member.
time
Specifies the time at which the message was posted.
pt
Specifies the cursor position, in screen coordinates, when the message was posted.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Messages and Message Queues Overview, Message and Message Queue Structures, GetMessage, PeekMessage


Messages and Message Queues Messages

Message and Message Queue Messages

The following message is used with messages and message queues.

WM_APP
WM_USER


WM_APP

The WM_APP constant is used by applications to help define private messages, usually of the form WM_APP+X, where X is an integer value.

#define WM_APP       0x8000

Remarks

The WM_APP constant is used to distinguish between message values that are reserved for use by the system and values that can be used by an application to send messages within a private window class. There are five ranges of message numbers:

Range | Meaning
0 through WM_USER – 1 | Messages reserved for use by the system.
WM_USER through 0x7FFF | Integer messages for use by private window classes.
WM_APP through 0xBFFF | Messages available for use by applications.
0xC000 through 0xFFFF | String messages for use by applications.
Greater than 0xFFFF | Reserved by the system for future use.

Message numbers in the first range (0 through WM_USER – 1) are defined by the system. Values in this range that are not explicitly defined are reserved for future use by the system.

Message numbers in the second range (WM_USER through 0x7FFF) can be defined and used by an application to send messages within a private window class. These values cannot be used to define messages that are meaningful throughout an application, because some predefined window classes already define values in this range. For example, predefined control classes such as BUTTON, EDIT, LISTBOX, and COMBOBOX may use these values. Messages in this range should not be sent to other applications unless the applications have been designed to exchange messages and to attach the same meaning to the message numbers.

Message numbers in the third range (0x8000 through 0xBFFF) are available for application to use as private messages. Message in this range do not conflict with system messages.

Message numbers in the fourth range (0xC000 through 0xFFFF) are defined at run time when an application calls the RegisterWindowMessage function to retrieve a message number for a string. All applications that register the same string can use the associated message number for exchanging messages. The actual message number, however, is not a constant and cannot be assumed to be the same between different sessions.

Message numbers in the fifth range (greater than 0xFFFF) are reserved for future use by the system.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

Messages and Message Queues Overview, Message and Message Queue Messages, RegisterWindowMessage, WM_USER


WM_USER

The WM_USER constant is used by applications to help define private messages, usually of the form WM_USER+X, where X is an integer value.

#define WM_USER       0x0400

Remarks

There are five ranges of message numbers:

Range | Meaning
0 through WM_USER – 1 | Messages reserved for use by the system.
WM_USER through 0x7FFF | Integer messages for use by private window classes.
WM_APP through 0xBFFF | Messages available for use by applications.
0xC000 through 0xFFFF | String messages for use by applications.
Greater than 0xFFFF | Reserved by the system for future use.

Message numbers in the first range (0 through WM_USER – 1) are defined by the system. Values in this range that are not explicitly defined are reserved for future use by the system.

Message numbers in the second range (WM_USER through 0x7FFF) can be defined and used by an application to send messages within a private window class. These values cannot be used to define messages that are meaningful throughout an application, because some predefined window classes already define values in this range. For example, predefined control classes such as BUTTON, EDIT, LISTBOX, and COMBOBOX may use these values. Messages in this range should not be sent to other applications unless the applications have been designed to exchange messages and to attach the same meaning to the message numbers.

Message numbers in the third range (0x8000 through 0xBFFF) are available for application to use as private messages. Message in this range do not conflict with system messages.

Message numbers in the fourth range (0xC000 through 0xFFFF) are defined at run time when an application calls the RegisterWindowMessage function to retrieve a message number for a string. All applications that register the same string can use the associated message number for exchanging messages. The actual message number, however, is not a constant and cannot be assumed to be the same between different sessions.

Message numbers in the fifth range (greater than 0xFFFF) are reserved for future use by the system.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Messages and Message Queues Overview, Message and Message Queue Messages, RegisterWindowMessage, WM_APP


Multiple Document Interface

The multiple document interface (MDI) is a specification that defines a user interface for applications that enable the user to work with more than one document at the same time.

This overview describes the structure of an MDI application and how to take advantage of the built-in MDI support provided by the system.

Note MDI is an application-oriented model. Many new and intermediate users find it difficult to learn to use MDI applications. Therefore, many applications are switching to a document-oriented model. Therefore, you may want to consider other models for your user interface. However, you can use MDI for applications which do not easily fit into an existing model until a more suitable model is introduced.


About the Multiple Document Interface

Each document in an MDI application is displayed in a separate child window within the client area of the application's main window. Typical MDI applications include word-processing applications that allow the user to work with multiple text documents, and spreadsheet applications that allow the user to work with multiple charts and spreadsheets.


Frame, Client, and Child Windows

An MDI application has three kinds of windows: a frame window, an MDI client window, as well as a number of child windows. The frame window is like the main window of the application: it has a sizing border, a title bar, a window menu (formerly known as the system menu), a minimize button, and a maximize button. The application must register a window class for the frame window and provide a window procedure to support it.

An MDI application does not display output in the client area of the frame window. Instead, it displays the MDI client window. An MDI client window is a special type of child window belonging to the preregistered window class MDICLIENT. The client window is a child of the frame window; it serves as the background for child windows. It also provides support for creating and manipulating child windows. For example, an MDI application can create, activate, or maximize child windows by sending messages to the MDI client window.

When the user opens or creates a document, the client window creates a child window for the document. The client window is the parent window of all MDI child windows in a given application. Each child window has a sizing border, a title bar, a window menu, a Minimize button, and a Maximize button. Because a child window is clipped, it is confined to the client window and cannot appear outside it.

An MDI application can support more than one kind of document. For example, a typical spreadsheet application enables the user to work with both charts and spreadsheets. For each type of document that it supports, an MDI application must register a child window class and provide a window procedure to support the windows belonging to that class. For more information about window classes, see Window Classes. For more information about window procedures, see Window Procedures.

Following is a typical MDI application. It is named Multipad.


Child Window Creation

To create a child window, an MDI application either calls the CreateMDIWindow function or sends the WM_MDICREATE message to the MDI client window. A more efficient way to create an MDI child window is to call the CreateWindowEx function, specifying the WS_EX_MDICHILD extended style. A thread in an MDI application can use CreateMDIWindow or CreateWindowEx to create a child window in a different thread. The WM_MDICREATE message is used only in the context of the same thread.

To destroy a child window, an MDI application sends a WM_MDIDESTROY message to the MDI client window.


Child Window Activation

Any number of child windows can appear in the client window at any one time, but only one can be active. The active child window is positioned in front of all other child windows, and its border is highlighted.

The user can activate an inactive child window by clicking it. An MDI application activates a child window by sending a WM_MDIACTIVATE message to the MDI client window. As the client window processes this message, it sends a WM_MDIACTIVATE message to the window procedure of the child window to be activated and to the window procedure of the child window being deactivated.

To prevent a child window from activating, handle the WM_NCACTIVATE message to the child window by returning FALSE.

The system keeps track of each child window's position in the stack of overlapping windows. This stacking is known as the Z order. The user can activate the next child window in the Z order by choosing the Next command from the window menu in the active window. An application activates the next (or previous) child window in the Z order by sending a WM_MDINEXT message to the client window.

To retrieve the handle to the active child window, the MDI application sends a WM_MDIGETACTIVE message to the client window.


Multiple Document Menus

The frame window of an MDI application should include a menu bar with a Window menu. The Window menu should include items that arrange the child windows within the client window or that close all child windows. The Window menu of a typical MDI application might include the items in the following table.

Menu item | Purpose
Tile | Arranges child windows in a tile format so that each appears in its entirety in the client window.
Cascade | Arranges child windows in a cascade format. The child windows overlap one another, but the title bar of each is visible.
Arrange Icons | Arranges the icons of minimized child windows along the bottom of the client window.
Close All | Closes all child windows.

Whenever a child window is created, the system automatically appends a new menu item to the Window menu. The text of the menu item is the same as the text on the menu bar of the new child window. By clicking the menu item, the user can activate the corresponding child window. When a child window is destroyed, the system automatically removes the corresponding menu item from the Window menu.

The system can add up to ten menu items to the Window menu. When the tenth child window is created, the system adds the More Windows item to the Window menu. Clicking this item displays the Select Window dialog box. The dialog box contains a list box with the titles of all MDI child windows currently available. The user can activate a child window by clicking its title in the list box.

If your MDI application supports several types of child windows, tailor the menu bar to reflect the operations associated with the active window. To do this, provide separate menu resources for each type of child window the application supports. When a new type of child window is activated, the application should send a WM_MDISETMENU message to the client window, passing to it the handle to the corresponding menu.

When no child window exists, the menu bar should contain only items used to create or open a document.

When the user is navigating through an MDI application's menus by using cursor keys, the keys behave differently than when the user is navigating through a typical application's menus. In an MDI application, control passes from the application's window menu to the window menu of the active child window, and then to the first item on the menu bar.


Accelerators

To receive and process accelerator keys for its child windows, an MDI application must include the TranslateMDISysAccel function in its message loop. The loop must call TranslateMDISysAccel before calling the TranslateAccelerator or DispatchMessage function.

Accelerator keys on the window menu for an MDI child window are different from those for a non-MDI child window. In an MDI child window, the alt+ – (minus) key combination opens the window menu, the ctrl+f4 key combination closes the active child window, and the ctrl+f6 key combination activates the next child window.


Child Window Size and Arrangement

An MDI application controls the size and position of its child windows by sending messages to the MDI client window. To maximize the active child window, the application sends the WM_MDIMAXIMIZE message to the client window. When a child window is maximized, its client area completely fills the MDI client window. In addition, the system automatically hides the child window's title bar, and adds the child window's window menu icon and Restore button to the MDI application's menu bar. The application can restore the client window to its original (premaximized) size and position by sending the client window a WM_MDIRESTORE message.

An MDI application can arrange its child windows in either a cascade or tile format. When the child windows are cascaded, the windows appear in a stack. The window on the bottom of the stack occupies the upper left corner of the screen, and the remaining windows are offset vertically and horizontally so that the left border and title bar of each child window is visible. To arrange child windows in the cascade format, an MDI application sends the WM_MDICASCADE message. Typically, the application sends this message when the user clicks Cascade on the Window menu.

When the child windows are tiled, the system displays each child window in its entirety — overlapping none of the windows. All of the windows are sized, as necessary, to fit within the client window. To arrange child windows in the tile format, an MDI application sends a WM_MDITILE message to the client window. Typically, the application sends this message when the user clicks Tile on the Window menu.

An MDI application should provide a different icon for each type of child window it supports. The application specifies an icon when registering the child window class. The system automatically displays a child window's icon in the lower portion of the client window when the child window is minimized. An MDI application directs the system to arrange child window icons by sending a WM_MDIICONARRANGE message to the client window. Typically, the application sends this message when the user clicks Arrange Icons on the Window menu.


Icon Title Windows

Because MDI child windows may be minimized, an MDI application must avoid manipulating icon title windows as if they were normal MDI child windows. Icon title windows appear when the application enumerates child windows of the MDI client window. Icon title windows differ from other child windows, however, in that they are owned by an MDI child window.

To determine whether a child window is an icon title window, use the GetWindow function with the GW_OWNER index. Non-title windows return NULL. Note that this test is insufficient for top-level windows, because menus and dialog boxes are owned windows.


Child Window Data

Because the number of child windows varies depending on how many documents the user opens, an MDI application must be able to associate data (for example, the name of the current file) with each child window. There are two ways to do this:

  • Store child window data in the window structure.
  • Use window properties.


Data in the Window Structure

When an MDI application registers a window class, it may reserve extra space in the window structure for application data specific to this particular class of windows. To store and retrieve data in this extra space, the application uses the GetWindowWord, SetWindowWord, GetWindowLong, and SetWindowLong functions.

To maintain a large amount of data for a child window, an application can allocate memory for a data structure and then store the handle to the memory containing the structure in the extra space associated with the child window.


Multiple Document Window Properties

An MDI application can also store per-document data by using window properties. Per-document data is data specific to the type of document contained in a particular child window. Properties are different from extra space in the window structure in that you need not allocate extra space when registering the window class. A window can have any number of properties. Also, where offsets are used to access the extra space in window structures, properties are referred to by string names. For more information about window properties, see Window Properties.


Using the Multiple Document Interface

This section explains how to perform the following tasks:

  • Registering child and frame window classes
  • Creating frame and child windows
  • Writing the main message loop
  • Writing the frame window procedure
  • Writing the child window procedure
  • Creating a child window

To illustrate these tasks, this section includes examples from Multipad, a typical MDI application.


Registering Child and Frame Window Classes

A typical MDI application must register two window classes: one for its frame window and one for its child windows. If an application supports more than one type of document (for example, a spreadsheet and a chart), it must register a window class for each type.

The class structure for the frame window is similar to the class structure for the main window in non-MDI applications. The class structure for the MDI child windows differs slightly from the structure for child windows in non-MDI applications as follows:

  • The class structure should have an icon, because the user can minimize an MDI child window as if it were a normal application window.
  • The menu name should be NULL, because an MDI child window cannot have its own menu.
  • The class structure should reserve extra space in the window structure. With this space, the application can associate data, such as a filename, with a particular child window.

The following example shows how Multipad registers its frame and child window classes.

BOOL WINAPI InitializeApplication()
{
    WNDCLASS wc;

    // Register the frame window class.

    wc.style         = 0;
    wc.lpfnWndProc   = (WNDPROC) MPFrameWndProc;
    wc.cbClsExtra    = 0;
    wc.cbWndExtra    = 0;
    wc.hInstance     = hInst;
    wc.hIcon         = LoadIcon(hInst, IDMULTIPAD);
    wc.hCursor       = LoadCursor((HANDLE) NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH) (COLOR_APPWORKSPACE + 1);
    wc.lpszMenuName  = IDMULTIPAD;
    wc.lpszClassName = szFrame;

    if (!RegisterClass (&wc) )
        return FALSE;

    // Register the MDI child window class.

    wc.lpfnWndProc   = (WNDPROC) MPMDIChildWndProc;
    wc.hIcon         = LoadIcon(hInst, IDNOTE);
    wc.lpszMenuName  = (LPCTSTR) NULL;
    wc.cbWndExtra    = CBWNDEXTRA;
    wc.lpszClassName = szChild;

    if (!RegisterClass(&wc))
        return FALSE;

    return TRUE;
}


Creating Frame and Child Windows

After registering its window classes, an MDI application can create its windows. First, it creates its frame window by using the CreateWindow or CreateWindowEx function. After creating its frame window, the application creates its client window, again by using CreateWindow or CreateWindowEx. The application should specify MDICLIENT as the client window's class name; MDICLIENT is a preregistered window class defined by the system. The lpvParam parameter of CreateWindow or CreateWindowEx should point to a CLIENTCREATESTRUCT structure. This structure contains the members described in the following table:

Member | Description
hWindowMenu | Handle to the Window menu used for controlling MDI child windows. As child windows are created, the application adds their titles to the Window menu as menu items. The user can then activate a child window by clicking its title on the Window menu.
idFirstChild | Specifies the identifier of the first MDI child window. The first MDI child window created is assigned this identifier. Additional windows are created with incremented window identifiers. When a child window is destroyed, the system immediately reassigns the window identifiers to keep their range contiguous.

When a child window's title is added to the Window menu, the system assigns an identifier to the child window. When the user clicks a child window's title, the frame window receives a WM_COMMAND message with the identifier in the wParam parameter. You should specify a value for the idFirstChild member that does not conflict with menu-item identifiers in the frame window's menu.

Multipad's frame window procedure creates the MDI client window while processing the WM_CREATE message. The following example shows how the client window is created.

case WM_CREATE:
    {
        CLIENTCREATESTRUCT ccs;

        // Retrieve the handle to the Window menu and assign the
        // first child window identifier.

        ccs.hWindowMenu = GetSubMenu(GetMenu(hwnd), WINDOWMENU);
        ccs.idFirstChild = IDM_WINDOWCHILD;

        // Create the MDI client window.

        hwndMDIClient = CreateWindow( "MDICLIENT", (LPCTSTR) NULL,
            WS_CHILD | WS_CLIPCHILDREN | WS_VSCROLL | WS_HSCROLL,
            0, 0, 0, 0, hwnd, (HMENU) 0xCAC, hInst, (LPSTR) &ccs);

        ShowWindow(hwndMDIClient, SW_SHOW);
    }
    break;

Titles of child windows are added to the bottom of the Window menu. If the application adds strings to the Window menu by using the AppendMenu function, these strings can be overwritten by the titles of the child windows when the Window menu is repainted (whenever a child window is created or destroyed). An MDI application that adds strings to its Window menu should use the InsertMenu function and verify that the titles of child windows have not overwritten these new strings.

Use the WS_CLIPCHILDREN style to create the MDI client window to prevent the window from painting over its child windows.


Writing the Main Message Loop

The main message loop of an MDI application is similar to that of a non-MDI application handling accelerator keys. The difference is that the MDI message loop calls the TranslateMDISysAccel function before checking for application-defined accelerator keys or before dispatching the message.

The following example shows the message loop of a typical MDI application.

while (GetMessage(&msg, (HWND) NULL, 0, 0))
{
    if (!TranslateMDISysAccel(hwndMDIClient, &msg) &&
            !TranslateAccelerator(hwndFrame, hAccel, &msg))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}

The TranslateMDISysAccel function translates WM_KEYDOWN messages into WM_SYSCOMMAND messages and sends them to the active MDI child window. If the message is not an MDI accelerator message, the function returns FALSE, in which case the application uses the TranslateAccelerator function to determine whether any of the application-defined accelerator keys were pressed. If not, the loop dispatches the message to the appropriate window procedure.


Writing the Frame Window Procedure

The window procedure for an MDI frame window is similar to that of a non-MDI application's main window. The difference is that a frame window procedure passes all messages it does not handle to the DefFrameProc function rather than to the DefWindowProc function. In addition, the frame window procedure must also pass some messages that it does handle, including those listed in the following table.

Message | Response
WM_COMMAND | Activates the MDI child window that the user chooses. This message is sent when the user chooses an MDI child window from the Window menu of the MDI frame window. The window identifier accompanying this message identifies the MDI child window to be activated.
WM_MENUCHAR | Opens the window menu of the active MDI child window when the user presses the alt+ – (minus) key combination.
WM_SETFOCUS | Passes the keyboard focus to the MDI client window, which in turn passes it to the active MDI child window.
WM_SIZE | Resizes the MDI client window to fit in the new frame window's client area. If the frame window procedure sizes the MDI client window to a different size, it should not pass the message to the DefWindowProc function.

The frame window procedure in Multipad is called MPFrameWndProc. The handling of other messages by MPFrameWndProc is similar to that of non-MDI applications. WM_COMMAND messages in Multipad are handled by the locally defined CommandHandler function. For command messages Multipad does not handle, CommandHandler calls the DefFrameProc function. If Multipad doesn't use DefFrameProc by default, the user can't activate a child window from the Window menu, because the WM_COMMAND message sent by clicking the window's menu item would be lost.


Writing the Child Window Procedure

Like the frame window procedure, an MDI child window procedure uses a special function for processing messages by default. All messages that the child window procedure does not handle must be passed to the DefMDIChildProc function rather than to the DefWindowProc function. In addition, some window-management messages must be passed to DefMDIChildProc, even if the application handles the message, in order for MDI to function correctly. Following are the messages the application must pass to DefMDIChildProc.

Message | Response
WM_CHILDACTIVATE | Performs activation processing when MDI child windows are sized, moved, or displayed. This message must be passed.
WM_GETMINMAXINFO | Calculates the size of a maximized MDI child window, based on the current size of the MDI client window.
WM_MENUCHAR | Passes the message to the MDI frame window.
WM_MOVE | Recalculates MDI client scroll bars, if they are present.
WM_SETFOCUS | Activates the child window, if it is not the active MDI child window.
WM_SIZE | Performs operations necessary for changing the size of a window, especially for maximizing or restoring an MDI child window. Failing to pass this message to the DefMDIChildProc function produces highly undesirable results.
WM_SYSCOMMAND | Handles window (formerly known as system) menu commands: SC_NEXTWINDOW, SC_PREVWINDOW, SC_MOVE, SC_SIZE, and SC_MAXIMIZE.


Creating a Child Window

To create an MDI child window, an application can either call the CreateMDIWindow function or send an WM_MDICREATE message to the MDI client window. (The application can use the CreateWindowEx function with the WS_EX_MDICHILD style to create MDI child windows.) A single-threaded MDI application can use either method to create a child window. A thread in a multithreaded MDI application must use the CreateMDIWindow or CreateWindowEx function to create a child window in a different thread.

The lParam parameter of a WM_MDICREATE message is a far pointer to an MDICREATESTRUCT structure. The structure includes four dimension members: x and y, which indicate the horizontal and vertical positions of the window, and cx and cy, which indicate the horizontal and vertical extents of the window. Any of these members may be assigned explicitly by the application, or they may be set to CW_USEDEFAULT, in which case the system selects a position, size, or both, according to a cascading algorithm. In any case, all four members must be initialized. Multipad uses CW_USEDEFAULT for all dimensions.

The last member of the MDICREATESTRUCT structure is the style member, which may contain style bits for the window. To create an MDI child window that can have any combination of window styles, specify the MDIS_ALLCHILDSTYLES window style. When this style is not specified, an MDI child window has the WS_MINIMIZE, WS_MAXIMIZE, WS_HSCROLL, and WS_VSCROLL styles as default settings.

Multipad creates its MDI child windows by using its locally defined AddFile function (located in the source file MPFILE.C). The AddFile function sets the title of the child window by assigning the szTitle member of the window's MDICREATESTRUCT structure to either the name of the file being edited or to "Untitled." The szClass member is set to the name of the MDI child window class registered in Multipad's InitializeApplication function. The hOwner member is set to the application's instance handle.

The following example shows the AddFile function in Multipad.

HWND APIENTRY AddFile(pName)
CHAR * pName;
{
    HWND hwnd;
    CHAR sz[160];
    MDICREATESTRUCT mcs;

    if (!pName)
    {

        // If the pName parameter is NULL, load the "Untitled"
        // string from the STRINGTABLE resource and set the szTitle
        // member of MDICREATESTRUCT.

        LoadString(hInst, IDS_UNTITLED, sz, sizeof(sz));
        mcs.szTitle = (LPCTSTR) sz;
    }
    else

        // Title the window with the full path and filename,
        // obtained by calling the OpenFile function with the
        // OF_PARSE flag, which is called before AddFile().

        mcs.szTitle = of.szPathName;

    mcs.szClass = szChild;
    mcs.hOwner  = hInst;

    // Use the default size for the child window.

    mcs.x = mcs.cx = CW_USEDEFAULT;
    mcs.y = mcs.cy = CW_USEDEFAULT;

    // Give the child window the default style. The styleDefault
    // variable is defined in MULTIPAD.C.

    mcs.style = styleDefault;

    // Tell the MDI client window to create the child window.

    hwnd = (HWND) SendMessage (hwndMDIClient, WM_MDICREATE, 0,
        (LONG) (LPMDICREATESTRUCT) &mcs);

    // If the file is found, read its contents into the child
    // window's client area.

    if (pName)
    {
        if (!LoadFile(hwnd, pName))
        {

            // Cannot load the file; close the window.

            SendMessage(hwndMDIClient, WM_MDIDESTROY,
                (DWORD) hwnd, 0L);
        }
    }
    return hwnd;
}

The pointer passed in the lParam parameter of the WM_MDICREATE message is passed to the CreateWindow function and appears as the first member in the CREATESTRUCT structure, passed in the WM_CREATE message. In Multipad, the child window initializes itself during WM_CREATE message processing by initializing document variables in its extra data and by creating the edit control's child window.


Multiple Document Interface Reference

The following elements are used in MDI applications.

  • Multiple Document Interface Functions
  • Multiple Document Interface Structures
  • Multiple Document Interface Messages


MDI Functions

Multiple Document Interface Functions

The following functions are used with MDI.

CreateMDIWindow
DefFrameProc
DefMDIChildProc
TranslateMDISysAccel


CreateMDIWindow

The CreateMDIWindow function creates a multiple document interface (MDI) child window.

HWND CreateMDIWindow(
  LPTSTR lpClassName,  // pointer to registered child class name
  LPTSTR lpWindowName, // pointer to window name
  DWORD dwStyle,       // window style
  int X,               // horizontal position of window
  int Y,               // vertical position of window
  int nWidth,          // width of window
  int nHeight,         // height of window
  HWND hWndParent,     // handle to parent window (MDI client)
  HINSTANCE hInstance, // handle to application instance
  LPARAM lParam        // application-defined value
);

Parameters

lpClassName
Pointer to a null-terminated string specifying the window class of the MDI child window. The class name must have been registered by a call to the RegisterClassEx function.
lpWindowName
Pointer to a null-terminated string that represents the window name. The system displays the name in the title bar of the child window.
dwStyle
Specifies the style of the MDI child window. If the MDI client window is created with the MDIS_ALLCHILDSTYLES window style, this parameter can be any combination of the window styles listed in the description of the CreateWindow function. Otherwise, this parameter can be one or more of the following values:
Value | Meaning
WS_MINIMIZE | Creates an MDI child window that is initially minimized.
WS_MAXIMIZE | Creates an MDI child window that is initially maximized.
WS_HSCROLL | Creates an MDI child window that has a horizontal scroll bar.
WS_VSCROLL | Creates an MDI child window that has a vertical scroll bar.

X
Specifies the initial horizontal position, in client coordinates, of the MDI child window. If this parameter is CW_USEDEFAULT, the MDI child window is assigned the default horizontal position.
Y
Specifies the initial vertical position, in client coordinates, of the MDI child window. If this parameter is CW_USEDEFAULT, the MDI child window is assigned the default vertical position.
nWidth
Specifies the initial width, in device units, of the MDI child window. If this parameter is CW_USEDEFAULT, the MDI child window is assigned the default width.
nHeight
Specifies the initial height, in device units, of the MDI child window. If this parameter is set to CW_USEDEFAULT, the MDI child window is assigned the default height.
hWndParent
Handle to the MDI client window that will be the parent of the new MDI child window.
hInstance
Handle to the instance of the application creating the MDI child window.
lParam
Specifies an application-defined value.

Return Values

If the function succeeds, the return value is the handle to the created window.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

Using the CreateMDIWindow function is similar to sending the WM_MDICREATE message to an MDI client window, except that the function can create an MDI child window in a different thread, while the message cannot.

Windows 95: The system can support a maximum of 16,364 window handles.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Multiple Document Interface Overview, Multiple Document Interface Functions, CreateWindow, RegisterClassEx, WM_MDICREATE


DefFrameProc

The DefFrameProc function provides default processing for any window messages that the window procedure of a multiple document interface (MDI) frame window does not process. All window messages that are not explicitly processed by the window procedure must be passed to the DefFrameProc function, not the DefWindowProc function.

LRESULT DefFrameProc(
  HWND hWnd,           // handle to MDI frame window
  HWND hWndMDIClient,  // handle to MDI client window
  UINT uMsg,           // message
  WPARAM wParam,       // first message parameter
  LPARAM lParam        // second message parameter
);

Parameters

hWnd
Handle to the MDI frame window.
hWndMDIClient
Handle to the MDI client window.
uMsg
Specifies the message to be processed.
wParam
Specifies additional message-specific information.
lParam
Specifies additional message-specific information.

Return Values

The return value specifies the result of the message processing and depends on the message. If the hWndMDIClient parameter is NULL, the return value is the same as for the DefWindowProc function.

Remarks

When an application's window procedure does not handle a message, it typically passes the message to the DefWindowProc function to process the message. MDI applications use the DefFrameProc and DefMDIChildProc functions instead of DefWindowProc to provide default message processing. All messages that an application would usually pass to DefWindowProc (such as nonclient messages and the WM_SETTEXT message) should be passed to DefFrameProc instead. The DefFrameProc function also handles the following messages:

Message | Response
WM_COMMAND | Activates the MDI child window that the user chooses. This message is sent when the user chooses an MDI child window from the Window menu of the MDI frame window. The window identifier accompanying this message identifies the MDI child window to be activated.
WM_MENUCHAR | Opens the window menu of the active MDI child window when the user presses the alt+ – (minus) key combination.
WM_SETFOCUS | Passes the keyboard focus to the MDI client window, which in turn passes it to the active MDI child window.
WM_SIZE | Resizes the MDI client window to fit in the new frame window's client area. If the frame window procedure sizes the MDI client window to a different size, it should not pass the message to the DefWindowProc function.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Multiple Document Interface Overview, Multiple Document Interface Functions, DefMDIChildProc, DefWindowProc, WM_SETTEXT


DefMDIChildProc

The DefMDIChildProc function provides default processing for any window message that the window procedure of a multiple document interface (MDI) child window does not process. A window message not processed by the window procedure must be passed to the DefMDIChildProc function, not to the DefWindowProc function.

LRESULT DefMDIChildProc(
  HWND hWnd,      // handle to MDI child window
  UINT uMsg,      // message
  WPARAM wParam,  // first message parameter
  LPARAM lParam   // second message parameter
);

Parameters

hWnd
Handle to the MDI child window.
uMsg
Specifies the message to be processed.
wParam
Specifies additional message-specific information.
lParam
Specifies additional message-specific information.

Return Values

The return value specifies the result of the message processing and depends on the message.

Remarks

The DefMDIChildProc function assumes that the parent window of the MDI child window identified by the hWnd parameter was created with the MDICLIENT class.

When an application's window procedure does not handle a message, it typically passes the message to the DefWindowProc function to process the message. MDI applications use the DefFrameProc and DefMDIChildProc functions instead of DefWindowProc to provide default message processing. All messages that an application would usually pass to DefWindowProc (such as nonclient messages and the WM_SETTEXT message) should be passed to DefMDIChildProc instead. In addition, DefMDIChildProc also handles the following messages:

Message | Response
WM_CHILDACTIVATE | Performs activation processing when MDI child windows are sized, moved, or displayed. This message must be passed.
WM_GETMINMAXINFO | Calculates the size of a maximized MDI child window, based on the current size of the MDI client window.
WM_MENUCHAR | Passes the message to the MDI frame window.
WM_MOVE | Recalculates MDI client scroll bars if they are present.
WM_SETFOCUS | Activates the child window if it is not the active MDI child window.
WM_SIZE | Performs operations necessary for changing the size of a window, especially for maximizing or restoring an MDI child window. Failing to pass this message to the DefMDIChildProc function produces highly undesirable results.
WM_SYSCOMMAND | Handles window menu commands: SC_NEXTWINDOW, SC_PREVWINDOW, SC_MOVE, SC_SIZE, and SC_MAXIMIZE.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Multiple Document Interface Overview, Multiple Document Interface Functions, DefFrameProc, DefWindowProc, WM_CHILDACTIVATE, WM_GETMINMAXINFO, WM_MENUCHAR, WM_MOVE, WM_SETFOCUS, WM_SETTEXT, WM_SIZE, WM_SYSCOMMAND


TranslateMDISysAccel

The TranslateMDISysAccel function processes accelerator keystrokes for window menu commands of the multiple document interface (MDI) child windows associated with the specified MDI client window. The function translates WM_KEYUP and WM_KEYDOWN messages to WM_SYSCOMMAND messages and sends them to the appropriate MDI child windows.

BOOL TranslateMDISysAccel(
  HWND hWndClient,  // handle to MDI client window
  LPMSG lpMsg       // address of structure with message data
);

Parameters

hWndClient
Handle to the MDI client window.
lpMsg
Pointer to a message retrieved by using the GetMessage or PeekMessage function. The message must be an MSG structure and contain message information from the application's message queue.

Return Values

If the message is translated into a system command, the return value is nonzero.

If the message is not translated into a system command, the return value is zero.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Multiple Document Interface Overview, Multiple Document Interface Functions, GetMessage, PeekMessage, TranslateAccelerator, MSG, WM_KEYDOWN, WM_KEYUP, WM_SYSCOMMAND


Multiple Document Interface Structures

The following structures are used with MDI.

MDICREATESTRUCT


MDICREATESTRUCT

The MDICREATESTRUCT structure contains information about the class, title, owner, location, and size of a multiple document interface (MDI) child window.

typedef struct tagMDICREATESTRUCT { // mdic
    LPCTSTR szClass;
    LPCTSTR szTitle;
    HANDLE  hOwner;
    int     x;
    int     y;
    int     cx;
    int     cy;
    DWORD   style;
    LPARAM  lParam;
} MDICREATESTRUCT;

Members

szClass
Pointer to a null-terminated string specifying the name of the window class of the MDI child window. The class name must have been registered by a previous call to the RegisterClass function.
szTitle
Pointer to a null-terminated string that represents the title of the MDI child window. The system displays the title in the child window's title bar.
hOwner
Handle to the instance of the application creating the MDI client window.
x
Specifies the initial horizontal position, in client coordinates, of the MDI child window. If this member is CW_USEDEFAULT, the MDI child window is assigned the default horizontal position.
y
Specifies the initial vertical position, in client coordinates, of the MDI child window. If this member is CW_USEDEFAULT, the MDI child window is assigned the default vertical position.
cx
Specifies the initial width, in device units, of the MDI child window. If this member is CW_USEDEFAULT, the MDI child window is assigned the default width.
cy
Specifies the initial height, in device units, of the MDI child window. If this member is set to CW_USEDEFAULT, the MDI child window is assigned the default height.
style
Specifies the style of the MDI child window. If the MDI client window was created with the MDIS_ALLCHILDSTYLES window style, this member can be any combination of the window styles listed in the description of the CreateWindow function. Otherwise, this member can be one or more of the following values:
Value | Meaning
WS_MINIMIZE | Creates an MDI child window that is initially minimized.
WS_MAXIMIZE | Creates an MDI child window that is initially maximized.
WS_HSCROLL | Creates an MDI child window that has a horizontal scroll bar.
WS_VSCROLL | Creates an MDI child window that has a vertical scroll bar.

lParam
Specifies an application-defined 32-bit value.

Remarks

When the MDI child window is created, the system sends the WM_CREATE message to the window. The lParam parameter of WM_CREATE contains a pointer to a CREATESTRUCT structure. The lpCreateParams member of this structure contains a pointer to the MDICREATESTRUCT structure passed with the WM_MDICREATE message that created the MDI child window.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Unicode: Defined as Unicode and ANSI structures.

See Also

Multiple Document Interface Overview, Multiple Document Interface Structures, CLIENTCREATESTRUCT, CREATESTRUCT, WM_CREATE


MDI Messages

Multiple Document Interface Messages

The following messages are used with MDI.

WM_MDIACTIVATE
WM_MDICASCADE
WM_MDICREATE
WM_MDIDESTROY
WM_MDIGETACTIVE
WM_MDIICONARRANGE
WM_MDIMAXIMIZE
WM_MDINEXT
WM_MDIREFRESHMENU
WM_MDIRESTORE
WM_MDISETMENU
WM_MDITILE


WM_MDIACTIVATE

An application sends the WM_MDIACTIVATE message to a multiple document interface (MDI) client window to instruct the client window to activate a different MDI child window. As the client window processes this message, it sends WM_MDIACTIVATE to the child window being deactivated and to the child window being activated.

WM_MDIACTIVATE
// Message sent to MDI client
wParam = (WPARAM) (HWND) hwndChildAct; // child to activate
lParam = 0;                            // not used; must be zero

// Message received by MDI child
hwndChildDeact = (HWND) wParam;        // child being deactivated
hwndChildAct = (HWND) lParam;          // child being activated

Parameters

In messages sent to an MDI client window:

hwndChildAct
Value of wParam. Handle to the MDI child window to be activated.
In messages received by an MDI child window:
hwndChildDeact
Value of wParam. Handle to the MDI child window being deactivated.
hwndChildAct
Value of lParam. Handle to the MDI child window being activated.

Return Values

If an application sends this message to an MDI client window, the return value is zero. An MDI child window should return zero if it processes this message.

Remarks

An MDI child window is activated independently of the MDI frame window. When the frame window becomes active, the child window last activated by using the WM_MDIACTIVATE message receives the WM_NCACTIVATE message to draw an active window frame and title bar; the child window does not receive another WM_MDIACTIVATE message.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Multiple Document Interface Overview, Multiple Document Interface Messages, WM_MDIGETACTIVE, WM_MDINEXT, WM_NCACTIVATE


WM_MDICASCADE

An application sends the WM_MDICASCADE message to a multiple document interface (MDI) client window to arrange all its child windows in a cascade format.

WM_MDICASCADE
wParam = (WPARAM) (UINT) fuCascade;  // cascade flag
lParam = 0;                          // not used; must be zero

Parameters

fuCascade
Value of wParam. Specifies a cascade flag. The only flag currently available, MDITILE_SKIPDISABLED, prevents disabled MDI child windows from being cascaded.

Return Values

If the message succeeds, the return value is TRUE.

If the message fails, the return value is FALSE.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Multiple Document Interface Overview, Multiple Document Interface Messages, WM_MDIICONARRANGE, WM_MDITILE


WM_MDICREATE

An application sends the WM_MDICREATE message to a multiple document interface (MDI) client window to create an MDI child window.

WM_MDICREATE
wParam = 0;                                     // not used; must be zero
lParam = (LPARAM) (LPMDICREATESTRUCT) lpmdic;   // creation data

Parameters

lpmdic
Pointer to an MDICREATESTRUCT structure containing information that the system uses to create the MDI child window.

Return Values

If the message succeeds, the return value is the handle to the new child window.

If the message fails, the return value is NULL.

Remarks

The MDI child window is created with the style bits WS_CHILD, WS_CLIPSIBLINGS, WS_CLIPCHILDREN, WS_SYSMENU, WS_CAPTION, WS_THICKFRAME, WS_MINIMIZEBOX, and WS_MAXIMIZEBOX, plus additional style bits specified in the MDICREATESTRUCT structure to which the lpmdic parameter points. The system adds the title of the new child window to the Window menu of the frame window. An application should use this message to create all child windows of the client window.

If an MDI client window receives any message that changes the activation of its child windows while the active child window is maximized, the system restores the active child window and maximizes the newly activated child window.

When an MDI child window is created, the system sends the WM_CREATE message to the window. The lParam parameter of the WM_CREATE message contains a pointer to a CREATESTRUCT structure. The lpCreateParams member of this structure contains a pointer to the MDICREATESTRUCT structure passed with the WM_MDICREATE message that created the MDI child window.

An application should not send a second WM_MDICREATE message while a WM_MDICREATE message is still being processed. For example, it should not send a WM_MDICREATE message while an MDI child window is processing its WM_MDICREATE message.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Multiple Document Interface Overview, Multiple Document Interface Messages, CreateMDIWindow, CREATESTRUCT, MDICREATESTRUCT, WM_CREATE, WM_MDIDESTROY


WM_MDIDESTROY

An application sends the WM_MDIDESTROY message to a multiple document interface (MDI) client window to close an MDI child window.

WM_MDIDESTROY
wParam = (WPARAM) (HWND) hwndChild; // handle to child to close
lParam = 0;                         // not used; must be zero

Parameters

hwndChild
Value of wParam. Handle to the MDI child window to be closed.

Return Values

This message always returns zero.

Remarks

This message removes the title of the MDI child window from the MDI frame window and deactivates the child window. An application should use this message to close all MDI child windows.

If an MDI client window receives a message that changes the activation of its child windows and the active MDI child window is maximized, the system restores the active child window and maximizes the newly activated child window.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Multiple Document Interface Overview, Multiple Document Interface Messages, WM_MDICREATE


WM_MDIGETACTIVE

An application sends the WM_MDIGETACTIVE message to a multiple document interface (MDI) client window to retrieve the handle to the active MDI child window.

WM_MDIGETACTIVE
wParam = 0;                      // not used; must be zero
lParam = (LPBOOL) lpfMaximized;  // optional pointer to maximized state flag

Parameters

lpfMaximized
Value of lparam. This is an optional pointer to a maximized state flag variable. If lpfMaximized is non-NULL, the BOOL it points to is set to indicate the maximized state of the MDI child window. TRUE indicates that the window is maximized, FALSE indicates that it is not. This is equivalent to the indication supplied by the high-order word of the return value of the WM_MDIGETACTIVE message under 16-bit Windows. If lpfMaximized is NULL, the parameter is ignored.

Return Values

The return value is the handle to the active MDI child window.

Remarks

Note carefully a change in how this message indicates maximization. In 16-bit Windows, the message return value includes a flag indicating whether the MDI child window is maximized. In the Win32 API, the return value does not include this flag. Instead, the MDI child window's maximized state is indicated by setting a BOOL variable via the optional parameter in lParam, lpfMaximized.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Multiple Document Interface Overview, Multiple Document Interface Messages


WM_MDIICONARRANGE

An application sends the WM_MDIICONARRANGE message to a multiple document interface (MDI) client window to arrange all minimized MDI child windows. It does not affect child windows that are not minimized.

WM_MDIICONARRANGE
wParam = 0; // not used; must be zero
lParam = 0; // not used; must be zero

Parameters

This message has no parameters.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Multiple Document Interface Overview, Multiple Document Interface Messages, WM_MDICASCADE, WM_MDITILE


WM_MDIMAXIMIZE

An application sends the WM_MDIMAXIMIZE message to a multiple document interface (MDI) client window to maximize an MDI child window. The system resizes the child window to make its client area fill the client window. The system places the child window's window menu icon in the rightmost position of the frame window's menu bar, and places the child window's restore icon in the leftmost position. The system also appends the title bar text of the child window to that of the frame window.

WM_MDIMAXIMIZE
wParam = (WPARAM) (HWND) hwndMax; // handle to child to maximize
lParam = 0;                       // not used; must be zero

Parameters

hwndMax
Value of wParam. Handle to the MDI child window to be maximized.

Return Values

The return value is always zero.

Remarks

If an MDI client window receives any message that changes the activation of its child windows while the currently active MDI child window is maximized, the system restores the active child window and maximizes the newly activated child window.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Multiple Document Interface Overview, Multiple Document Interface Messages, WM_MDIRESTORE


WM_MDINEXT

An application sends the WM_MDINEXT message to a multiple document interface (MDI) client window to activate the next or previous child window.

WM_MDINEXT
wParam = (WPARAM) (HWND) hwndChild; // handle to child
lParam = (LPARAM) fNext;            // next or previous child

Parameters

hwndChild
Value of wParam. Handle to the MDI child window. The system activates the child window that is immediately before or after the given child window, depending on the value of the fNext parameter. If the hwndChild parameter is NULL, the system activates the child window that is immediately before or after the currently active child window.
fNext
Value of lParam. If this parameter is zero, the system activates the next MDI child window and places the child window identified by the hwndChild parameter behind all other child windows. If this parameter is nonzero, the system activates the previous child window, placing it in front of the child window identified by hwndChild.

Return Values

The return value is always zero.

Remarks

If an MDI client window receives any message that changes the activation of its child windows while the active MDI child window is maximized, the system restores the active child window and maximizes the newly activated child window.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Multiple Document Interface Overview, Multiple Document Interface Messages, WM_MDIACTIVATE, WM_MDIGETACTIVE


WM_MDIREFRESHMENU

An application sends the WM_MDIREFRESHMENU message to a multiple document interface (MDI) client window to refresh the Window menu of the MDI frame window.

WM_MDIREFRESHMENU
wParam = 0; // not used; must be zero
lParam = 0; // not used; must be zero

Parameters

This message has no parameters.

Return Values

If the message succeeds, the return value is the handle to the frame window menu.

If the message fails, the return value is NULL.

Remarks

After sending this message, an application must call the DrawMenuBar function to update the menu bar.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Multiple Document Interface Overview, Multiple Document Interface Messages, DrawMenuBar, WM_MDISETMENU


WM_MDIRESTORE

An application sends the WM_MDIRESTORE message to a multiple document interface (MDI) client window to restore an MDI child window from maximized or minimized size.

WM_MDIRESTORE
wParam = (WPARAM) (HWND) hwndRes; // handle to child to restore
lParam = 0;                       // not used; must be zero

Parameters

hwndRes
Value of wParam. Handle to the MDI child window to be restored.

Return Values

The return value is always zero.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Multiple Document Interface Overview, Multiple Document Interface Messages, WM_MDIMAXIMIZE


WM_MDISETMENU

An application sends the WM_MDISETMENU message to a multiple document interface (MDI) client window to replace the entire menu of an MDI frame window, to replace the Window menu of the frame window, or both.

WM_MDISETMENU
wParam = (WPARAM) (HMENU) hmenuFrame;  // handle to frame menu
lParam = (LPARAM) (HMENU) hmenuWindow; // handle to Window menu

Parameters

hmenuFrame
Value of wParam. Handle to the new frame window menu. If this parameter is NULL, the frame window menu is not changed.
hmenuWindow
Value of lParam. Handle to the new Window menu. If this parameter is NULL, the Window menu is not changed.

Return Values

If the message succeeds, the return value is the handle to the old frame window menu.

If the message fails, the return value is zero.

Remarks

After sending this message, an application must call the DrawMenuBar function to update the menu bar.

If this message replaces the Window menu, the MDI child window menu items are removed from the previous Window menu and added to the new Window menu.

If an MDI child window is maximized and this message replaces the MDI frame window menu, the window menu icon and restore icon are removed from the previous frame window menu and added to the new frame window menu.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Multiple Document Interface Overview, Multiple Document Interface Messages, DrawMenuBar, WM_MDIREFRESHMENU


WM_MDITILE

An application sends the WM_MDITILE message to a multiple document interface (MDI) client window to arrange all of its MDI child windows in a tile format.

WM_MDITILE
wParam = (WPARAM) (UINT) fuTile; // tiling flag
lParam = 0;                      // not used; must be zero

Parameters

fuTile
Specifies a tiling flag. This parameter can be one of the following values:
Value | Meaning
MDITILE_HORIZONTAL | Tiles MDI child windows so that they are wide rather than tall.
MDITILE_SKIPDISABLED | Prevents disabled MDI child windows from being tiled.
MDITILE_VERTICAL | Tiles MDI child windows so that they are tall rather than wide.

Return Values

If the message succeeds, the return value is TRUE.

If the message fails, the return value is FALSE.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Multiple Document Interface Overview, Multiple Document Interface Messages, WM_MDICASCADE, WM_MDIICONARRANGE


Window Classes

A window class is a set of attributes that the system uses as a template to create a window. Every window is a member of a window class. All window classes are process specific.

This overview describes the types of window classes, how the system locates them, and the elements that define the default behavior of windows that belong to them.


About Window Classes

Each window class has an associated window procedure shared by all windows of the same class. The window procedure processes messages for all windows of that class and therefore controls their behavior and appearance. For more information, see Window Procedures.

A process must register a window class before it can create a window of that class. Registering a window class associates a window procedure, class styles, and other class attributes with a class name. When a process specifies a class name in the CreateWindow or CreateWindowEx function, the system creates a window with the window procedure, styles, and other attributes associated with that class name.


Types of Window Classes

There are three types of window classes:

  • System classes
  • Application global classes
  • Application local classes

These types differ in scope and in when and how they are registered and destroyed.


System Global Classes

System Classes

The system registers the system classes for all processes to use. Any process can use a system class at any time. Because the system registers these classes, a process cannot destroy them.

Each Win32-based application receives its own copy of the system classes. All 16-bit Windows-based applications in the same VDM share system classes, just as they do on 16-bit Windows.

The following table describes the system classes:

Class | Description
Button | The class for a button.
ComboBox | The class for a combo box.
ComboLBox | The class for the list box contained in a combo box.
DDEMLEvent | Windows NT: The class for DDEML events.
Edit | The class for an edit control.
ListBox | The class for a list box.
MDIClient | The class for an MDI client window.
Message | Windows NT 5.0 and later: The class for a message-only window.
ScrollBar | The class for a scroll bar.
Static | The class for a static control.
#32768 | The class for a menu.
#32769 | The class for the desktop window.
#32770 | The class for a dialog box.
#32771 | The class for the task switch window.
#32772 | Windows NT: The class for icon titles.

Windows 95 and Windows 98: The system registers the system classes when it starts.

Windows NT: The system registers the system classes for a process the first time one of its threads calls a User or a GDI function.


Application Global Classes

An application global class is a window class registered by an executable or dynamic-link library (DLL) that is available to all other modules in the process. For example, your DLL can call the RegisterClassEx function to register a window class that defines a custom control as an application global class so that a process that loads the DLL can create instances of the custom control.

Windows NT: To create a class that can be used in every process, create the window class in a DLL and load the DLL in every process. To load the DLL in every process, add its name to the AppInit_DLLs value in following registry key:

HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Windows

Whenever a process starts, the system loads the specified DLL in the context of the newly started process before calling its entry-point function. The DLL must register the class during its initialization procedure and must specify the CS_GLOBALCLASS style. For more information, see Class Styles.

To remove an application global class and free the storage associated with it, use the UnregisterClass function.


Application Local Classes

An application local class is any window class that an executable or DLL registers for its exclusive use. Although you can register any number of local classes, it is typical to register only one. This window class supports the window procedure of the application's main window.

The system destroys a local class when the module that registered it closes. An application can also use the UnregisterClass function to remove a local class and free the storage associated with it.


How the System Locates a Window Class

The system maintains a list of structures for each of the three types of window classes. When an application calls the CreateWindow or CreateWindowEx function to create a window with a specified class, the system uses the following procedure to locate the class:

  1. Search the list of application local classes for a class with the specified name whose instance handle matches the module's instance handle. (Several modules can use the same name to register local classes in the same process.)
  2. If the name is not in the application local class list, search the list of application global classes.
  3. If the name is not in the application global class list, search the list of system classes.

All windows created by the application use this procedure, including windows created by the system on the application's behalf, such as dialog boxes. It is possible to override system classes without affecting other applications. That is, an application can register an application local class having the same name as a system class. This replaces the system class in the context of the application but does not prevent other applications from using the system class.


Registering a Window Class

A window class defines the attributes of a window, such as its style, icon, cursor, menu, and window procedure. The first step in registering a window class is to fill in a WNDCLASSEX structure with the window class information. For more information, see Elements of a Window Class. Next, pass the structure to the RegisterClassEx function. For more information, see Using Window Classes.

To register an application global class, specify the CS_GLOBALCLASS style in the style member of the WNDCLASSEX structure. When registering an application local class, do not specify the CS_GLOBALCLASS style.

If you register the window class using the ANSI version of RegisterClassEx, RegisterClassExA, the application requests that the system pass text parameters of messages to the windows of the created class using the ANSI character set; if you register the class using the Unicode version of RegisterClassEx, RegisterClassExW, the application requests that the system pass text parameters of messages to the windows of the created class using the Unicode character set. The IsWindowUnicode function enables applications to query the nature of each window. For more information on ANSI and Unicode functions in the Win32 API, see Win32 Function Prototypes.

The executable or DLL that registered the class is the owner of the class. The system determines class ownership from the hInstance member of the WNDCLASSEX structure passed to the RegisterClassEx function when the class is registered. For DLLs, the hInstance member must be the instance handle of the DLL.

Windows 95: The class is destroyed when the owner closes or is unloaded. For this reason, the process must destroy all windows using the class before the owner closes or is unloaded.

Windows NT: The class is not destroyed when the DLL that owns it is unloaded. Therefore, if the system calls the window procedure for a window of that class, it will cause an access violation, because the DLL containing the window procedure is no longer in memory. The process must destroy all windows using the class before the DLL is unloaded and call the UnregisterClass function.


Elements of a Window Class

The elements of a window class define the default behavior of windows belonging to the class. The application that registers a window class assigns elements to the class by setting appropriate members in a WNDCLASSEX structure and passing the structure to the RegisterClassEx function. The GetClassInfoEx and GetClassLong functions retrieve information about a given window class. The SetClassLong function changes elements of a local or global class that the application has already registered.

Although a complete window class consists of many elements, the system requires only that an application supply a class name, the window-procedure address, and an instance handle. Use the other elements to define default attributes for windows of the class, such as the shape of the cursor and the content of the menu for the window. You must initialize any unused members of the WNDCLASSEX structure to zero or NULL. The window class elements are as follows.

Element | Purpose
Class name | Distinguishes the class from other registered classes.
Window-procedure address | Pointer to the function that processes all messages sent to windows in the class and defines the behavior of the window.
Instance handle | Identifies the application or DLL that registered the class.
Class cursor | Defines the mouse cursor that the system displays for a window of the class.
Class icons | Defines the large icon and the small icon (starting with Windows 95 and Windows NT 4.0).
Class background brush | Defines the color and pattern that fill the client area when the window is opened or painted.
Class menu | Specifies the default menu for windows that do not explicitly define a menu.
Class styles | Defines how to update the window after moving or resizing it, how to process double-clicks of the mouse, how to allocate space for the device context, and other aspects of the window.
Extra class memory | Specifies the amount of extra memory, in bytes, that the system should reserve for the class. All windows in the class share the extra memory and can use it for any application-defined purpose. The system initializes this memory to zero.
Extra window memory | Specifies the amount of extra memory, in bytes, that the system should reserve for each window belonging to the class. The extra memory can be used for any application-defined purpose. The system initializes this memory to zero.


Class Name

Every window class needs a class name to distinguish one class from another. Assign a class name by setting the lpszClassName member of the WNDCLASSEX structure to the address of a null-terminated string that specifies the name. Because window classes are process specific, window class names need to be unique only within the same process. Also, because class names occupy space in the system's private atom table, you should keep class name strings as short a possible.

The GetClassName function retrieves the name of the class to which a given window belongs.


Window-Procedure Address

Every class needs a window-procedure address to define the entry point of the window procedure used to process all messages for windows in the class. The system passes messages to the procedure when it requires the window to carry out tasks, such as painting its client area or responding to input from the user. A process assigns a window procedure to a class by copying its address to the lpfnWndProc member of the WNDCLASSEX structure. For more information, see Window Procedures.


Instance Handle

Every window class requires an instance handle to identify the application or DLL that registered the class. The system requires instance handles to keep track of all of modules. The system assigns a handle to each copy of a running executable or DLL.

The system passes an instance handle to the entry-point function of each executable (see WinMain) and DLL (see DllMain). The executable or DLL assigns this instance handle to the class by copying it to the hInstance member of the WNDCLASSEX structure.

Windows 95 and Windows 98: Multiple instances of the same application or DLL use the same code segment, but each has its own data segment. The system uses an instance handle to identify the data segment that corresponds to a particular instance of an application or DLL.


Class Cursor

The class cursor defines the shape of the cursor when it is in the client area of a window in the class. The system automatically sets the cursor to the given shape when the cursor enters the window's client area and ensures it keeps that shape while it remains in the client area. To assign a cursor shape to a window class, load a predefined cursor shape by using the LoadCursor function and then assign the returned cursor handle to the hCursor member of the WNDCLASSEX structure. Alternatively, provide a custom cursor resource and use the LoadCursor function to load it from the application's resources.

The system does not require a class cursor. If an application sets the hCursor member of the WNDCLASSEX structure to NULL, no class cursor is defined. The system assumes the window sets the cursor shape each time the cursor moves into the window. A window can set the cursor shape by calling the SetCursor function whenever the window receives the WM_MOUSEMOVE message. For more information about cursors, see Cursors.


Class Icons

A class icon is a picture that the system uses to represent a window of a particular class. An application can have two class icons — one large and one small. The system displays a window's large class icon in the task-switch window that appears when the user presses alt+tab, and in the large icon views of the task bar and explorer. The small class icon appears in a window's title bar and in the small icon views of the task bar and explorer.

To assign a large and small icon to a window class, specify the handles of the icons in the hIcon and hIconSm members of the WNDCLASSEX structure. The icon dimensions must conform to required dimensions for large and small class icons. For a large class icon, you can determine the required dimensions by specifying the SM_CXICON and SM_CYICON values in a call to the GetSystemMetrics function. For a small class icon, specify the SM_CXSMICON and SM_CYSMICON values. For information, see Icons.

If an application sets the hIcon and hIconSm members of the WNDCLASSEX structure to NULL, the system uses the default application icon as the large and small class icons for the window class. If you specify a large class icon but not a small one, the system creates a small class icon based on the large one. However, if you specify a small class icon but not a large one, the system uses the default application icon as the large class icon and the specified icon as the small class icon.

You can override the large or small class icon for a particular window by using the WM_SETICON message. You can retrieve the current large or small class icon by using the WM_GETICON message.


Class Background Brush

A class background brush prepares the client area of a window for subsequent drawing by the application. The system uses the brush to fill the client area with a solid color or pattern, thereby removing all previous images from that location whether they belong to the window or not. The system notifies a window that its background should be painted by sending the WM_ERASEBKGND message to the window. For more information, see Brushes.

To assign a background brush to a class, create a brush by using the appropriate GDI functions and assign the returned brush handle to the hbrBackground member of the WNDCLASSEX structure.

Instead of creating a brush, an application can set the hbrBackground member to one of the standard system color values. For a list of the standard system color values, see SetSysColors.

To use a standard system color, the application must increase the background-color value by one. For example, COLOR_BACKGROUND + 1 is the system background color. Alternatively, you can use the GetSysColorBrush function to retrieve the handle of a brush that corresponds to a standard system color, and then specify the handle in the hbrBackground member of the WNDCLASSEX structure.

The system does not require that a window class have a class background brush. If this parameter is set to NULL, the window must paint its own background whenever it receives the WM_ERASEBKGND message.


Class Menu

A class menu defines the default menu to be used by the windows in the class if no explicit menu is given when the windows are created. A menu is a list of commands from which a user can choose actions for the application to carry out.

You can assign a menu to a class by setting the lpszMenuName member of the WNDCLASSEX structure to the address of a null-terminated string that specifies the resource name of the menu. The menu is assumed to be a resource in the given application. The system automatically loads the menu when it is needed. If the menu resource is identified by an integer and not by a name, the application can set the lpszMenuName member to that integer by applying the MAKEINTRESOURCE macro before assigning the value.

The system does not require a class menu. If an application sets the lpszMenuName member of the WNDCLASSEX structure to NULL, windows in the class have no menu bars. Even if no class menu is given, an application can still define a menu bar for a window when it creates the window.

If a menu is given for a class and a child window of that class is created, the menu is ignored. For more information, see Menus.


Class Styles

The class styles define additional elements of the window class. Two or more styles can be combined by using the bitwise OR (|) operator. To assign a style to a window class, assign the style to the style member of the WNDCLASSEX structure. The class styles are as follows.

Style | Action
CS_BYTEALIGNCLIENT | Aligns the window's client area on a byte boundary (in the x direction). This style affects the width of the window and its horizontal placement on the display.
CS_BYTEALIGNWINDOW | Aligns the window on a byte boundary (in the x direction). This style affects the width of the window and its horizontal placement on the display.
CS_CLASSDC | Allocates one device context to be shared by all windows in the class. Because window classes are process specific, it is possible for multiple threads of an application to create a window of the same class. It is also possible for the threads to attempt to use the device context simultaneously. When this happens , the system allows only one thread to successfully finish its drawing operation. For more information, Device Contexts.
CS_DBLCLKS | Sends a double-click message to the window procedure when the user double-clicks the mouse while the cursor is within a window belonging to the class. For more information, see Mouse Input.
CS_GLOBALCLASS | Specifies that the window class is an application global class. For more information, see Application Global Classes.
CS_HREDRAW | Specifies that the entire window is to be redrawn if a movement or size adjustment changes the width of the client area.
CS_NOCLOSE | Disables the Close command on the System menu.
CS_OWNDC | Allocates a unique device context for each window in the class. For more information about device contexts, see Device Contexts.
CS_PARENTDC | Sets the clipping rectangle of the child window to that of the parent window so that the child can draw on the parent. A window with the CS_PARENTDC style bit receives a regular device context from the system's cache of device contexts. It does not give the child the parent's device context or device context settings. Specifying CS_PARENTDC enhances an application's performance. For more information, see Device Contexts.
CS_SAVEBITS | Saves, as a bitmap, the portion of the screen image obscured by a window. The system uses the saved bitmap to re-create the screen image when the window is removed. The system displays the bitmap at its original location and does not send WM_PAINT messages to windows obscured by the window if other screen actions have not invalidated the stored image. Use this style for small windows that are displayed briefly and then removed before other screen activity takes place (for example, menus or dialog boxes). This style increases the time required to display the window, because the system must first allocate memory to store the bitmap.
CS_VREDRAW | Specifies that the entire window is to be redrawn if a movement or size adjustment changes the height of the client area.

Classes and Device Contexts

A device context is a special set of values that applications use for drawing in the client area of their windows. The system requires a device context for each window on the display but allows some flexibility in how the system stores and treats that device context.

If no device-context style is explicitly given, the system assumes each window uses a device context retrieved from a pool of contexts maintained by the system. In such cases, each window must retrieve and initialize the device context before painting and free it after painting.

To avoid retrieving a device context each time it needs to paint inside a window, an application can specify the CS_OWNDC style for the window class. This class style directs the system to create a private device context — that is, to allocate a unique device context for each window in the class. The application need only retrieve the context once and then use it for all subsequent painting.

Windows 95 and Windows 98: Although the CS_OWNDC style is convenient, use it carefully, because each device context uses a significant portion of 64K GDI heap.


Extra Class Memory

The system maintains a WNDCLASSEX structure internally for each window class in the system. When an application registers a window class, it can direct the system to allocate and append a number of additional bytes of memory to the end of the WNDCLASSEX structure. This memory is called extra class memory and is shared by all windows belonging to the class. Use the extra class memory to store any information pertaining to the class.

Because extra memory is allocated from the system's local heap, an application should use extra class memory sparingly. The RegisterClassEx function fails if the amount of extra class memory requested is greater than 40 bytes. If an application requires more than 40 bytes, it should allocate its own memory and store a pointer to the memory in the extra class memory.

The SetClassWord and SetClassLong functions copy a value to the extra class memory. To retrieve a value from the extra class memory, use the GetClassWord and GetClassLong functions. The cbClsExtra member of the WNDCLASSEX structure specifies the amount of extra class memory to allocate. An application that doesn't use extra class memory must initialize the cbClsExtra member to zero.


Extra Window Memory

The system maintains an internal data structure for each window. When registering a window class, an application can specify a number of additional bytes of memory, called extra window memory. When creating a window of the class, the system allocates and appends the specified amount of extra window memory to the end of the window's structure. An application can use this memory to store window-specific data.

Because extra memory is allocated from the system's local heap, an application should use extra window memory sparingly. With system version 4.0 or later, the RegisterClassEx function fails if the amount of extra window memory requested is greater than 40 bytes. If an application requires more than 40 bytes, it should allocate its own memory and store a pointer to the memory in the extra window memory.

The SetWindowWord and SetWindowLong functions copy a value to the extra memory. The GetWindowWord and GetWindowLong functions retrieve a value from the extra memory. The cbWndExtra member of the WNDCLASSEX structure specifies the amount of extra window memory to allocate. An application that doesn't use the memory must initialize cbWndExtra to zero.


Using Window Classes

Each process must register its own window classes. To register an application local class, use the RegisterClassEx function. You must define the window procedure, fill the members of the WNDCLASSEX structure, and then pass a pointer to the structure to the RegisterClassEx function.

The following example shows how to register a local window class and use it to create a main window.

#include <windows.h>

// Global variable

HINSTANCE hinst;

// Function prototypes.

int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int);
InitApplication(HINSTANCE);
InitInstance(HINSTANCE, int);
LRESULT CALLBACK MainWndProc(HWND, UINT, WPARAM, LPARAM);

// Application entry point.

int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE hPrevInstance,
    LPSTR lpCmdLine, int nCmdShow)
{
    MSG msg;

    if (!InitApplication(hinstance))
        return FALSE;

    if (!InitInstance(hinstance, nCmdShow))
        return FALSE;

    while (GetMessage(&msg, (HWND) NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return msg.wParam;
        UNREFERENCED_PARAMETER(lpCmdLine);
}

BOOL InitApplication(HINSTANCE hinstance)
{
    WNDCLASSEX wcx;

    // Fill in the window class structure with parameters
    // that describe the main window.

    wcx.cbSize = sizeof(wcx);          // size of structure
    wcx.style = CS_HREDRAW |
        CS_VREDRAW;                    // redraw if size changes
    wcx.lpfnWndProc = MainWndProc;     // points to window procedure
    wcx.cbClsExtra = 0;                // no extra class memory
    wcx.cbWndExtra = 0;                // no extra window memory
    wcx.hInstance = hinstance;         // handle of instance
    wcx.hIcon = LoadIcon(NULL,
        IDI_APPLICATION);              // predefined app. icon
    wcx.hCursor = LoadCursor(NULL,
        IDC_ARROW);                    // predefined arrow
    wcx.hbrBackground = GetStockObject(
        WHITE_BRUSH);                  // white background brush
    wcx.lpszMenuName =  "MainMenu";    // name of menu resource
    wcx.lpszClassName = "MainWClass";  // name of window class
    wcx.hIconSm = LoadImage(hinstance, // small class icon
        MAKEINTRESOURCE(5),
        GetSystemMetrics(SM_CXSMICON),
        GetSystemMetrics(SM_CYSMICON),
        LR_DEFAULTCOLOR);

    // Register the window class.

    return RegisterClassEx(&wcx);
}

BOOL InitInstance(HINSTANCE hinstance, int nCmdShow)
{
    HWND hwnd;

    // Save the application-instance handle.

    hinst = hinstance;

    // Create the main window.

    hwnd = CreateWindow(
        "MainWClass",        // name of window class
        "Sample",            // title-bar string
        WS_OVERLAPPEDWINDOW, // top-level window
        CW_USEDEFAULT,       // default horizontal position
        CW_USEDEFAULT,       // default vertical position
        CW_USEDEFAULT,       // default width
        CW_USEDEFAULT,       // default height
        (HWND) NULL,         // no owner window
        (HMENU) NULL,        // use class menu
        hinstance,           // handle of application instance
        (LPVOID) NULL);      // no window-creation data

    if (!hwnd)
        return FALSE;

    // Show the window and send a WM_PAINT message to the window
    // procedure.

    ShowWindow(hwnd, nCmdShow);
    UpdateWindow(hwnd);
    return TRUE;

}

Registering an application global class is similar to registering an application local class, except that the style member of the WNDCLASSEX structure must specify the CS_GLOBALCLASS style.


Window Class Reference

The following elements are used with window classes.

  • Window Class Functions
  • Window Class Structures


Window Class Functions

The following functions are used with window classes.

GetClassInfoEx
GetClassLong
GetClassName
GetWindowLong
RegisterClassEx
SetClassLong
SetWindowLong
UnregisterClass

Obsolete Functions

GetClassInfo
GetClassWord
GetWindowWord
RegisterClass
SetClassWord
SetWindowWord


GetClassInfo

The GetClassInfo function retrieves information about a window class.

The GetClassInfo function has been superseded by the GetClassInfoEx function. You can still use GetClassInfo, however, if you do not need information about the class small icon.

BOOL GetClassInfo(
  HINSTANCE hInstance,    // handle of application instance
  LPCTSTR lpClassName,    // address of class name string
  LPWNDCLASS lpWndClass   // address of structure for class data
);

Parameters

hInstance
Handle to the instance of the application that created the class. To retrieve information about classes defined by the system (such as buttons or list boxes), set this parameter to NULL.
lpClassName
Pointer to a null-terminated string containing the class name. The name must be that of a preregistered class or a class registered by a previous call to the RegisterClass function. Alternatively, this parameter can be an integer atom. If so, it must be a global atom created by a previous call to the GlobalAddAtom function. The atom, a 16-bit value less than 0xC000, must be in the low-order word of lpClassName; the high-order word must be zero.
lpWndClass
Pointer to a WNDCLASS structure that receives the information about the class.

Return Values

If the function finds a matching class and successfully copies the data, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Windows CE: If lpClassName is an atom, it must be an atom returned from RegisterClass.

See Also

Window Classes Overview, Window Class Functions, GetClassInfoEx, GetClassLong, GetClassName, GlobalAddAtom, RegisterClass, WNDCLASS


GetClassInfoEx

The GetClassInfoEx function retrieves information about a window class, including the handle of the small icon associated with the window class. The GetClassInfo function does not retrieve the handle of the small icon.

BOOL GetClassInfoEx(
  HINSTANCE hinst,    // handle of application instance
  LPCTSTR lpszClass,  // address of class name string
  LPWNDCLASSEX lpwcx  // address of structure for class data
);

Parameters

hinst
Handle to the instance of the application that created the class. To retrieve information about classes defined by the system (such as buttons or list boxes), set this parameter to NULL.
lpszClass
Pointer to a null-terminated string containing the class name. The name must be that of a preregistered class or a class registered by a previous call to the RegisterClassEx function. Alternatively, this parameter can be an integer atom. If this parameter is an integer atom, it must be a global atom created by a previous call to the GlobalAddAtom function. The atom, a 16-bit value less than 0xC000, must be in the low-order word of lpszClass; the high-order word must be zero.
lpwcx
Pointer to a WNDCLASSEX structure that receives the information about the class.

Return Values

If the function finds a matching class and successfully copies the data, the return value is nonzero.

If the function does not find a matching class and successfully copy the data, the return value is zero. To get extended error information, call GetLastError.

QuickInfo

Windows NT: Requires version 3.5 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Window Classes Overview, Window Class Functions, GetClassLong, GetClassName, GlobalAddAtom, RegisterClassEx


GetClassLong

The GetClassLong function retrieves the specified 32-bit (long) value from the WNDCLASSEX structure associated with the specified window.

DWORD GetClassLong(
  HWND hWnd,  // handle of window
  int nIndex  // offset of value to retrieve
);

Parameters

hWnd
Handle to the window and, indirectly, the class to which the window belongs.
nIndex
Specifies the 32-bit value to retrieve. To retrieve a 32-bit value from the extra class memory, specify the positive, zero-based byte offset of the value to be retrieved. Valid values are in the range zero through the number of bytes of extra class memory, minus four; for example, if you specified 12 or more bytes of extra class memory, a value of 8 would be an index to the third 32-bit integer. To retrieve any other value from the WNDCLASSEX structure, specify one of the following values:
Value | Action
GCW_ATOM | Retrieves an ATOM value that uniquely identifies the window class. This is the same atom that the RegisterClassEx function returns.
GCL_CBCLSEXTRA | Retrieves the size, in bytes, of the extra memory associated with the class.
GCL_CBWNDEXTRA | Retrieves the size, in bytes, of the extra window memory associated with each window in the class. For information on how to access this memory, see GetWindowLong.
GCL_HBRBACKGROUND | Retrieves the handle of the background brush associated with the class.
GCL_HCURSOR | Retrieves the handle of the cursor associated with the class.
GCL_HICON | Retrieves the handle of the icon associated with the class.
GCL_HICONSM | Retrieves the handle of the small icon associated with the class.
GCL_HMODULE | Retrieves the handle of the module that registered the class.
GCL_MENUNAME | Retrieves the address of the menu name string. The string identifies the menu resource associated with the class.
GCL_STYLE | Retrieves the window-class style bits.
GCL_WNDPROC | Retrieves the address of the window procedure associated with the class.

Return Values

If the function succeeds, the return value is the requested 32-bit value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Reserve extra class memory by specifying a nonzero value in the cbClsExtra member of the WNDCLASSEX structure used with the RegisterClassEx function.

Windows CE: The nIndex parameter is a byte offset but must be a multiple of 4 bytes. Windows CE does not support unaligned access.

The only values supported for the nIndex parameter are GCL_HICON and GCL_STYLE.

If you are using the Windows CE Iconcurs component, which supports mouse cursors on appropriate target platforms, you can also use the GCL_HCURSOR value in the nIndex parameter.

Note Windows CE versions that support mouse cursors include the Iconcurs and Mcursor components rather than the Icon and Cursor components.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Window Classes Overview, Window Class Functions, GetWindowLong, RegisterClassEx, SetClassLong, WNDCLASSEX


GetClassName

The GetClassName function retrieves the name of the class to which the specified window belongs.

int GetClassName(
  HWND hWnd,           // handle of window
  LPTSTR lpClassName,  // address of buffer for class name
  int nMaxCount        // size of buffer, in characters
);

Parameters

hWnd
Handle to the window and, indirectly, the class to which the window belongs.
lpClassName
Pointer to the buffer that is to receive the class name string.
nMaxCount
Specifies the length, in characters, of the buffer pointed to by the lpClassName parameter. The class name string is truncated if it is longer than the buffer.

Return Values

If the function succeeds, the return value is the number of characters copied to the specified buffer.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Window Classes Overview, Window Class Functions, FindWindow, GetClassInfo, GetClassLong, GetClassWord


GetClassWord

The GetClassWord function retrieves the 16-bit (word) value at the specified offset into the extra class memory for the window class to which the specified window belongs.

Other than GCW_ATOM and GCW_HICONSM, the GCW_ values support by 16-bit Windows are obsolete. You must use the GetClassLong function to retrieve the class values of a window.

WORD GetClassWord(
  HWND hWnd,  // handle of window
  int nIndex  // offset of value to retrieve
);

Parameters

hWnd
Handle to the window and, indirectly, the class to which the window belongs.
nIndex
Specifies the zero-based byte offset of the value to be retrieved. Valid values are in the range zero through the number of bytes of class memory, minus two; for example, if you specified 10 or more bytes of extra class memory, a value of eight would be an index to the fifth 16-bit integer. There is an additional valid value:
Value | Action
GCW_ATOM | Retrieves an ATOM value that uniquely identifies the window class. This is the same atom that the RegisterClass function returns.
GCW_HICONSM | Retrieves the handle of the small icon associated with the window.

Return Values

If the function succeeds, the return value is the requested 16-bit value.

If the function fails, the return value is otherwise, it is zero. To get extended error information, call GetLastError.

Remarks

Reserve extra class memory by specifying a nonzero value in the cbClsExtra member of the WNDCLASS structure used with the RegisterClass function.

See Also

Window Classes Overview, Window Class Functions, GetClassLong, RegisterClass, SetClassWord, WNDCLASS


GetWindowLong

The GetWindowLong function retrieves information about the specified window. The function also retrieves the 32-bit (long) value at the specified offset into the extra window memory of a window.

LONG GetWindowLong(
  HWND hWnd,  // handle of window
  int nIndex  // offset of value to retrieve
);

Parameters

hWnd
Handle to the window and, indirectly, the class to which the window belongs.
nIndex
Specifies the zero-based offset to the value to be retrieved. Valid values are in the range zero through the number of bytes of extra window memory, minus four; for example, if you specified 12 or more bytes of extra memory, a value of 8 would be an index to the third 32-bit integer. To retrieve any other value, specify one of the following values:
Value | Action
GWL_EXSTYLE | Retrieves the extended window styles.
GWL_STYLE | Retrieves the window styles.
GWL_WNDPROC | Retrieves the address of the window procedure, or a handle representing the address of the window procedure. You must use the CallWindowProc function to call the window procedure.
GWL_HINSTANCE | Retrieves the handle of the application instance.
GWL_HWNDPARENT | Retrieves the handle of the parent window, if any.
GWL_ID | Retrieves the identifier of the window.
GWL_USERDATA | Retrieves the 32-bit value associated with the window. Each window has a corresponding 32-bit value intended for use by the application that created the window.

The following values are also available when the hWnd parameter identifies a dialog box:
Value | Action
DWL_DLGPROC | Retrieves the address of the dialog box procedure, or a handle representing the address of the dialog box procedure. You must use the CallWindowProc function to call the dialog box procedure.
DWL_MSGRESULT | Retrieves the return value of a message processed in the dialog box procedure.
DWL_USER | Retrieves extra information private to the application, such as handles or pointers.

Return Values

If the function succeeds, the return value is the requested 32-bit value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Reserve extra window memory by specifying a nonzero value in the cbWndExtra member of the WNDCLASSEX structure used with the RegisterClassEx function.

Windows CE: The nIndex parameter must be a multiple of 4 bytes. Unaligned access is not supported.

Windows CE does not support the GWL_HINSTANCE and GWL_HWNDPARENT values in the nIndex parameter.

Windows CE 1.0 also does not support the DWL_DLGPROC and GWL_USERDATA value in the nIndex parameter.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Window Classes Overview, Window Class Functions, CallWindowProc, RegisterClassEx, SetParent, SetWindowLong, WNDCLASS


GetWindowWord

The GetWindowWord function is obsolete. The GWW_ values are not supported. Win32-based applications should use the GetWindowLong function.

See Also

Window Classes Overview, Window Class Functions


RegisterClass

The RegisterClass function registers a window class for subsequent use in calls to the CreateWindow or CreateWindowEx function.

The RegisterClass function has been superseded by the RegisterClassEx function. You can still use RegisterClass, however, if you do not need to set the class small icon.

ATOM RegisterClass(
  CONST WNDCLASS *lpWndClass   // address of structure with class
                               // data
);

Parameters

lpWndClass
Pointer to a WNDCLASS structure. You must fill the structure with the appropriate class attributes before passing it to the function.

Return Values

If the function succeeds, the return value is an atom that uniquely identifies the class being registered.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

If you register the window class by using RegisterClassA, the application tells the system that the windows of the created class expect messages with text or character parameters to use the ANSI character set; if you register it by using RegisterClassW, the application requests that the system pass text parameters of messages as Unicode. The IsWindowUnicode function enables applications to query the nature of each window. For more information on ANSI and Unicode functions in the Win32 API, see Function Prototypes.

All window classes that an application registers are unregistered when it terminates.

Windows 95: All window classes registered by a DLL are unregistered when the DLL is unloaded.

Windows NT: No window classes registered by a DLL are unregistered when the DLL is unloaded.

Windows 95: RegisterClass fails if the cbWndExtra or cbClsExtra member of the WNDCLASS structure contains more than 40 bytes.

Windows CE: The WNDCLASS structure pointed to by the lpWndClass parameter does not support the lpszMenuName field because Windows CE does not support default menus.

Unless you are using the Windows CE Iconcurs component, which provides mouse cursor support on appropriate target platforms, you cannot use the hCursor field in the WNDCLASS structure pointed to by lpWndClass.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Window Classes Overview, Window Class Functions, CreateWindow, CreateWindowEx, GetClassInfo, GetClassName, RegisterClassEx, UnregisterClass, WindowProc, WNDCLASS


RegisterClassEx

The RegisterClassEx function registers a window class for subsequent use in calls to the CreateWindow or CreateWindowEx function.

ATOM RegisterClassEx(
  CONST WNDCLASSEX *lpwcx  // address of structure with class data
);

Parameters

lpwcx
Pointer to a WNDCLASSEX structure. You must fill the structure with the appropriate class attributes before passing it to the function.

Return Values

If the function succeeds, the return value is an atom that uniquely identifies the class being registered.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

If you register the window class by using RegisterClassExA, the application tells the system that the windows of the created class expect messages with text or character parameters to use the ANSI character set; if you register it by using RegisterClassExW, the application requests that the system pass text parameters of messages as Unicode. The IsWindowUnicode function enables applications to query the nature of each window. For more information on ANSI and Unicode functions in the Win32 API, see Function Prototypes.

All window classes that an application registers are unregistered when it terminates.

Windows 95: All window classes registered by a DLL are unregistered when the DLL is unloaded.

Windows NT: No window classes registered by a DLL are unregistered when the DLL is unloaded.

Windows 95: RegisterClassEx fails if the cbWndExtra or cbClsExtra member of the WNDCLASSEX structure contains more than 40 bytes.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Window Classes Overview, Window Class Functions, CreateWindow, CreateWindowEx, GetClassInfoEx, GetClassName, UnregisterClass, WindowProc,WNDCLASSEX


SetClassLong

The SetClassLong function replaces the specified 32-bit (long) value at the specified offset into the extra class memory or the WNDCLASSEX structure for the class to which the specified window belongs.

DWORD SetClassLong(
  HWND hWnd,       // handle of window
  int nIndex,      // index of value to change
  LONG dwNewLong   // new value
);

Parameters

hWnd
Handle to the window and, indirectly, the class to which the window belongs.
nIndex
Specifies the 32-bit value to replace. To set a 32-bit value in the extra class memory, specify the positive, zero-based byte offset of the value to be set. Valid values are in the range zero through the number of bytes of extra class memory, minus four; for example, if you specified 12 or more bytes of extra class memory, a value of 8 would be an index to the third 32-bit integer. To set any other value from the WNDCLASSEX structure, specify one of the following values:
Value | Action
GCL_CBCLSEXTRA | Sets the size, in bytes, of the extra memory associated with the class. Setting this value does not change the number of extra bytes already allocated.
GCL_CBWNDEXTRA | Sets the size, in bytes, of the extra window memory associated with each window in the class. Setting this value does not change the number of extra bytes already allocated. For information on how to access this memory, see SetWindowLong.
GCL_HBRBACKGROUND | Replaces the handle of the background brush associated with the class.
GCL_HCURSOR | Replaces the handle of the cursor associated with the class.
GCL_HICON | Replaces the handle of the icon associated with the class.
GCL_HMODULE | Replaces the handle of the module that registered the class.
GCL_MENUNAME | Replaces the address of the menu name string. The string identifies the menu resource associated with the class.
GCL_STYLE | Replaces the window-class style bits.
GCL_WNDPROC | Replaces the address of the window procedure associated with the class.

dwNewLong
Specifies the replacement value.

Return Values

If the function succeeds, the return value is the previous value of the specified 32-bit integer. If the value was not previously set, the return value is zero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

If you use the SetClassLong function and the GCL_WNDPROC index to replace the window procedure, the window procedure must conform to the guidelines specified in the description of the WindowProc callback function.

Calling SetClassLong with the GCL_WNDPROC index creates a subclass of the window class that affects all windows subsequently created with the class. An application can subclass a system class, but should not subclass a window class created by another process.

Reserve extra class memory by specifying a nonzero value in the cbClsExtra member of the WNDCLASSEX structure used with the RegisterClassEx function.

Use the SetClassLong function with care. For example, it is possible to change the background color for a class by using SetClassLong, but this change does not immediately repaint all windows belonging to the class.

Windows CE: The nIndex parameter is a byte offset but must be a multiple of 4 bytes. Unaligned access is not supported.

None of the standard GCL_* values are supported in the nIndex parameter, with one exception. If the device you are targetting supports a mouse cursor, you can use the GCL_HCURSOR value in the nIndex parameter.

Note Windows CE versions that support mouse cursors include the Iconcurs and Mcursor components rather than the Icon and Cursor components.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Window Classes Overview, Window Class Functions, GetClassLong, RegisterClassEx, SetWindowLong, WindowProc, WNDCLASSEX


SetClassWord

The SetClassWord function replaces the 16-bit (word) value at the specified offset into the extra class memory for the window class to which the specified window belongs.

The GCW_ values supported by 16-bit Windows are obsolete. You must use the SetClassLong function to set the class values previously set by using the GCW_ values with the SetClassWord function.

WORD SetClassWord(
  HWND hWnd,      // handle of window
  int nIndex,     // index of value to change
  WORD wNewWord   // new value
);

Parameters

hWnd
Handle to the window and, indirectly, the class to which the window belongs.
nIndex
Specifies the zero-based byte offset of the value to be replaced. Valid values are in the range zero through the number of bytes of class memory minus two; for example, if you specified 10 or more bytes of extra class memory, a value of 8 would be an index to the fifth 16-bit integer.
wNewWord
Specifies the replacement value.

Return Values

If the function succeeds, the return value is the previous value of the specified 16-bit integer. If the value was not previously set, the return value is zero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Reserve extra class memory by specifying a nonzero value in the cbClsExtra member of the WNDCLASS structure used with the RegisterClass function.

See Also

Window Classes Overview, Window Class Functions, GetClassWord, RegisterClass, SetClassLong, WNDCLASS


SetWindowLong

The SetWindowLong function changes an attribute of the specified window. The function also sets a 32-bit (long) value at the specified offset into the extra window memory of a window.

LONG SetWindowLong(
  HWND hWnd,       // handle of window
  int nIndex,      // offset of value to set
  LONG dwNewLong   // new value
);

Parameters

hWnd
Handle to the window and, indirectly, the class to which the window belongs.
nIndex
Specifies the zero-based offset to the value to be set. Valid values are in the range zero through the number of bytes of extra window memory, minus 4; for example, if you specified 12 or more bytes of extra memory, a value of 8 would be an index to the third 32-bit integer. To set any other value, specify one of the following values:
Value | Action
GWL_EXSTYLE | Sets a new extended window style.
GWL_STYLE | Sets a new window style.
GWL_WNDPROC | Sets a new address for the window procedure.
GWL_HINSTANCE | Sets a new application instance handle.
GWL_ID | Sets a new identifier of the window.
GWL_USERDATA | Sets the 32-bit value associated with the window. Each window has a corresponding 32-bit value intended for use by the application that created the window.

The following values are also available when the hWnd parameter identifies a dialog box:
Value | Action
DWL_DLGPROC | Sets the new address of the dialog box procedure.
DWL_MSGRESULT | Sets the return value of a message processed in the dialog box procedure.
DWL_USER | Sets new extra information that is private to the application, such as handles or pointers.

dwNewLong
Specifies the replacement value.

Return Values

If the function succeeds, the return value is the previous value of the specified 32-bit integer.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

If the previous value of the specified 32-bit integer is zero, and the function succeeds, the return value is zero, but the function does not clear the last error information. This makes it difficult to determine success or failure. To deal with this, you should clear the last error information by calling SetLastError(0) before calling SetWindowLong. Then, function failure will be indicated by a return value of zero and a GetLastError result that is nonzero.

Remarks

The SetWindowLong function fails if the window specified by the hWnd parameter does not belong to the same process as the calling thread.

Certain window data is cached, so changes you make using SetWindowLong will not take effect until you call the SetWindowPos function.

If you use SetWindowLong with the GWL_WNDPROC index to replace the window procedure, the window procedure must conform to the guidelines specified in the description of the WindowProc callback function.

If you use SetWindowLong with the DWL_MSGRESULT index to set the return value for a message processed by a dialog procedure, you should return TRUE directly afterwards. Otherwise, if you call any function that results in your dialog procedure receiving a window message, the nested window message could overwrite the return value you set using DWL_MSGRESULT.

Calling SetWindowLong with the GWL_WNDPROC index creates a subclass of the window class used to create the window. An application can subclass a system class, but should not subclass a window class created by another process. The SetWindowLong function creates the window subclass by changing the window procedure associated with a particular window class, causing the system to call the new window procedure instead of the previous one. An application must pass any messages not processed by the new window procedure to the previous window procedure by calling CallWindowProc. This allows the application to create a chain of window procedures.

Reserve extra window memory by specifying a nonzero value in the cbWndExtra member of the WNDCLASSEX structure used with the RegisterClassEx function.

You must not call SetWindowLong with the GWL_HWNDPARENT index to change the parent of a child window. Instead, use the SetParent function.

Windows CE: The nIndex parameter must be a multiple of 4 bytes.

Unaligned access is not supported.

The following nIndex parameter values are not supported:

GWL_HINSTANCE

GWL_HWNDPARENT

GWL_USERDATA

Windows CE versions 2.0 and later support the DWL_DLGPROC value in the nIndex parameter, but Windows CE 1.0 does not.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Window Classes Overview, Window Class Functions, CallWindowProc, GetWindowLong, RegisterClassEx, SetParent, WindowProc, WNDCLASSEX


SetWindowWord

The SetWindowWord function is obsolete. The GWW_ values are not supported. Win32-based applications should use the SetWindowLong function.

See Also

Window Classes Overview, Window Class Functions


UnregisterClass

The UnregisterClass function removes a window class, freeing the memory required for the class.

BOOL UnregisterClass(
  LPCTSTR lpClassName,  // address of class name string
  HINSTANCE hInstance   // handle of application instance
);

Parameters

lpClassName
Pointer to a null-terminated string or is an integer atom. If lpClassName is a string, it specifies the window class name. This class name must have been registered by a previous call to the RegisterClassEx function. System classes, such as dialog box controls, cannot be unregistered.

If this parameter is an integer atom, it must be a global atom created by a previous call to the RegisterClassEx function. The atom, a 16-bit value less than 0xC000, must be in the low-order word of lpClassName; the high-order word must be zero.

hInstance
Handle to the instance of the module that created the class.

Return Values

If the function succeeds, the return value is nonzero.

If the class could not be found or if a window still exists that was created with the class, the return value is zero. To get extended error information, call GetLastError.

Remarks

Before calling this function, an application must destroy all windows created with the specified class.

All window classes that an application registers are unregistered when it terminates.

Windows 95: All window classes registered by a DLL are unregistered when the DLL is unloaded.

Windows NT: No window classes registered by a DLL registers are unregistered when the DLL is unloaded.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Window Classes Overview, Window Class Functions, RegisterClassEx


Window Class Structures

The following structure is used with window classes.

WNDCLASSEX

Obsolete Structures

WNDCLASS


WNDCLASS

The WNDCLASS structure contains the window class attributes that are registered by the RegisterClass function.

This structure has been superseded by the WNDCLASSEX structure used with the RegisterClassEx function. You can still use WNDCLASS and RegisterClass if you do not need to set the small icon associated with the window class.

typedef struct _WNDCLASS {
    UINT    style;
    WNDPROC lpfnWndProc;
    int     cbClsExtra;
    int     cbWndExtra;
    HANDLE  hInstance;
    HICON   hIcon;
    HCURSOR hCursor;
    HBRUSH  hbrBackground;
    LPCTSTR lpszMenuName;
    LPCTSTR lpszClassName;
} WNDCLASS;

Members

style
Specifies the class style(s). Styles can be combined by using the bitwise OR (|) operator. This member can be any combination of the following values:
Value | Action
CS_BYTEALIGNCLIENT | Aligns the window's client area on the byte boundary (in the x direction). This style affects the width of the window and its horizontal position on the display.
CS_BYTEALIGNWINDOW | Aligns a window on a byte boundary (in the x direction). This style affects the width of the window and its horizontal position on the display.
CS_CLASSDC | Allocates one device context to be shared by all windows in the class. Because window classes are process specific, it is possible for multiple threads of an application to create a window of the same class. It is also possible for the threads to attempt to use the device context simultaneously. When this happens, the system allows only one thread to successfully finish its drawing operation. For more information, see Device Contexts.
CS_DBLCLKS | Sends double-click messages to the window procedure when the user double-clicks the mouse while the cursor is within a window belonging to the class.
CS_GLOBALCLASS | Allows an application to create a window of the class regardless of the value of the hInstance parameter passed to the CreateWindow or CreateWindowEx function. If you do not specify this style, the hInstance parameter passed to the CreateWindow (or CreateWindowEx) function must be the same as the hInstance parameter passed to the RegisterClass function.
You can create a global class by creating the window class in a dynamic-link library (DLL) and listing the name of the DLL in the registry under the following keys:
HKEY_LOCAL_MACHINE\Software
\Microsoft\Windows NT\
CurrentVersion\Windows\AppInit_DLLs
Whenever a process starts, the system loads the specified DLLs in the context of the newly started process before calling the entry-point function in that process. The DLL must register the class during its initialization procedure and must specify the CS_GLOBALCLASS style.
CS_HREDRAW | Redraws the entire window if a movement or size adjustment changes the width of the client area.
CS_NOCLOSE | Disables Close on the window menu.
CS_OWNDC | Allocates a unique device context for each window in the class.
CS_PARENTDC | Sets the clipping region of the child window to that of the parent window so that the child can draw on the parent. A window with the CS_PARENTDC style bit receives a regular device context from the system's cache of device contexts. It does not give the child the parent's device context or device context settings. Specifying CS_PARENTDC enhances an application's performance. For more information, see Device Contexts.
CS_SAVEBITS | Saves, as a bitmap, the portion of the screen image obscured by a window. The system uses the saved bitmap to re-create the screen image when the window is removed. The system displays the bitmap at its original location and does not send WM_PAINT messages to windows obscured by the window if the memory used by the bitmap has not been discarded and if other screen actions have not invalidated the stored image. This style is useful for small windows (for example, menus or dialog boxes) that are displayed briefly and then removed before other screen activity takes place. This style increases the time required to display the window, because the system must first allocate memory to store the bitmap.
CS_VREDRAW | Redraws the entire window if a movement or size adjustment changes the height of the client area.

lpfnWndProc
Pointer to the window procedure. You must use the CallWindowProc function to call the window procedure. For more information, see WindowProc.
cbClsExtra
Specifies the number of extra bytes to allocate following the window-class structure. The system initializes the bytes to zero.
cbWndExtra
Specifies the number of extra bytes to allocate following the window instance. The system initializes the bytes to zero. If an application uses WNDCLASS to register a dialog box created by using the CLASS directive in the resource file, it must set this member to DLGWINDOWEXTRA.
hInstance
Handle to the instance that the window procedure of this class is within.
hIcon
Handle to the class icon. This member must be a handle of an icon resource. If this member is NULL, an application must draw an icon whenever the user minimizes the application's window.
hCursor
Handle to the class cursor. This member must be a handle of a cursor resource. If this member is NULL, an application must explicitly set the cursor shape whenever the mouse moves into the application's window.
hbrBackground
Handle to the class background brush. This member can be a handle to the physical brush to be used for painting the background, or it can be a color value. A color value must be one of the following standard system colors (the value 1 must be added to the chosen color). If a color value is given, you must convert it to one of the following HBRUSH types:

COLOR_ACTIVEBORDER
COLOR_ACTIVECAPTION
COLOR_APPWORKSPACE
COLOR_BACKGROUND
COLOR_BTNFACE
COLOR_BTNSHADOW
COLOR_BTNTEXT
COLOR_CAPTIONTEXT
COLOR_GRAYTEXT
COLOR_HIGHLIGHT
COLOR_HIGHLIGHTTEXT
COLOR_INACTIVEBORDER
COLOR_INACTIVECAPTION
COLOR_MENU
COLOR_MENUTEXT
COLOR_SCROLLBAR
COLOR_WINDOW
COLOR_WINDOWFRAME
COLOR_WINDOWTEXT

The system automatically deletes class background brushes when the class is freed. An application should not delete these brushes, because a class may be used by multiple instances of an application.

When this member is NULL, an application must paint its own background whenever it is requested to paint in its client area. To determine whether the background must be painted, an application can either process the WM_ERASEBKGND message or test the fErase member of the PAINTSTRUCT structure filled by the BeginPaint function.

lpszMenuName
Pointer to a null-terminated character string that specifies the resource name of the class menu, as the name appears in the resource file. If you use an integer to identify the menu, use the MAKEINTRESOURCE macro. If this member is NULL, windows belonging to this class have no default menu.
lpszClassName
Pointer to a null-terminated string or is an atom. If this parameter is an atom, it must be a global atom created by a previous call to the GlobalAddAtom function. The atom, a 16-bit value, must be in the low-order word of lpszClassName; the high-order word must be zero.

If lpszClassName is a string, it specifies the window class name.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Unicode: Defined as Unicode and ANSI structures.

See Also

Window Classes Overview, Window Class Structures, BeginPaint, CreateWindow, CreateWindowEx, GetDC, GlobalAddAtom, MAKEINTRESOURCE, PAINTSTRUCT, RegisterClass, WNDCLASSEX, WindowProc, WM_PAINT


WNDCLASSEX

The WNDCLASSEX structure contains window class information. It is used with the RegisterClassEx and GetClassInfoEx functions.

The WNDCLASSEX structure is similar to the WNDCLASS structure. There are two differences. WNDCLASSEX includes the cbSize member, which specifies the size of the structure, and the hIconSm member, which contains a handle to a small icon associated with the window class.

typedef struct _WNDCLASSEX {
    UINT    cbSize;
    UINT    style;
    WNDPROC lpfnWndProc;
    int     cbClsExtra;
    int     cbWndExtra;
    HANDLE  hInstance;
    HICON   hIcon;
    HCURSOR hCursor;
    HBRUSH  hbrBackground;
    LPCTSTR lpszMenuName;
    LPCTSTR lpszClassName;
    HICON   hIconSm;
} WNDCLASSEX;

Members

cbSize
Specifies the size, in bytes, of this structure. Set this member to sizeof(WNDCLASSEX). Be sure to set this member before calling the GetClassInfoEx function.
style
Specifies the class style(s). Styles can be combined by using the bitwise OR (|) operator. This member can be any combination of the following values:
Value | Action
CS_BYTEALIGNCLIENT | Aligns the window's client area on the byte boundary (in the x direction). This style affects the width of the window and its horizontal position on the display.
CS_BYTEALIGNWINDOW | Aligns a window on a byte boundary (in the x direction). This style affects the width of the window and its horizontal position on the display.
CS_CLASSDC | Allocates one device context to be shared by all windows in the class. Because window classes are process specific, it is possible for multiple threads of an application to create a window of the same class. It is also possible for the threads to attempt to use the device context simultaneously. When this happens, the system allows only one thread to successfully finish its drawing operation. For more information, see Device Contexts.
CS_DBLCLKS | Sends double-click messages to the window procedure when the user double-clicks the mouse while the cursor is within a window belonging to the class.
CS_GLOBALCLASS | Allows an application to create a window of the class regardless of the value of the hInstance parameter passed to the CreateWindowEx function. If you do not specify this style, the hInstance parameter passed to the CreateWindow (or CreateWindowEx) function must be the same as the hInstance parameter passed to the RegisterClassEx function.
You can create a global class by creating the window class in a dynamic-link library (DLL) and listing the name of the DLL in the registry under the following keys:
HKEY_LOCAL_MACHINE\Software
\Microsoft\Windows NT\
CurrentVersion\Windows\AppInit_DLLs
Whenever a process starts, the system loads the specified DLLs in the context of the newly started process before calling the entry-point function in that process. The DLL must register the class during its initialization procedure and must specify the CS_GLOBALCLASS style.
CS_HREDRAW | Redraws the entire window if a movement or size adjustment changes the width of the client area.
CS_NOCLOSE | Disables Close on the window menu.
CS_OWNDC | Allocates a unique device context for each window in the class. For more information, see Device Contexts.
CS_PARENTDC | Sets the clipping region of the child window to that of the parent window so that the child can draw on the parent. A window with the CS_PARENTDC style bit receives a regular device context from the system's cache of device contexts. It does not give the child the parent's device context or device context settings. Specifying CS_PARENTDC enhances an application's performance. For more information, see Device Contexts.
CS_SAVEBITS | Saves, as a bitmap, the portion of the screen image obscured by a window. The system uses the saved bitmap to re-create the screen image when the window is removed. The system displays the bitmap at its original location and does not send WM_PAINT messages to windows obscured by the window if the memory used by the bitmap has not been discarded and if other screen actions have not invalidated the stored image. This style is useful for small windows (for example, menus or dialog boxes) that are displayed briefly and then removed before other screen activity takes place. This style increases the time required to display the window, because the system must first allocate memory to store the bitmap.
CS_VREDRAW | Redraws the entire window if a movement or size adjustment changes the height of the client area.

lpfnWndProc
Pointer to the window procedure. You must use the CallWindowProc function to call the window procedure. For more information, see WindowProc.
cbClsExtra
Specifies the number of extra bytes to allocate following the window-class structure. The system initializes the bytes to zero.
cbWndExtra
Specifies the number of extra bytes to allocate following the window instance. The system initializes the bytes to zero. If an application uses WNDCLASSEX to register a dialog box created by using the CLASS directive in the resource file, it must set this member to DLGWINDOWEXTRA.
hInstance
Handle to the instance that the window procedure of this class is within.
hIcon
Handle to the class icon. This member must be a handle of an icon resource. If this member is NULL, an application must draw an icon whenever the user minimizes the application's window.
hCursor
Handle to the class cursor. This member must be a handle of a cursor resource. If this member is NULL, an application must explicitly set the cursor shape whenever the mouse moves into the application's window.
hbrBackground
Handle to the class background brush. This member can be a handle to the physical brush to be used for painting the background, or it can be a color value. A color value must be one of the following standard system colors (the value 1 must be added to the chosen color). If a color value is given, you must convert it to one of the following HBRUSH types:

COLOR_ACTIVEBORDER
COLOR_ACTIVECAPTION
COLOR_APPWORKSPACE
COLOR_BACKGROUND
COLOR_BTNFACE
COLOR_BTNSHADOW
COLOR_BTNTEXT
COLOR_CAPTIONTEXT
COLOR_GRAYTEXT
COLOR_HIGHLIGHT
COLOR_HIGHLIGHTTEXT
COLOR_INACTIVEBORDER
COLOR_INACTIVECAPTION
COLOR_MENU
COLOR_MENUTEXT
COLOR_SCROLLBAR
COLOR_WINDOW
COLOR_WINDOWFRAME
COLOR_WINDOWTEXT

The system automatically deletes class background brushes when the class is freed. An application should not delete these brushes, because a class may be used by multiple instances of an application.

When this member is NULL, an application must paint its own background whenever it is requested to paint in its client area. To determine whether the background must be painted, an application can either process the WM_ERASEBKGND message or test the fErase member of the PAINTSTRUCT structure filled by the BeginPaint function.

lpszMenuName
Pointer to a null-terminated character string that specifies the resource name of the class menu, as the name appears in the resource file. If you use an integer to identify the menu, use the MAKEINTRESOURCE macro. If this member is NULL, windows belonging to this class have no default menu.
lpszClassName
Pointer to a null-terminated string or is an atom. If this parameter is an atom, it must be a global atom created by a previous call to the GlobalAddAtom function. The atom, a 16-bit value, must be in the low-order word of lpszClassName; the high-order word must be zero.

If lpszClassName is a string, it specifies the window class name.

hIconSm
Handle to a small icon that is associated with the window class. If this member is NULL, the system searches the icon resource specified by the hIcon member for an icon of the appropriate size to use as the small icon.

QuickInfo

Windows NT: Requires version 3.5 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Unicode: Defined as Unicode and ANSI structures.

See Also

Window Classes Overview, Window Class Structures, GetClassInfoEx, RegisterClassEx


Window Procedures

Every window has an associated window procedure — a function that processes all messages sent or posted to all windows of the class. All aspects of a window's appearance and behavior depend on the window procedure's response to these messages.


About Window Procedures

Each window is a member of a particular window class. The window class determines the default window procedure that an individual window uses to process its messages. All windows belonging to the same class use the same default window procedure. For example, the system defines a window procedure for the combo box class (COMBOBOX); all combo boxes then use that window procedure.

An application typically registers at least one new window class and its associated window procedure. After registering a class, the application can create many windows of that class, all of which use the same window procedure. Because this means several sources could simultaneously call the same piece of code, you must be careful when modifying shared resources from a window procedure. For more information, see Window Classes.

Window procedures for dialog boxes (called dialog box procedures) have a similar structure and function as regular window procedures. All points referring to window procedures in this section also apply to dialog box procedures. For more information, see Dialog Boxes.


Structure of a Window Procedure

A window procedure is a function that has four parameters and returns a 32-bit signed value. The parameters consist of a window handle, a UINT message identifier, and two message parameters declared with the WPARAM and LPARAM data types. For more information, see WindowProc.

Message parameters often contain information in both their low-order and high-order words. The Microsoft® Win32® application programming interface (API) includes several macros an application can use to extract information from the message parameters. The LOWORD macro, for example, extracts the low-order word (bits 0 through 15) from a message parameter. Other macros include HIWORD, LOBYTE, and HIBYTE.

The interpretation of the return value depends on the particular message. Consult the description of each message to determine the appropriate return value.

Because it is possible to call a window procedure recursively, it is important to minimize the number of local variables that it uses. When processing individual messages, an application should call functions outside the window procedure to avoid excessive use of local variables, possibly causing the stack to overflow during deep recursion.


Default Window Procedure

The default window procedure function, DefWindowProc defines certain fundamental behavior shared by all windows. The default window procedure provides the minimal functionality for a window. An application-defined window procedure should pass any messages that it does not process to the DefWindowProc function for default processing.


Window Procedure Subclassing

When an application creates a window, the system allocates a block of memory for storing information specific to the window, including the address of the window procedure that processes messages for the window. When the system needs to pass a message to the window, it searches the window-specific information for the address of the window procedure and passes the message to that procedure.

Subclassing is a technique that allows an application to intercept and process messages sent or posted to a particular window before the window has a chance to process them. By subclassing a window, an application can augment, modify, or monitor the behavior of the window. An application can subclass a window belonging to a system global class, such as an edit control or a list box. For example, an application could subclass an edit control to prevent the control from accepting certain characters. However, you cannot subclass a window or class that belongs to another application. All subclassing must be performed within the same process.

An application subclasses a window by replacing the address of the window's original window procedure with the address of a new window procedure, called the subclass procedure. Thereafter, the subclass procedure receives any messages sent or posted to the window.

The subclass procedure can take three actions upon receiving a message: it can pass the message to the original window procedure, modify the message and pass it to the original window procedure, or process the message and not pass it to the original window procedure. If the subclass procedure processes a message, it can do so before, after, or both before and after it passes the message to the original window procedure.

The system provides two types of subclassing: instance and global. In instance subclassing, an application replaces the window procedure address of a single instance of a window. An application must use instance subclassing to subclass an existing window. In global subclassing, an application replaces the address of the window procedure in the WNDCLASS structure of a window class. All subsequent windows created with the class have the address of the subclass procedure, but existing windows of the class are not affected.


Instance Subclassing

An application subclasses an instance of a window by using the SetWindowLong function. The application passes the GWL_WNDPROC flag, the handle to the window to subclass, and the address of the subclass procedure to SetWindowLong. The subclass procedure can reside in either the application's executable or a dynamic-link library (DLL).

SetWindowLong returns the address of the window's original window procedure. The application must save the address, using it in subsequent calls to the CallWindowProc function, to pass intercepted messages to the original window procedure. The application must also have the original window procedure address to remove the subclass from the window. To remove the subclass, the application calls SetWindowLong again, passing the address of the original window procedure with the GWL_WNDPROC flag and the handle to the window.

The system owns the system global classes, and aspects of the controls might change from one version of the system to the next. If the application must subclass a window that belongs to a system global class, the developer may need to update the application when a new version of the system is released.

Because instance subclassing occurs after a window is created, you cannot add any extra bytes to the window. Applications that subclass a window should use the window's property list to store any data needed for an instance of the subclassed window. For more information, see Window Properties.

When an application subclasses a subclassed window, it must remove the subclasses in the reverse order they were performed. If the removal order is not reversed, an unrecoverable system error may occur.


Global Subclassing

To globally subclass a window class, the application must have a handle to a window of the class. The application also needs the handle to remove the subclass. To get the handle, an application typically creates a hidden window of the class to be subclassed. After obtaining the handle, the application calls the SetClassLong function, specifying the handle, the GCL_WNDPROC flag, and the address of the subclass procedure. SetClassLong returns the address of the original window procedure for the class.

The original window procedure address is used in global subclassing in the same way it is used in instance subclassing. The subclass procedure passes messages to the original window procedure by calling CallWindowProc. The application removes the subclass from the window class by calling SetClassLong again, specifying the address of the original window procedure, the GCL_WNDPROC flag, and the handle to a window of the class being subclassed. An application that globally subclasses a control class must remove the subclass when the application terminates; otherwise, an unrecoverable system error may occur.

Global subclassing has the same limitations as instance subclassing, plus some additional restrictions. An application should not use the extra bytes for either the class or the window instance without knowing exactly how the original window procedure uses them. If the application must associate data with a window, it should use window properties.


Window Procedure Superclassing

Superclassing is a technique that allows an application to create a new window class with the basic functionality of the existing class, plus enhancements provided by the application. A superclass is based on an existing window class called the base class. Frequently, the base class is a system global window class such as an edit control, but it can be any window class.

A superclass has its own window procedure, called the superclass procedure. The superclass procedure can take three actions upon receiving a message: It can pass the message to the original window procedure, modify the message and pass it to the original window procedure, or process the message and not pass it to the original window procedure. If the superclass procedure processes a message, it can do so before, after, or both before and after it passes the message to the original window procedure.

Unlike a subclass procedure, a superclass procedure can process window creation messages (WM_NCCREATE, WM_CREATE, and so on), but it must also pass them to the original base-class window procedure so that the base-class window procedure can perform its initialization procedure.

To superclass a window class, an application first calls the GetClassInfo function to retrieve information about the base class. GetClassInfo fills a WNDCLASS structure with the values from the WNDCLASS structure of the base class. Next, the application copies its own instance handle into the hInstance member of the WNDCLASS structure and copies the name of the superclass into the lpszClassName member. If the base class has a menu, the application must provide a new menu with the same menu identifiers and copy the menu name into the lpszMenuName member. If the superclass procedure processes the WM_COMMAND message and does not pass it to the window procedure of the base class, the menu need not have corresponding identifiers. GetClassInfo does not return the lpszMenuName, lpszClassName, or hInstance member of the WNDCLASS structure.

An application must also set the lpfnWndProc member of the WNDCLASS structure. The GetClassInfo function fills this member with the address of the original window procedure for the class. The application must save this address, to pass messages to the original window procedure, and then copy the address of the superclass procedure into the lpfnWndProc member. The application can, if necessary, modify any other members of the WNDCLASS structure. After it fills the WNDCLASS structure, the application registers the superclass by passing the address of the structure to the RegisterClass function. The superclass can then be used to create windows.

Because superclassing registers a new window class, an application can add to both the extra class bytes and the extra window bytes. The superclass must not use the original extra bytes for the base class or the window for the same reasons that an instance subclass or a global subclass should not use them. Also, if the application adds extra bytes for its use to either the class or the window instance, it must reference the extra bytes relative to the number of extra bytes used by the original base class. Because the number of bytes used by the base class may vary from one version of the base class to the next, the starting offset for the superclass's own extra bytes may also vary from one version of the base class to the next.


Using Window Procedures

  • Designing a window procedure
  • Associating a window procedure with a window class
  • Subclassing a window


Designing a Window Procedure

The following example shows the structure of a typical window procedure. The window procedure uses the message argument in a switch statement with individual messages handled by separate case statements. Notice that each case returns a specific value for each message. For messages that it does not process, the window procedure calls the DefWindowProc function.

LRESULT CALLBACK MainWndProc(
    HWND hwnd,        // handle to window
    UINT uMsg,        // message identifier
    WPARAM wParam,    // first message parameter
    LPARAM lParam)    // second message parameter
{

    switch (uMsg)
    {
        case WM_CREATE:
            // Initialize the window.
            return 0;

        case WM_PAINT:
            // Paint the window's client area.
            return 0;

        case WM_SIZE:
            // Set the size and position of the window.
            return 0;

        case WM_DESTROY:
            // Clean up window-specific data objects.
            return 0;

        //
        // Process other messages.
        //

        default:
            return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }
    return 0;
}

The WM_NCCREATE messageis sent just after your window is created, but if an application responds to this message by returning FALSE, CreateWindowEx function fails. The WM_CREATE message is sent after your window is already created.

The WM_DESTROY message is sent when your window is about to be destroyed. The DestroyWindow function takes care of destroying any child windows of the window being destroyed. The WM_NCDESTROY message is sent just before a window is destroyed.

At the very least, a window procedure should process the WM_PAINT message to draw itself. Typically, it should handle mouse and keyboard messages as well. Consult the descriptions of individual messages to determine whether your window procedure should handle them.

Your application can call the DefWindowProc function as part of the processing of a message. In such a case, the application can modify the message parameters before passing the message to DefWindowProc, or it can continue with the default processing after performing its own operations.

A dialog box procedure receives a WM_INITDIALOG message instead of a WM_CREATE message and does not pass unprocessed messages to the DefDlgProc function. Otherwise, a dialog box procedure is exactly the same as a window procedure.


Associating a Window Procedure with a Window Class

You associate a window procedure with a window class when registering the class. You must fill a WNDCLASS structure with information about the class, and the lpfnWndProc member must specify the address of the window procedure. To register the class, pass the address of WNDCLASS structure to the RegisterClass function. Once the window class is registered, the window procedure is automatically associated with each new window created with that class.

The following example shows how to associate the window procedure in the previous example with a window class.

int APIENTRY WinMain(
    HINSTANCE hinstance,  // handle to current instance
    HINSTANCE hinstPrev,  // handle to previous instance
    LPSTR lpCmdLine,      // address of command-line string
    int nCmdShow)         // show-window type
{
    WNDCLASS wc;

    // Register the main window class.
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = (WNDPROC) MainWndProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = hinstance;
    wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = GetStockObject(WHITE_BRUSH);
    wc.lpszMenuName =  "MainMenu";
    wc.lpszClassName = "MainWindowClass";

    if (!RegisterClass(&wc))
       return FALSE;

    //
    // Process other messages.
    //

}


Subclassing a Window

To subclass an instance of a window, call the SetWindowLong function and specify the handle to the window to subclass the GWL_WNDPROC flag and a pointer to the subclass procedure. SetWindowLong returns a pointer to the original window procedure; use this pointer to pass messages to the original procedure. The subclass window procedure must use the CallWindowProc function to call the original window procedure.

The following example shows how to subclass an instance of an edit control in a dialog box. The subclass window procedure enables the edit control to receive all keyboard input, including the enter and tab keys, whenever the control has the input focus.

WNDPROC wpOrigEditProc;

LRESULT APIENTRY EditBoxProc(
    HWND hwndDlg,
    UINT uMsg,
    WPARAM wParam,
    LPARAM lParam)
{
    HWND hwndEdit;

    switch(uMsg)
    {
        case WM_INITDIALOG:
            // Retrieve the handle to the edit control.
            hwndEdit = GetDlgItem(hwndDlg, ID_EDIT);

            // Subclass the edit control.
            wpOrigEditProc = (WNDPROC) SetWindowLong(hwndEdit,
                GWL_WNDPROC, (LONG) EditSubclassProc);
            //
            // Continue the initialization procedure.
            //
            return TRUE;

        case WM_DESTROY:
            // Remove the subclass from the edit control.
            SetWindowLong(hwndEdit, GWL_WNDPROC,
                (LONG) wpOrigEditProc);
            //
            // Continue the cleanup procedure.
            //
            break;
    }
    return FALSE;
        UNREFERENCED_PARAMETER(lParam);
}

// Subclass procedure
LRESULT APIENTRY EditSubclassProc(
    HWND hwnd,
    UINT uMsg,
    WPARAM wParam,
    LPARAM lParam)
{
    if (uMsg == WM_GETDLGCODE)
        return DLGC_WANTALLKEYS;

    return CallWindowProc(wpOrigEditProc, hwnd, uMsg,
        wParam, lParam);
}


Window Procedure Reference

The following elements are used with window procedures.

  • Window Procedure Functions


Window Procedure Functions

The following functions are used with window procedures.

CallWindowProc
DefWindowProc
WindowProc


CallWindowProc

The CallWindowProc function passes message information to the specified window procedure.

LRESULT CallWindowProc(
  WNDPROC lpPrevWndFunc,  // pointer to previous procedure
  HWND hWnd,              // handle to window
  UINT Msg,               // message
  WPARAM wParam,          // first message parameter
  LPARAM lParam           // second message parameter
);

Parameters

lpPrevWndFunc
Pointer to the previous window procedure.

If this value is obtained by calling the GetWindowLong function with the nIndex parameter set to GWL_WNDPROC or DWL_DLGPROC, it is actually either the address of a window or dialog box procedure, or a handle representing that address.

hWnd
Handle to the window procedure to receive the message.
Msg
Specifies the message.
wParam
Specifies additional message-specific information. The contents of this parameter depend on the value of the Msg parameter.
lParam
Specifies additional message-specific information. The contents of this parameter depend on the value of the Msg parameter.

Return Values

The return value specifies the result of the message processing and depends on the message sent.

Remarks

Use the CallWindowProc function for window subclassing. Usually, all windows with the same class share one window procedure. A subclass is a window or set of windows with the same class whose messages are intercepted and processed by another window procedure (or procedures) before being passed to the window procedure of the class.

The SetWindowLong function creates the subclass by changing the window procedure associated with a particular window, causing the system to call the new window procedure instead of the previous one. An application must pass any messages not processed by the new window procedure to the previous window procedure by calling CallWindowProc. This allows the application to create a chain of window procedures.

If STRICT is defined, the lpPrevWndFunc parameter has the data type WNDPROC. The WNDPROC type is declared as follows:

LRESULT (CALLBACK* WNDPROC) (HWND, UINT, WPARAM, LPARAM);

If STRICT is not defined, the lpPrevWndFunc parameter has the data type FARPROC. The FARPROC type is declared as follows:

int (FAR WINAPI * FARPROC) ()

In C, the FARPROC declaration indicates a callback function that has an unspecified parameter list. In C++, however, the empty parameter list in the declaration indicates that a function has no parameters. This subtle distinction can break careless code. Following is one way to handle this situation:

#ifdef STRICT
  WNDPROC MyWindowProcedure
#else
  FARPROC MyWindowProcedure
#endif
...
    lResult = CallWindowProc(MyWindowProcedure, ...) ;

For further information about functions declared with empty argument lists, refer to The C++ Programming Language, Second Edition, by Bjarne Stroustrup.

Windows NT: The CallWindowProc function handles Unicode-to-ANSI conversion. You cannot take advantage of this conversion if you call the window procedure directly.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Window Procedures Overview, Window Procedure Functions, GetWindowLong, SetClassLong, SetWindowLong


DefWindowProc

The DefWindowProc function calls the default window procedure to provide default processing for any window messages that an application does not process. This function ensures that every message is processed. DefWindowProc is called with the same parameters received by the window procedure.

LRESULT DefWindowProc(
  HWND hWnd,      // handle to window
  UINT Msg,       // message identifier
  WPARAM wParam,  // first message parameter
  LPARAM lParam   // second message parameter
);

Parameters

hWnd
Handle to the window procedure that received the message.
Msg
Specifies the message.
wParam
Specifies additional message information. The content of this parameter depends on the value of the Msg parameter.
lParam
Specifies additional message information. The content of this parameter depends on the value of the Msg parameter.

Return Values

The return value is the result of the message processing and depends on the message.

Remarks

Windows CE: If Msg is WM_SETTEXT, zero is returned.

DefWindowProc does not automatically call PostQuitMessage when it handles a WM_DESTROY message.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Window Procedures Overview, Window Procedure Functions, CallWindowProc, DefDlgProc, WindowProc


WindowProc

The WindowProc function is an application-defined function that processes messages sent to a window. The WNDPROC type defines a pointer to this callback function. WindowProc is a placeholder for the application-defined function name.

LRESULT CALLBACK WindowProc(
  HWND hwnd,      // handle to window
  UINT uMsg,      // message identifier
  WPARAM wParam,  // first message parameter
  LPARAM lParam   // second message parameter
);

Parameters

hwnd
Handle to the window.
uMsg
Specifies the message.
wParam
Specifies additional message information. The contents of this parameter depend on the value of the uMsg parameter.
lParam
Specifies additional message information. The contents of this parameter depend on the value of the uMsg parameter.

Return Values

The return value is the result of the message processing and depends on the message sent.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: User-defined.

See Also

Window Procedures Overview, Window Procedure Functions, CallWindowProc, DefWindowProc, RegisterClass


Window Properties

A window property is any data assigned to a window. A window property is usually a handle of the window-specific data, but it may be any 32-bit value. Each window property is identified by a string name.


About Window Properties

The Win32 API provides several functions that enable applications to use window properties. This overview discusses the following topics:

  • Advantages of Using Window Properties
  • Assigning Window Properties
  • Enumerating Window Properties


Advantages of Using Window Properties

Window properties are typically used to associate data with a subclassed window or a window in a multiple document interface (MDI) application. In either case, it is not convenient to use the extra bytes specified in the CreateWindow function or class structure for the following two reasons:

  • An application might not know how many extra bytes are available or how the space is being used. By using window properties, the application can associate data with a window without accessing the extra bytes.
  • An application must access the extra bytes by using offsets. However, window properties are accessed by their string identifiers, not by offsets.

For more information about subclassing, see Window Procedure Subclassing. For more information about MDI windows, see Multiple Document Interface.


Assigning Window Properties

The SetProp function assigns a window property and its string identifier to a window. The GetProp function retrieves the window property identified by a given string. The RemoveProp function destroys the association between a window and a window property but does not destroy the data itself.


Enumerating Window Properties

The EnumProps and EnumPropsEx functions enumerate all of a window's properties by using an application-defined callback function. For more information about the callback function, see PropEnumProc.

EnumPropsEx includes an extra parameter for application-defined data used by the callback function. For more information about the callback function, see PropEnumProcEx.


Using Window Properties

  • Adding a window property
  • Retrieving a window property
  • Listing window properties for a given window
  • Deleting a window property


Adding a Window Property

The following example loads an icon and then a cursor and allocates memory for a buffer. The example then uses the SetProp function to assign the resulting icon, cursor, and memory handles as window properties for the window identified by the application-defined hwndSubclass variable. The properties are identified by the strings PROP_ICON, PROP_CURSOR, and PROP_BUFFER.

#define BUFFER 4096

HINSTANCE hinst;       // handle of current instance
HWND hwndSubclass;     // handle of a subclassed window
HANDLE hIcon, hCursor;
HGLOBAL hMem;
char *lpMem;
TCHAR tchPath[] = "c:\\winnt\\samples\\winprop.c";

// Load resources.

hIcon = LoadIcon(hinst, MAKEINTRESOURCE(400));
hCursor = LoadCursor(hinst, MAKEINTRESOURCE(220));

// Allocate and fill a memory buffer.

hMem = GlobalAlloc(GPTR, BUFFER);
lpMem = GlobalLock(hMem);
lstrcpy(lpMem, tchPath);
GlobalUnlock(hMem);

// Set the window properties for hwndSubclass.

SetProp(hwndSubclass, "PROP_ICON", hIcon);
SetProp(hwndSubclass, "PROP_CURSOR", hCursor);
SetProp(hwndSubclass, "PROP_BUFFER", hMem);


Retrieving a Window Property

A window can create handles to its window property data and use the data for any purpose. The following example uses GetProp to obtain handles to the window properties identified by PROP_ICON, PROP_CURSOR, and PROP_BUFFER. The example then displays the contents of the newly obtained memory buffer, cursor, and icon in the window's client area.

#define PATHLENGTH 256

HWND hwndSubclass;     // handle of a subclassed window
HANDLE hIconProp, hCursProp;
HGLOBAL hMemProp;
char *lpFilename;
TCHAR tchBuffer[PATHLENGTH];
int nSize;
HDC hdc;

// Get the window properties, then use the data.

hIconProp = (HICON) GetProp(hwndSubclass, "PROP_ICON");
TextOut(hdc, 10, 40, "PROP_ICON", 9);
DrawIcon(hdc, 90, 40, hIconProp);

hCursProp = (HCURSOR) GetProp(hwndSubclass, "PROP_CURSOR");
TextOut(hdc, 10, 85, "PROP_CURSOR", 9);
DrawIcon(hdc, 110, 85, hCursProp);

hMemProp = (HGLOBAL) GetProp(hwndSubclass, "PROP_BUFFER");
lpFilename = GlobalLock(hMemProp);
nSize = sprintf(tchBuffer,
    "Path to file:  %s", lpFilename);
TextOut(hdc, 10, 10, tchBuffer, nSize);


Listing Window Properties for a Given Window

In the following example, the EnumPropsEx function lists the string identifiers of the window properties for the window identified by the application-defined hwndSubclass variable. This function relies on the application-defined callback function WinPropProc to display the strings in the window's client area.

EnumPropsEx(hwndSubclass, WinPropProc, NULL);

// WinPropProc is an application-defined callback function
// that lists a window property.

BOOL CALLBACK WinPropProc(
    HWND hwndSubclass,  // handle of window with property
    LPCSTR lpszString,  // property string or atom
    HANDLE hData)       // data handle
{
    static int nProp = 1;    // property counter
    TCHAR tchBuffer[BUFFER]; // expanded-string buffer
    int nSize;               // size of string in buffer
    HDC hdc;                 // device-context handle

    hdc = GetDC(hwndSubclass);

    // Display window property string in client area.

    nSize = sprintf(tchBuffer, "WinProp %d:  %s", nProp++,
        lpszString);
    TextOut(hdc, 10, nProp * 20, tchBuffer, nSize);

    ReleaseDC(hwndSubclass, hdc);

    return TRUE;
}


Deleting a Window Property

When a window is destroyed, it must destroy any window properties it set. The following example uses the EnumPropsEx function and the application-defined callback function DelPropProc to destroy the properties associated with the window identified by the application-defined hwndSubclass variable. The callback function, which uses the RemoveProp function, is also shown.

case WM_DESTROY:

    EnumPropsEx(hwndSubclass, DelPropProc, NULL);

    PostQuitMessage(0);
    break;

// DelPropProc is an application-defined callback function
// that deletes a window property.

BOOL CALLBACK DelPropProc(
    HWND hwndSubclass,  // handle of window with property
    LPCSTR lpszString,  // property string or atom
    HANDLE hData)       // data handle
{
    RemoveProp(hwndSubclass, lpszString);

    return TRUE;
}


Window Property Reference

The following elements are used with window properties.

  • Window Property Functions


Window Property Functions

The following functions are used with window properties.

EnumProps
EnumPropsEx
GetProp
PropEnumProc
PropEnumProcEx
RemoveProp
SetProp


EnumProps

The EnumProps function enumerates all entries in the property list of a window by passing them, one by one, to the specified callback function. EnumProps continues until the last entry is enumerated or the callback function returns FALSE.

int EnumProps(
  HWND hWnd,               // handle to window
  PROPENUMPROC lpEnumFunc  // pointer to callback function
);

Parameters

hWnd
Handle to the window whose property list is to be enumerated.
lpEnumFunc
Pointer to the callback function. For more information about the callback function, see the PropEnumProc function.

Return Values

The return value specifies the last value returned by the callback function. It is -1 if the function did not find a property for enumeration.

Remarks

An application can remove only those properties it has added. It must not remove properties added by other applications or by the system itself.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Window Properties Overview, Window Property Functions, EnumPropsEx, GetProp, PropEnumProc, RemoveProp, SetProp


EnumPropsEx

The EnumPropsEx function enumerates all entries in the property list of a window by passing them, one by one, to the specified callback function. EnumPropsEx continues until the last entry is enumerated or the callback function returns FALSE.

int EnumPropsEx(
  HWND hWnd,                  // handle to window
  PROPENUMPROCEX lpEnumFunc,  // pointer to callback function
  LPARAM lParam               // application-defined data
);

Parameters

hWnd
Handle to the window whose property list is to be enumerated.
lpEnumFunc
Pointer to the callback function. For more information about the callback function, see the PropEnumProcEx function.
lParam
Contains application-defined data to be passed to the callback function.

Return Values

The return value specifies the last value returned by the callback function. It is -1 if the function did not find a property for enumeration.

Remarks

An application can remove only those properties it has added. It must not remove properties added by other applications or by the system itself.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Window Properties Overview, Window Property Functions, EnumProps, GetProp, PropEnumProcEx, RemoveProp, SetProp


GetProp

The GetProp function retrieves a data handle from the property list of the given window. The given character string identifies the handle to be retrieved. The string and handle must have been added to the property list by a previous call to the SetProp function.

HANDLE GetProp(
  HWND hWnd,         // handle of window
  LPCTSTR lpString   // atom or address of string
);

Parameters

hWnd
Handle to the window whose property list is to be searched.
lpString
Pointer to a null-terminated character string or contains an atom that identifies a string. If this parameter is an atom, it must have been created by using the GlobalAddAtom function. The atom, a 16-bit value, must be placed in the low-order word of the lpString parameter; the high-order word must be zero.

Return Values

If the property list contains the given string, the return value is the associated data handle. Otherwise, the return value is NULL.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Window Properties Overview, Window Property Functions, EnumProps, GlobalAddAtom, RemoveProp, SetProp


PropEnumProc

The PropEnumProc function is an application-defined callback function used with the EnumProps function. The function receives property entries from a window's property list. The PROPENUMPROC type defines a pointer to this callback function. PropEnumProc is a placeholder for the application-defined function name.

BOOL CALLBACK PropEnumProc(
  HWND hwnd,           // handle to window whose property list is
                       // being enumerated
  LPCTSTR lpszString,  // string component of property
  HANDLE hData         // data handle component of property
);

Parameters

hwnd
Handle to the window whose property list is being enumerated.
lpszString
Pointer to a null-terminated string. This string is the string component of a property list entry. This is the string that was specified, along with a data handle, when the property was added to the window's property list via a call to the SetProp function.
hData
Handle to data. This handle is the data component of a property list entry.

Return Values

Return TRUE to continue the property list enumeration.

Return FALSE to stop the property list enumeration.

Remarks

The following restrictions apply to this callback function:

  • The callback function must not yield control or do anything that might yield control to other tasks.
  • The callback function can call the RemoveProp function. However, RemoveProp can remove only the property passed to the callback function through the callback function's parameters.
  • The callback function should not attempt to add properties.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: User-defined.
Unicode: Defined as Unicode and ANSI prototypes.

See Also

Window Properties Overview, Window Property Functions, EnumProps, EnumPropsEx, PropEnumProcEx, RemoveProp, SetProp


PropEnumProcEx

The PropEnumProcEx function is an application-defined callback function used with the EnumPropsEx function. The function receives property entries from a window's property list. The PROPENUMPROCEX type defines a pointer to this callback function. PropEnumProcEx is a placeholder for the application-defined function name.

BOOL CALLBACK PropEnumProcEx(
  HWND hwnd,          // handle of window with property
  LPTSTR lpszString,  // string component of property
  HANDLE hData,       // data handle component of property
  DWORD dwData        // application-defined data
);

Parameters

hwnd
Handle to the window whose property list is being enumerated.
lpszString
Pointer to a null-terminated string. This string is the string component of a property list entry. This is the string that was specified, along with a data handle, when the property was added to the window's property list via a call to the SetProp function.
hData
Handle to data. This handle is the data component of a property list entry.
dwData
Application-defined data. This is the value that was specified as the lParam parameter of the call to EnumPropsEx that initiated the enumeration.

Return Values

Return TRUE to continue the property list enumeration.

Return FALSE to stop the property list enumeration.

Remarks

The following restrictions apply to this callback function:

  • The callback function must not yield control or do anything that might yield control to other tasks.
  • The callback function can call the RemoveProp function. However, RemoveProp can remove only the property passed to the callback function through the callback function's parameters.
  • The callback function should not attempt to add properties.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: User-defined.
Unicode: Defined as Unicode and ANSI prototypes.

See Also

Window Properties Overview, Window Property Functions, EnumProps, EnumPropsEx, PropEnumProc, RemoveProp, SetProp


RemoveProp

The RemoveProp function removes an entry from the property list of the specified window. The specified character string identifies the entry to be removed.

HANDLE RemoveProp(
  HWND hWnd,         // handle to window
  LPCTSTR lpString   // atom or address of string
);

Parameters

hWnd
Handle to the window whose property list is to be changed.
lpString
Pointer to a null-terminated character string or contains an atom that identifies a string. If this parameter is an atom, it must have been created using the AddAtom function. The atom, a 16-bit value, must be placed in the low-order word of lpString; the high-order word must be zero.

Return Values

The return value identifies the specified string. If the string cannot be found in the specified property list, the return value is NULL.

Remarks

An application must free the data handles associated with entries removed from a property list. The application can remove only those properties it has added. It must not remove properties added by other applications or by the system itself.

The RemoveProp function returns the data handle associated with the string so that the application can free the data associated with the handle.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Window Properties Overview, Window Property Functions, AddAtom, EnumProps, EnumPropsEx, GetProp, SetProp


SetProp

The SetProp function adds a new entry or changes an existing entry in the property list of the specified window. The function adds a new entry to the list if the specified character string does not exist already in the list. The new entry contains the string and the handle. Otherwise, the function replaces the string's current handle with the specified handle.

BOOL SetProp(
  HWND hWnd,         // handle of window
  LPCTSTR lpString,  // atom or address of string
  HANDLE hData       // handle of data
);

Parameters

hWnd
Handle to the window whose property list receives the new entry.
lpString
Pointer to a null-terminated string or contains an atom that identifies a string. If this parameter is an atom, it must be a global atom created by a previous call to the GlobalAddAtom function. The atom, a 16-bit value, must be placed in the low-order word of lpString; the high-order word must be zero.
hData
Handle to the data to be copied to the property list. The data handle can identify any value useful to the application.

Return Values

If the data handle and string are added to the property list, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Before destroying a window (that is, before processing the WM_DESTROY message), an application must remove all entries it has added to the property list. The application must use the RemoveProp function to remove the entries.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Window Properties Overview, Window Property Functions, EnumProps, EnumPropsEx, GetProp, GlobalAddAtom, RemoveProp


Windows

In a graphical Win32-based application, a window is a rectangular area of the screen where the application displays output and receives input from the user. Therefore, one of the first tasks of a graphical Win32-based application is to create a window.

A window shares the screen with other windows, including those from other applications. Only one window at a time can receive input from the user. The user can use the mouse, keyboard, or other input device to interact with this window and the application that owns it.


About Windows

This overview describes the programming elements that applications use to create and use windows; manage relationships between windows; and size, move, and display windows. The overview includes the following topics:

  • Desktop Window
  • Application Windows
  • Z Order
  • Window Creation
  • General Window Styles
  • Window Relationships
  • Show State
  • Window Size and Position
  • Window Animation
  • Window Destruction


Desktop Window

When you start the system, it automatically creates the desktop window. The desktop window is a system-defined window that paints the background of the screen and serves as the base for all windows displayed by all applications.

The desktop window uses a bitmap to paint the background of the screen. The pattern created by the bitmap is called the desktop wallpaper. By default, the desktop window uses the bitmap from a .BMP file specified in the registry as the desktop wallpaper.

The GetDesktopWindow function returns a handle to the desktop window.

A system configuration application, such as a Control Panel applet, changes the desktop wallpaper by using the SystemParametersInfo function with the wAction parameter set to SPI_SETDESKWALLPAPER and the lpvParam parameter specifying a bitmap filename. SystemParametersInfo then loads the bitmap from the specified file, uses the bitmap to paint the background of the screen, and enters the new filename in the registry.


Application Windows

Every graphical Win32-based application creates at least one window, called the main window, that serves as the primary interface between the user and the application. Most applications also create other windows, either directly or indirectly, to perform tasks related to the main window. Each window plays a part in displaying output and receiving input from the user.

When you start an application, the system also associates a taskbar button with the application. The taskbar button contains the program icon and title. When the application is active, its taskbar button is displayed in the pushed state.

This section contains the following topics:

  • Components of an Application Window
  • Controls, Dialog Boxes, and Message Boxes


Components of an Application Window

An application window includes elements such as a title bar, a menu bar, the window menu (formerly known as the system menu), the minimize button, the maximize button, the restore button, the close button, a sizing border, a client area, a horizontal scroll bar, and a vertical scroll bar. An application's main window typically includes all of these components. The following illustration shows these components in a typical main window.

The title bar displays an application-defined icon and line of text; typically, the text specifies the name of the application or indicates the purpose of the window. An application specifies the icon and text when creating the window. The title bar also makes it possible for the user to move the window by using a mouse or other pointing device.

Most applications include a menu bar that lists the commands supported by the application. Items in the menu bar represent the main categories of commands. Clicking an item on the menu bar typically opens a pop-up menu whose items correspond to the tasks within a given category. By clicking a command, the user directs the application to carry out a task.

The window menu is created and managed by the system. It contains a standard set of menu items that, when chosen by the user, set a window's size or position, close the application, or perform tasks. For more information, see Menus.

When you click the maximize or minimize button, this affects the size and position of the window. When you click the maximize button, the system enlarges the window to the size of the screen and positions the window, so it covers the entire desktop, minus the taskbar. At the same time, the system replaces the maximize button with the restore button. The restore button is a bitmap that, when clicked, restores the window to its previous size and position.

When the user clicks the minimize button, the system reduces the window to the size of its taskbar button, positions the window over the taskbar button, and displays the taskbar button in its normal state. To restore the application to its previous size and position, click its taskbar button.

The sizing border is an area around the perimeter of the window that enables the user to size the window by using a mouse or other pointing device.

The client area is the part of a window where the application displays output, such as text or graphics. For example, a desktop publishing application displays the current page of a document in the client area. The application must provide a function, called a window procedure, to process input to the window and display output in the client area. For more information, see Window Procedures.

The horizontal scroll bar and vertical scroll bar convert mouse or keyboard input into values that an application uses to shift the contents of the client area either horizontally or vertically. For example, a word-processing application that displays a lengthy document typically provides a vertical scroll bar to enable the user to page up and down through the document.

The title bar, menu bar, window menu, minimize and maximize buttons, sizing border, and scroll bars are referred to collectively as the window's nonclient area. The system manages most aspects of the nonclient area; the application manages everything else about the window. In particular, eac application manages the appearance and behavior of its client area.


Controls, Dialog Boxes, and Message Boxes

An application uses several types of windows in addition to its main window, including controls, dialog boxes, and message boxes.

A control is a window that an application uses to obtain a specific piece of information from the user, such as the name of a file to open or the desired point size of a text selection. Applications also use controls to obtain information needed to control a particular feature of an application. For example, a word-processing application typically provides a control to let the user turn word wrapping on and off. For more information, see Controls.

Controls are always used in conjunction with another window — typically, a dialog box. A dialog box is a window that contains one or more controls. An application uses a dialog box to prompt the user for input needed to complete a command. For example, an application that includes a command to open a file would display a dialog box that includes controls in which the user specifies a path and filename.

A message box is a window that displays a note, caution, or warning to the user. For example, a message box can inform the user of a problem the application has encountered while performing a task.

Dialog boxes and message boxes do not typically use the same set of window components as does a main window. Most have a title bar, a window menu, a border (non-sizing), and a client area, but they typically do not have a menu bar, minimize and maximize buttons, or scroll bars. For more information, see Dialog Boxes.


Z Order

The Z order of a window indicates the window's position in a stack of overlapping windows. This window stack is oriented along an imaginary axis, the z-axis, extending outward from the screen. The window at the top of the Z order overlaps all other windows. The window at the bottom of the Z order is overlapped by all other windows.

The system maintains the Z order in a single list. It adds windows to the Z order based on whether they are topmost windows, top-level windows, or child windows. A topmost window overlaps all other non-topmost windows, regardless of whether it is the active or foreground window. A topmost window has the WS_EX_TOPMOST style. All topmost windows appear in the Z order before any non-topmost windows. A child window is grouped with its parent in Z order.

When an application creates a window, the system puts it at the top of the Z order for windows of the same type. You can use the BringWindowToTop function to bring a window to the top of the Z order for windows of the same type. You can rearrange the Z order by using the SetWindowPos and DeferWindowPos functions.

The user changes the Z order by activating a different window. The system positions the active window at the top of the Z order for windows of the same type. When a window comes to the top of Z order, so do its child windows. You can use the GetTopWindow function to search all child windows of a parent window and return a handle to the child window that is highest in Z order. The GetNextWindow function retrieves a handle to the next or previous window in Z order.


Window Creation

An application creates its windows (including the main window) by using the CreateWindow or CreateWindowEx function and providing the information required to define the attributes of the window. CreateWindowEx has a parameter, dwExStyle, that CreateWindow does not have; otherwise, the functions are identical. In fact, CreateWindow simply calls CreateWindowEx, setting the dwExStyle parameter to zero. For this reason, the remainder of this overview refers only to CreateWindowEx.

There are additional functions — including DialogBox, CreateDialog, and MessageBox — for creating special-purpose windows such as dialog boxes and message boxes. For more information, see Dialog Boxes.

This section contains the following topics:

  • Window Attributes
  • Window Handles
  • Main Window Creation
  • Window-Creation Messages
  • Multithread Applications


Window Attributes

An application must provide the following information when creating a window:

  • Window class
  • Window name
  • Window style
  • Parent or owner window
  • Size
  • Location
  • Position
  • Child-window identifier or menu handle
  • Instance handle
  • Creation data

These attributes are described in the following sections.

Window Class

Every window belongs to a window class. An application must register a window class before creating any windows of that class. The window class defines most aspects of a window's appearance and behavior. The chief component of a window class is the window procedure, a function that receives and processes all input and requests sent to the window. The system provides the input and requests in the form of messages. For more information, see Window Classes, Window Procedures, or Messages and Message Queues.

Window Name

A window name (also called window text) is a text string that identifies a window for the user. A main window, dialog box, or message box typically displays its window name in its title bar, if present. For a control, the appearance of the window name depends on the control's class. A button, edit control, or static control displays its window name within the rectangle occupied by the control. A list box, combo box, or static control does not display its window name.

An application uses the SetWindowText function to change the window name after creating the window. It uses the GetWindowTextLength and GetWindowText functions to retrieve the current window-name text from a window.

Window Style

Every window has one or more window styles. A window style is a named constant that defines an aspect of the window's appearance and behavior that is not specified by the window's class. For example, the SCROLLBAR class creates a scroll bar control, but the SBS_HORZ and SBS_VERT styles determine whether a horizontal or vertical scroll bar control is created. A few window styles apply to all windows, but most apply to windows of specific window classes. The system and, to some extent, the window procedure for the class, interpret the window styles.

Parent or Owner Window

A window can have a parent window. A window that has a parent is called a child window. The parent window provides the coordinate system used for positioning a child window. Having a parent window affects aspects of a window's appearance; for example, a child window is clipped so that no part of the child window can appear outside the borders of its parent window. A window that has no parent, or whose parent is the desktop window, is called a top-level window. An application uses the EnumWindows function to obtain a handle to each of its top-level windows. EnumWindows passes the handle to each top-level window, in turn, to an application-defined callback function, EnumWindowsProc.

A window can own, or be owned by, another window. An owned window always appears in front of its owner window, is hidden when its owner window is minimized, and is destroyed when its owner window is destroyed.

Location, Size, and Position in the Z Order

Every window has a location, size, and position in the Z order. The location is the coordinates of the window's upper left corner, relative to the upper left corner of the screen or, in the case of a child window, the upper left corner of the parent's client area. A window's size is its width and height measured in pixels. A window's position in the Z order is the position of the window in a stack of overlapping windows. For more information, see Z Order.

Child-Window Identifier or Menu Handle

A child window can have a child-window identifier, a unique, application-defined value associated with the child window. Child-window identifiers are especially useful in applications that create multiple child windows. When creating a child window, an application specifies the identifier of the child window. After creating the window, the application can change the window's identifier by using the SetWindowLong function, or it can retrieve the identifier by using the GetWindowLong function.

Every window, except a child window, can have a menu. An application can include a menu by providing a menu handle either when registering the window's class or when creating the window.

Instance Handle

Every Win32-based application has an instance handle associated with it. The system provides the instance handle to an application when the application starts. Because it can run multiple copies of the same application, the system uses instance handles internally to distinguish one instance of an application from another. The application must specify the instance handle in many different windows, including those that create windows.

Creation Data

Every window can have application-defined creation data associated with it. When the window is first created, the system passes a pointer to the data on to the window procedure of the window being created. The window procedure uses the data to initialize application-defined variables.


Window Handles

After creating a window, the creation function returns a window handle that uniquely identifies the window. An application uses this handle in other functions to direct their actions to the window. A window handle has the HWND data type; an application must use this type when declaring a variable that holds a window handle.

There are special constants that can replace a window handle in certain functions. For example, an application can use HWND_BROADCAST in the SendMessage and SendMessageTimeout functions, or HWND_DESKTOP in the MapWindowPoints function.

Although the NULL constant is not a window handle, you can use it in some functions to specify that no window is affected. For example, specifying NULL for the CreateWindowEx function's hwndParent parameter creates a window that has no parent or owner. Specifying NULL for the MessageBox function's hWnd parameter creates a message box that has no owner. Some functions may return NULL instead of a handle, indicating that the given action applies to no window.

An application can use the FindWindow function to discover whether a window with the specified class name or window name exists in the system. If such a window exists, FindWindow returns a handle to the window. To limit the search to the child windows of a particular application, use the FindWindowEx function. The IsWindow function determines whether a window handle identifies a valid, existing window.


Main Window Creation

Every Win32-based application must have WinMain as its entry point function. WinMain performs a number of tasks, including registering the window class for the main window and creating the main window. WinMain registers the main window class by calling the RegisterClass function, and it creates the main window by calling the CreateWindowEx function.

Portability Issue The entry point need not be named WinMain.

Your WinMain function can also limit your application to a single instance. Create a named mutex using the CreateMutex function. If GetLastError returns ERROR_ALREADY_EXISTS, another instance of your application exists (it created the mutex) and you should exit WinMain.

The system does not automatically display the main window after creating it; instead, an application must use the ShowWindow function to display the main window. After creating the main window, the application's WinMain function calls ShowWindow, passing it two parameters: a handle to the main window and a flag specifying whether the main window should be minimized or maximized when it is first displayed. Normally, the flag can be set to any of the constants beginning with the SW_ prefix. However, when ShowWindow is called to display the application's main window, the flag must be set to SW_SHOWDEFAULT. This flag tells the system to display the window as directed by the program that started the application.

If a window class was registered with the Unicode version of RegisterClass, the window receives only Unicode messages. To determine whether a window uses the Unicode character set or not, call IsWindowUnicode.


Window-Creation Messages

When creating any window, the system sends messages to the window procedure for the window. The system sends the WM_NCCREATE message after creating the window's nonclient area and the WM_CREATE message after creating the client area. The window procedure receives both messages before the system displays the window. Both messages include a pointer to a CREATESTRUCT structure that contains all the information specified in the CreateWindowEx function. Typically, the window procedure performs initialization tasks upon receiving these messages.

When creating a child window, the system sends the WM_PARENTNOTIFY message to the parent window after sending the WM_NCCREATE and WM_CREATE messages. It also sends other messages while creating a window. The number and order of these messages depend on the window class and style and on the function used to create the window. These messages are described in other topics in this help file.


Multithread Applications

A Win32-based application can have multiple threads of execution, and each thread can create windows. The thread that creates a window must contain the code for its window procedure.

An application can use the EnumThreadWindows function to enumerate the windows created by a particular thread. This function passes the handle to each thread window, in turn, to an application-defined callback function, EnumThreadWndProc.

The GetWindowThreadProcessId function returns the identifier of the thread that created a particular window.

To set the show state of a window created by another thread, use the ShowWindowAsync function.


General Window Styles

There are general window styles and class-specific window styles. The general windows styles are represented by constants that begin with the WS_ prefix; they can be combined with the OR operator to form different types of windows, including main windows, dialog boxes, and child windows. The class-specific window styles define the appearance and behavior of windows belonging to the predefined control classes such as edit controls and list boxes.

An application usually sets window styles when creating windows. It can also set the styles after creating a window by using the SetWindowLong function.

This section contains the following topics:

  • Overlapped Window
  • Pop-up Window
  • Child Window
  • Message-Only Window
  • Window Border
  • Nonclient-Area Components
  • Initial State
  • Parent and Child Styles
  • Extended Styles


Overlapped Window

An overlapped window is a top-level window that has a title bar, border, and client area; it is meant to serve as an application's main window. It can also have a window menu, minimize and maximize buttons, and scroll bars. An overlapped window used as a main window typically includes all of these components.

By specifying the WS_OVERLAPPED or WS_OVERLAPPEDWINDOW style in the CreateWindowEx function, an application creates an overlapped window. If you use the WS_OVERLAPPED style, the window has a title bar and border. If you use the WS_OVERLAPPEDWINDOW style, the window has a title bar, sizing border, window menu, and minimize and maximize buttons.


Pop-up Window

A pop-up window is a special type of overlapped window used for dialog boxes, message boxes, and other temporary windows that appear outside an application's main window. Title bars are optional for pop-up windows; otherwise, pop-up windows are the same as overlapped windows of the WS_OVERLAPPED style.

You create a pop-up window by specifying the WS_POPUP style in CreateWindowEx. To include a title bar, specify the WS_CAPTION style. Use the WS_POPUPWINDOW style to create a pop-up window that has a border and a window menu. The WS_CAPTION style must be combined with the WS_POPUPWINDOW style to make the window menu visible.


Child Window

A child window has the WS_CHILD style and is confined to the client area of its parent window. An application typically uses child windows to divide the client area of a parent window into functional areas. You create a child window by specifying the WS_CHILD style in the CreateWindowEx function.

A child window must have a parent window. The parent window can be an overlapped window, a pop-up window, or even another child window. You specify the parent window when you call CreateWindowEx. If you specify the WS_CHILD style in CreateWindowEx but do not specify a parent window, the system does not create the window.

A child window has a client area but no other features, unless they are explicitly requested. An application can request a title bar, a window menu, minimize and maximize buttons, a border, and scroll bars for a child window, but a child window cannot have a menu. If the application specifies a menu handle, either when it registers the child's window class or creates the child window, the menu handle is ignored.

Positioning

The system always positions a child window relative to the upper left corner of its parent window's client area. No part of a child window ever appears outside the borders of its parent window. If an application creates a child window that is larger than the parent window or positions a child window so that some or all of the child window extends beyond the borders of the parent, the system clips the child window; that is, the portion outside the parent window's client area is not displayed. Actions that affect the parent window can also affect the child window, as follows.

Parent window | Child window
Destroyed | Destroyed before the parent window is destroyed.
Hidden | Hidden before the parent window is hidden. A child window is visible only when the parent window is visible.
Moved | Moved with the parent window's client area. The child window is responsible for painting its client area after the move.
Shown | Shown after the parent window is shown.

Clipping

The system does not automatically clip a child window from the parent window's client area. This means the parent window draws over the child window if it carries out any drawing in the same location as the child window. However, the system does clip the child window from the parent window's client area if the parent window has the WS_CLIPCHILDREN style. If the child window is clipped, the parent window cannot draw over it.

A child window can overlap other child windows in the same client area. A child window that shares the same parent window as one or more other child windows is called a sibling window. Sibling windows can draw in each other's client area, unless one of the child windows has the WS_CLIPSIBLINGS style. If a child window does have this style, any portion of its sibling window that lies within the child window is clipped.

If a window has either the WS_CLIPCHILDREN or WS_CLIPSIBLINGS style, a slight loss in performance occurs. Each window takes up system resources, so an application should not use child windows indiscriminately. For best performance, an application that needs to logically divide its main window should do so in the window procedure of the main window rather than by using child windows.

Relationship to Parent Window

An application can change the parent window of an existing child window by calling the SetParent function. In this case, the system removes the child window from the client area of the old parent window and moves it to the client area of the new parent window. If SetParent specifies a NULL handle, the desktop window becomes the new parent window. In this case, the child window is drawn on the desktop, outside the borders of any other window. The GetParent function retrieves a handle to a child window's parent window.

The parent window relinquishes a portion of its client area to a child window, and the child window receives all input from this area. The window class need not be the same for each of the child windows of the parent window. This means that an application can fill a parent window with child windows that look different and carry out different tasks. For example, a dialog box can contain many types of controls, each one a child window that accepts different types of data from the user.

A child window has only one parent window, but a parent can have any number of child windows. Each child window, in turn, can have child windows. In this chain of windows, each child window is called a descendant window of the original parent window. An application uses the IsChild function to discover whether a given window is a child window or a descendant window of a given parent window.

The EnumChildWindows function enumerates the child windows of a parent window. Then, EnumChildWindows passes the handle to each child window to an application-defined callback function. Descendant windows of the given parent window are also enumerated.

Messages

The system passes a child window's input messages directly to the child window; the messages are not passed through the parent window. The only exception is if the child window has been disabled by the EnableWindow function. In this case, the system passes any input messages that would have gone to the child window to the parent window instead. This permits the parent window to examine the input messages and enable the child window, if necessary.

A child window can have a unique integer identifier. Child window identifiers are important when working with control windows. An application directs a control's activity by sending it messages. The application uses the control's child window identifier to direct the messages to the control. In addition, a control sends notification messages to its parent window. A notification message includes the control's child window identifier, which the parent uses to identify which control sent the message. An application specifies the child-window identifier for other types of child windows by setting the hMenu parameter of the CreateWindowEx function to a value rather than a menu handle.


Message-Only Window

[This is preliminary documentation and subject to change.]

Windows NT 5.0 and later

A message-only window enables you to send and receive messages. It is not visible, has no Z order, cannot be enumerated, and does not receive broadcast messages. The window simply dispatches messages.

To create a message-only window, specify the HWND_MESSAGE constant or a handle to an existing message-only window in the hWndParent parameter of the CreateWindowEx function. You can also change an existing window to a message-only window by specifying HWND_MESSAGE in the hWndNewParent parameter of the SetParent function.

To find message-only windows, specify HWND_MESSAGE in the hwndParent parameter of the FindWindowEx function. In addition, FindWindowEx searches message-only windows as well as top-level windows if both the hwndParent and hwndChildAfter parameters are NULL.


Window Border

A window can have one of the following border styles.

Border Style | Description
WS_BORDER | Creates a window with a thin-line border.
WS_DLGFRAME | Creates a window with a double border, a style typically used with dialog boxes. A window with this style cannot have a title bar.
WS_EX_DLGMODALFRAME | Creates a window with a double border. Unlike the WS_DLGFRAME style, an application can also specify the WS_CAPTION style to create a title bar for the window.
WS_EX_STATICEDGE | Creates a window with a three-dimensional border style intended to be used for items that do not accept user input.
WS_THICKFRAME | Creates a window with a sizing border.

A window with the WS_OVERLAPPED or WS_POPUPWINDOW style has the WS_BORDER style by default. One of the other border styles must be combined with the WS_OVERLAPPED or WS_POPUPWINDOW style to give an overlapped window a different border style.

If no border style is specified for a window with the WS_POPUP or WS_CHILD style, the system creates a borderless window. An application can use borderless child windows to divide the parent window's client area while keeping the divisions invisible to the user.


Nonclient-Area Components

The nonclient area of a window can include a title bar, window menu, minimize and maximize buttons, sizing border, and horizontal and vertical scroll bars. An application can create a window with one or more of these components by specifying the following styles in the CreateWindowEx function.

Style | Description
WS_CAPTION | Creates a window that has a title bar (includes the WS_BORDER style).
WS_HSCROLL | Creates a window that has a horizontal scroll bar.
WS_MAXIMIZEBOX | Creates a window that has a maximize button. Cannot be combined with the WS_EX_CONTEXTHELP style.
WS_MINIMIZEBOX | Creates a window that has a minimize button. Cannot be combined with the WS_EX_CONTEXTHELP style.
WS_SYSMENU | Creates a window that has a window-menu in its title bar. The WS_CAPTION style must also be specified.
WS_VSCROLL | Creates a window that has a vertical scroll bar.


Initial State

The following styles determine whether a window is enabled or disabled, visible or invisible, and minimized or maximized.

Style | Description
WS_DISABLED | Creates a window that is initially disabled. A disabled window cannot receive input from the user.
WS_MAXIMIZE | Creates a window that is initially maximized.
WS_MINIMIZE | Creates a window that is initially minimized.
WS_VISIBLE | Creates a window that is initially visible.


Parent and Child Styles

The following styles affect the clipping relationship between a parent window and its child windows, and between a child window and its sibling windows.

Style | Description
WS_CLIPCHILDREN | Excludes the area occupied by child windows when drawing within the parent window. Use this style when creating the parent window.
WS_CLIPSIBLINGS | Clips child windows relative to each other; that is, when a particular child window receives a WM_PAINT message, the WS_CLIPSIBLINGS style clips all other overlapping child windows out of the region of the child window to be updated. If WS_CLIPSIBLINGS is not specified and child windows overlap, it is possible, when drawing within the client area of one child window, to draw within the client area of another neighboring child window.


Extended Styles

The following styles can be specified in the dwExStyle parameter of the CreateWindowEx function.

Style | Description
WS_EX_ACCEPTFILES | Specifies that a window created with this style accepts drag-drop files.
WS_EX_CONTEXTHELP Includes a question mark in the title bar of the window. When the user clicks the question mark, the cursor changes to a question mark with a pointer. If the user then clicks a child window, the child receives a WM_HELP message. The child window should pass the message to the parent window procedure, which should call the WinHelp function using the HELP_WM_HELP command. The application displays a pop-up window that typically contains help for the child window.

WS_EX_CONTEXTHELP cannot be used with the WS_MAXIMIZEBOX or WS_MINIMIZEBOX styles.
WS_EX_CONTROLPARENT | Allows the user to navigate among the child windows of the window by using the tab key.
WS_EX_DLGMODALFRAME | Creates a window with a double border. Unlike the WS_DLGFRAME style, an application can also specify the WS_CAPTION style to create a title bar for the window.
WS_EX_NOPARENTNOTIFY | Specifies that a child window created with this style will not send the WM_PARENTNOTIFY message to its parent window when either created or destroyed.
WS_EX_TOPMOST | Specifies that a window created with this style should be placed above all non-topmost windows and stay above them even when the window is deactivated.
WS_EX_TOOLWINDOW | Creates a tool window; that is, a window intended to be used as a floating toolbar. A tool window has a title bar that is shorter than a normal title bar, and the window title is drawn using a smaller font. A tool window does not appear in the task bar or in the window that appears when the user presses ALT+TAB. If a tool window has a system menu, its icon is not displayed on the title bar. However, you can display the system menu by right-clicking or by typing alt+space.


Window Relationships

A window may be an owned window, disabled window, foreground window, or background window. These are some of the different ways that a window can relate to the user or another window.


Owned Windows

An overlapped or pop-up window can be owned by another overlapped or pop-up window. Being owned places several constraints on a window.

  • An owned window is always above its owner in the Z order.
  • The system automatically destroys an owned window when its owner is destroyed.
  • An owned window is hidden when its owner is minimized.

Only an overlapped or pop-up window can be an owner window; a child window cannot be an owner window. An application creates an owned window by specifying the owner's window handle as the hwndParent parameter of CreateWindowEx when it creates a window with the WS_OVERLAPPED or WS_POPUP style. The hwndParent parameter must identify an overlapped or pop-up window. If hwndParent identifies a child window, the system assigns ownership to the top-level parent window of the child window. After creating an owned window, an application cannot transfer ownership of the window to another window.

Dialog boxes and message boxes are owned windows by default. An application specifies the owner window when calling a function that creates a dialog box or message box.

An application can use the GetWindow function with the GW_OWNER flag to retrieve a handle to a window's owner.


Disabled Windows

A window can be disabled. A disabled window receives no keyboard or mouse input from the user, but it can receive messages from other windows, from other applications, and from the system. An application typically disables a window to prevent the user from using the window. For example, an application may disable a push button in a dialog box to prevent the user from choosing it. An application can enable a disabled window at any time; enabling a window restores normal input.

By default, a window is enabled when created. An application can specify the WS_DISABLED style, however, to disable a new window. An application enables or disables an existing window by using the EnableWindow function. The system sends a WM_ENABLE message to a window when its enabled state is about to change. An application can determine whether a window is enabled by using the IsWindowEnabled function.

When a child window is disabled, the system passes the child's mouse input messages to the parent window. The parent uses the messages to determine whether to enable the child window. For more information, see Mouse Input.

Only one window at a time can receive keyboard input; that window is said to have the keyboard focus. If an application uses the EnableWindow function to disable a keyboard-focus window, the window loses the keyboard focus in addition to being disabled. EnableWindow then sets the keyboard focus to NULL, meaning no window has the focus. If a child window, or other descendant window, has the keyboard focus, the descendant window loses the focus when the parent window is disabled. For more information, see Keyboard Input.


Foreground and Background Windows

Each process can have multiple threads of execution, and each thread can create windows. The thread that created the window with which the user is currently working is called the foreground thread, and the window is called the foreground window. All other threads are background threads, and the windows created by background threads are called background windows.

Each thread has a priority level that determines the amount of CPU time the thread receives. Although an application can set the priority level of its threads, normally the foreground thread has a slightly higher priority level than the background threads. Because it has a higher priority, the foreground thread receives more CPU time than the background threads. The foreground thread has a normal base priority of 9; a background thread has a normal base priority of 7.

The user sets the foreground window by clicking a window, or by using the alt+tab or alt+esc key combination. An application sets the foreground window by using the SetForegroundWindow function. If the new foreground window is a top-level window, the system activates it; otherwise, it activates the associated top-level window. An application retrieves a handle to the foreground window by using the GetForegroundWindow function. To check if your application window is active, compare the handle returned by GetForegroundWindow to that of your application window.


Show State

At any one given time, a window may be active or inactive; hidden or visible; and minimized, maximized, or restored. These qualities are referred to collectively as the window's show state. The following topics discuss the window show state:

  • Active Window
  • Window Visibility
  • Minimized, Maximized, and Restored Windows


Active Window

An active window is the top-level window of the application with which the user is currently working. To allow the user to easily identify the active window, the system places it at the top of the Z order and changes the color of its title bar and border to the system-defined active window colors. Only a top-level window can be an active window. When the user is working with a child window, the system activates the top-level parent window associated with the child window.

Only one top-level window in the system is active at a time. The user activates a top-level window by clicking it (or one of its child windows), or by using the alt+esc or alt+tab key combination. An application activates a top-level window by calling the SetActiveWindow function. Other functions can cause the system to activate a different top-level window, including SetWindowPos, DeferWindowPos, SetWindowPlacement, and DestroyWindow. Although an application can activate a different top-level window at any time, to avoid confusing the user, it should do so only in response to a user action. An application uses the GetActiveWindow function to retrieve a handle to the active window.

When the activation changes from a top-level window of one application to the top-level window of another, the system sends a WM_ACTIVATEAPP message to both applications, notifying them of the change. When the activation changes to a different top-level window in the same application, the system sends both windows a WM_ACTIVATE message.


Window Visibility

A window can be either visible or hidden. The system displays a visible window on the screen. It hides a hidden window by not drawing it. If a window is visible, the user can supply input to the window and view the window's output. If a window is hidden, it is effectively disabled. A hidden window can process messages from the system or from other windows, but it cannot process input from the user or display output. An application sets a window's visibility state when creating the window. Later, the application can change the visibility state.

A window is visible when the WS_VISIBLE style is set for the window. By default, the CreateWindowEx function creates a hidden window unless the application specifies the WS_VISIBLE style. Typically, an application sets the WS_VISIBLE style after it has created a window to keep details of the creation process hidden from the user. For example, an application may keep a new window hidden while it customizes the window's appearance. If the WS_VISIBLE style is specified in CreateWindowEx, the system sends the WM_SHOWWINDOW message to the window after creating the window, but before displaying it.

An application can determine whether a window is visible by using the IsWindowVisible function. An application can show (make visible) or hide a window by using the ShowWindow, SetWindowPos, DeferWindowPos, or SetWindowPlacement function. These functions show or hide a window by setting or removing the WS_VISIBLE style for the window. They also send the WM_SHOWWINDOW message to the window before showing or hiding it.

When an owner window is minimized, the system automatically hides the associated owned windows. Similarly, when an owner window is restored, the system automatically shows the associated owned windows. In both cases, the system sends the WM_SHOWWINDOW message to the owned windows before hiding or showing them. Occasionally, an application may need to hide the owned windows without having to minimize or hide the owner. In this case, the application uses the ShowOwnedPopups function. This function sets or removes the WS_VISIBLE style for all owned windows and sends the WM_SHOWWINDOW message to the owned windows before hiding or showing them. Hiding an owner window has no effect on the visibility state of the owned windows.

When a parent window is visible, its associated child windows are also visible. Similarly, when the parent window is hidden, its child windows are also hidden. Minimizing the parent window has no effect on the visibility state of the child windows; that is, the child windows are minimized along with the parent, but the WS_VISIBLE style is not changed.

Even if a window has the WS_VISIBLE style, the user may not be able to see the window on the screen; other windows may completely overlap it or it may have been moved beyond the edge of the screen. Also, a visible child window is subject to the clipping rules established by its parent-child relationship. If the window's parent window is not visible, it will also not be visible. If the parent window moves beyond the edge of the screen, the child window also moves because a child window is drawn relative to the parent's upper left corner. For example, a user may move the parent window containing the child window far enough off the edge of the screen that the user may not be able to see the child window, even though the child window and its parent window both have the WS_VISIBLE style.


Minimized, Maximized, and Restored Windows

A maximized window is a window that has the WS_MAXIMIZE style. By default, the system enlarges a maximized window so that it fills the screen or, in the case of a child window, the parent window's client area. Although a window's size can be set to the same size of a maximized window, a maximized window is slightly different. The system automatically moves the window's title bar to the top of the screen or to the top of the parent window's client area. Also, the system disables the window's sizing border and the window-positioning capability of the title bar (so that the user cannot move the window by dragging the title bar).

A minimized window is a window that has the WS_MINIMIZE style. By default, the system reduces a minimized window to the size of its taskbar button and moves the minimized window to the taskbar. A restored window is a window that has been returned to its previous size and position, that is, the size it was before it was minimized or maximized.

If an application specifies the WS_MAXIMIZE or WS_MINIMIZE style in the CreateWindowEx function, the window is initially maximized or minimized. After creating a window, an application can use the CloseWindow function to minimize the window. The ArrangeIconicWindows function arranges the icons on the desktop, or it arranges a parent window's minimized child windows in the parent window. The OpenIcon function restores a minimized window to its previous size and position.

The ShowWindow function can minimize, maximize, or restore a window. It can also set the window's visibility and activation states. The SetWindowPlacement function includes the same functionality as ShowWindow, but it can override the window's default minimized, maximized, and restored positions.

The IsZoomed and IsIconic functions determine whether a given window is maximized or minimized, respectively. The GetWindowPlacement function retrieves the minimized, maximized, and restored positions for the window, and also determines the window's show state.

When the system receives a command to maximize or restore a minimized window, it sends the window a WM_QUERYOPEN message. If the window procedure returns FALSE, the system ignores the maximize or restore command.

The system automatically sets the size and position of a maximized window to the system-defined defaults for a maximized window. To override these defaults, an application can either call the SetWindowPlacement function or process the WM_GETMINMAXINFO message that is received by a window when the system is about to maximize the window. WM_GETMINMAXINFO includes a pointer to a MINMAXINFO structure containing values the system uses to set the maximized size and position. Replacing these values overrides the defaults.


Window Size and Position

A window's size and position are expressed as a bounding rectangle, given in coordinates relative to the screen or the parent window. The coordinates of a top-level window are relative to the upper left corner of the screen; the coordinates of a child window are relative to the upper left corner of the parent window. An application specifies a window's initial size and position when it creates the window, but it can change the window's size and position at any time. For more information, see Filled Shapes.

This section contains the following topics:

  • Window Size
  • Window Position
  • Default Size and Position
  • Tracking Size
  • System Commands
  • Size and Position Functions
  • Size and Position Messages


Window Size

A window's size (width and height) is given in pixels. A window can have zero width or height. If an application sets a window's width and height to zero, the system sets the size to the default minimum window size. To discover the default minimum window size, an application uses the GetSystemMetrics function with the SM_CXMIN and SM_CYMIN flags.

An application may need to create a window with a client area of a particular size. The AdjustWindowRect and AdjustWindowRectEx functions calculate the required size of a window based on the desired size of the client area. The application can pass the resulting size values to the CreateWindowEx function.

An application can size a window so that it is extremely large; however, it should not size a window so that it is larger than the screen. Before setting a window's size, the application should check the width and height of the screen by using GetSystemMetrics with the SM_CXSCREEN and SM_CYSCREEN flags.


Window Position

A window's position is defined as the coordinates of its upper left corner. These coordinates, sometimes called window coordinates, are always relative to the upper left corner of the screen or, for a child window, the upper left corner of the parent window's client area. For example, a top-level window having the coordinates (10,10) is placed 10 pixels to the right of the upper left corner of the screen and 10 pixels down from it. A child window having the coordinates (10,10) is placed 10 pixels to the right of the upper left corner of its parent window's client area and 10 pixels down from it.

The WindowFromPoint function retrieves a handle to the window occupying a particular point on the screen. Similarly, the ChildWindowFromPoint and ChildWindowFromPointEx functions retrieve a handle to the child window occupying a particular point in the parent window's client area. Although ChildWindowFromPointEx can ignore invisible, disabled, and transparent child windows, ChildWindowFromPoint cannot.


Default Size and Position

An application can allow the system to calculate the initial size or position of a top-level window by specifying CW_USEDEFAULT in CreateWindowEx. If the application sets the window's coordinates to CW_USEDEFAULT and has created no other top-level windows, the system sets the new window's position relative to the upper left corner of the screen; otherwise, it sets the position relative to the position of the top-level window that the application created most recently. If the width and height parameters are set to CW_USEDEFAULT, the system calculates the size of the new window. If the application has created other top-level windows, the system bases the size of the new window on the size of the application's most recently created top-level window. Specifying CW_USEDEFAULT when creating a child or pop-up window causes the system to set the window's size to the default minimum window size.


Tracking Size

The system maintains a minimum and maximum tracking size for a window of the WS_THICKFRAME style; a window with this style has a sizing border. The minimum tracking size is the smallest window size you can produce by dragging the window's sizing border. Similarly, the maximum tracking size is the largest window size you can produce by dragging the sizing border.

A window's minimum and maximum tracking sizes are set to system-defined default values when the system creates the window. An application can discover the defaults and override them by processing the WM_GETMINMAXINFO message. For more information, see Size and Position Messages.


System Commands

An application that has a window menu can change the size and position of that window by sending system commands. System commands are generated when the user chooses commands from the window menu. An application can emulate the user action by sending a WM_SYSCOMMAND message to the window. The following system commands affect the size and position of a window.

Command | Description
SC_CLOSE | Closes the window. This command sends a WM_CLOSE message to the window. The window carries out any steps needed to clean up and destroy itself.
SC_MAXIMIZE | Maximizes the window.
SC_MINIMIZE | Minimizes the window.
SC_MOVE | Moves the window.
SC_RESTORE | Restores a minimized or maximized window to its previous size and position.
SC_SIZE | Starts a size command. To change the size of the window, use the mouse or keyboard.


Size and Position Functions

After creating a window, an application can set the window's size or position by calling one of several different functions, including SetWindowPlacement, MoveWindow, SetWindowPos, and DeferWindowPos. SetWindowPlacement sets a window's minimized position, maximized position, restored size and position, and show state. The MoveWindow and SetWindowPos functions are similar; both set the size or position of a single application window. The SetWindowPos function includes a set of flags that affect the window's show state; MoveWindow does not include these flags. Use the BeginDeferWindowPos, DeferWindowPos, and EndDeferWindowPos functions to simultaneously set the position of a number of windows, including the size, position, position in the Z order, and show state.

An application can retrieve the coordinates of a window's bounding rectangle by using the GetWindowRect function. GetWindowRect fills a RECT structure with the coordinates of the window's upper left and lower right corners. The coordinates are relative to the upper left corner of the screen, even for a child window. The ScreenToClient or MapWindowPoints function maps the screen coordinates of a child window's bounding rectangle to coordinates relative to the parent window's client area.

The GetClientRect function retrieves the coordinates of a window's client area. GetClientRect fills a RECT structure with the coordinates of the upper left and lower right corners of the client area, but the coordinates are relative to the client area itself. This means the coordinates of a client area's upper left corner are always (0,0), and the coordinates of the lower right corner are the width and height of the client area.

The CascadeWindows function cascades the windows on the desktop or cascades the child windows of the specified parent window. The TileWindows function tiles the windows on the desktop or tiles the child windows of the specified parent window.


Size and Position Messages

The system sends the WM_GETMINMAXINFO message to a window whose size or position is about to change. For example, the message is sent when the user clicks Move or Size from the window menu or clicks the sizing border or title bar; the message is also sent when an application calls SetWindowPos to move or size the window. WM_GETMINMAXINFO includes a pointer to a MINMAXINFO structure containing the default maximized size and position for the window, as well as the default minimum and maximum tracking sizes. An application can override the defaults by processing WM_GETMINMAXINFO and setting the appropriate members of MINMAXINFO. A window must have the WS_THICKFRAME or WS_CAPTION style to receive WM_GETMINMAXINFO. A window with the WS_THICKFRAME style receives this message during the window-creation process, as well as when it is being moved or sized.

The system sends the WM_WINDOWPOSCHANGING message to a window whose size, position, position in the Z order, or show state is about to change. This message includes a pointer to a WINDOWPOS structure that specifies the window's new size, position, position in the Z order, and show state. By setting the members of WINDOWPOS, an application can affect the window's new size, position, and appearance.

After changing a window's size, position, position in the Z order, or show state, the system sends the WM_WINDOWPOSCHANGED message to the window. This message includes a pointer to WINDOWPOS that informs the window of its new size, position, position in the Z order, and show state. Setting the members of the WINDOWPOS structure that is passed with WM_WINDOWPOSCHANGED has no effect on the window. A window that must process WM_SIZE and WM_MOVE messages must pass WM_WINDOWPOSCHANGED to the DefWindowProc function; otherwise, the system does not send WM_SIZE and WM_MOVE messages to the window.

The system sends the WM_NCCALCSIZE message to a window when the window is created or sized. The system uses the message to calculate the size of a window's client area and the position of the client area relative to the upper left corner of the window. A window typically passes this message to the default window procedure; however, this message can be useful in applications that customize a window's nonclient area or preserve portions of the client area when the window is sized. For more information, see Painting and Drawing.


Window Animation

Windows NT 5.0 or later

You can produce special effects when showing or hiding windows by using the AnimateWindow function. When the window is animated in this manner, the system will either roll or slide the window, depending on the flags you specify in a call to AnimateWindow.

By default, the system uses roll animation. With this effect, the window appears to roll open (showing the window) or roll closed (hiding the window). You can use the dwFlags parameter to specify whether the window rolls horizontally, vertically, or diagonally.

When you specify the AW_SLIDE flag, the system uses slide animation. With this effect, the window appears to slide into view (showing the window) or slide out of view (hiding the window). You can use the dwFlags parameter to specify whether the window slides horizontally, vertically, or diagonally.

You can also use the AW_CENTER flag to make a window appear to collapse inward or expand outward.


Window Destruction

In general, an application must destroy all the windows it creates. It does this by using the DestroyWindow function. When a window is destroyed, the system hides the window, if it is visible, and then removes any internal data associated with the window. This invalidates the window handle, which can no longer be used by the application.

An application destroys many of the windows it creates soon after creating them. For example, an application usually destroys a dialog box window as soon as the application has sufficient input from the user to continue its task. An application eventually destroys the main window of the application (before terminating).

Before destroying a window, an application should save or remove any data associated with the window, and it should release any system resources allocated for the window. If the application does not release the resources, the system will free any resources not freed by the application.

Destroying a window does not affect the window class from which the window is created. New windows can still be created using that class, and any existing windows of that class continue to operate. Destroying a window also destroys the window's descendant windows. The DestroyWindow function sends a WM_DESTROY message first to the window, then to its child windows and descendant windows. In this way, all descendant windows of the window being destroyed are also destroyed.

A window with a window menu receives a WM_CLOSE message when the user clicks Close. By processing this message, an application can prompt the user for confirmation before destroying the window. If the user confirms that the window should be destroyed, the application can call the DestroyWindow function to destroy the window.

If the window being destroyed is the active window, both the active and focus states are transferred to another window. The window that becomes the active window is the next window, as determined by the alt+esc key combination. The new active window then determines which window receives the keyboard focus.


Using Windows

The examples in this section describe how to perform the following tasks:

  • Creating a main window.
  • Creating, enumerating, and sizing child windows.
  • Destroying a window.


Creating a Main Window

The first window an application creates is typically the main window. You create the main window by using the CreateWindowEx function, specifying the window class, window name, window styles, size, position, menu handle, instance handle, and creation data. A main window belongs to an application-defined window class, so you must register the window class and provide a window procedure for the class before creating the main window.

Most applications typically use the WS_OVERLAPPEDWINDOW style to create the main window. This style gives the window a title bar, a window menu, a sizing border, and minimize and maximize buttons. The CreateWindowEx function returns a handle that uniquely identifies the window.

The following example creates a main window belonging to an application-defined window class. The window name, Main Window, will appear in the window's title bar. By combining the WS_VSCROLL and WS_HSCROLL styles with the WS_OVERLAPPEDWINDOW style, the application creates a main window with horizontal and vertical scroll bars in addition to the components provided by the WS_OVERLAPPEDWINDOW style. The four occurrences of the CW_USEDEFAULT constant set the initial size and position of the window to the system-defined default values. By specifying NULL instead of a menu handle, the window will have the menu defined for the window class.

HINSTANCE hinst;
HWND hwndMain;

// Create the main window.

hwndMain = CreateWindowEx(
    0,                      // no extended styles
    "MainWClass",           // class name
    "Main Window",          // window name
    WS_OVERLAPPEDWINDOW |   // overlapped window
        WS_HSCROLL |        // horizontal scroll bar
        WS_VSCROLL,         // vertical scroll bar
    CW_USEDEFAULT,          // default horizontal position
    CW_USEDEFAULT,          // default vertical position
    CW_USEDEFAULT,          // default width
    CW_USEDEFAULT,          // default height
    (HWND) NULL,            // no parent or owner window
    (HMENU) NULL,           // class menu used
    hinstance,              // instance handle
    NULL);                  // no window creation data

if (!hwndMain)
    return FALSE;

// Show the window using the flag specified by the program
// that started the application, and send the application
// a WM_PAINT message.

ShowWindow(hwndMain, SW_SHOWDEFAULT);
UpdateWindow(hwndMain);

Notice that the preceding example calls the ShowWindow function after creating the main window. This is done because the system does not automatically display the main window after creating it. By passing the SW_SHOWDEFAULT flag to ShowWindow, the application allows the program that started the application to set the initial show state of the main window. The UpdateWindow function sends the window its first WM_PAINT message.


Creating, Enumerating, and Sizing Child Windows

You can divide a window's client area into different functional areas by using child windows. Creating a child window is like creating a main window — you use the CreateWindowEx function. To create a window of an application-defined window class, you must register the window class and provide a window procedure before creating the child window. You must give the child window the WS_CHILD style and specify a parent window for the child window when you create it.

The following example divides the client area of an application's main window into three functional areas by creating three child windows of equal size. Each child window is the same height as the main window's client area, but each is one-third its width. The main window creates the child windows in response to the WM_CREATE message, which the main window receives during its own window-creation process. Because each child window has the WS_BORDER style, each has a thin line border. Also, because the WS_VISIBLE style is not specified, each child window is initially hidden. Notice also that each child window is assigned a child-window identifier.

The main window sizes and positions the child windows in response to the WM_SIZE message, which the main window receives when its size changes. In response to WM_SIZE, the main window retrieves the dimensions of its client area by using the GetWindowRect function and then passes the dimensions to the EnumChildWindows function. EnumChildWindows passes the handle to each child window, in turn, to the application-defined EnumChildProc callback function. This function sizes and positions each child window by calling the MoveWindow function; the size and position are based on the dimensions of the main window's client area and the identifier of the child window. Afterward, EnumChildProc calls the ShowWindow function to make the window visible.

#define ID_FIRSTCHILD  100
#define ID_SECONDCHILD 101
#define ID_THIRDCHILD  102

LONG APIENTRY MainWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    RECT rcClient;
    int i;

    switch(uMsg)
    {
        case WM_CREATE: // creating main window

            // Create three invisible child windows.

            for (i = 0; i < 3; i++)
            {
                CreateWindowEx(
                    0,
                    "ChildWClass",
                    (LPCTSTR) NULL,
                    WS_CHILD | WS_BORDER,
                    0,0,0,0,
                    hwnd,
                    (HMENU) (int) (ID_FIRSTCHILD + i),
                    hinst,
                    NULL);
            }

            return 0;

        case WM_SIZE:   // main window changed size

            // Get the dimensions of the main window's client
            // area, and enumerate the child windows. Pass the
            // dimensions to the child windows during enumeration.

            GetClientRect(hwnd, &rcClient);
            EnumChildWindows(hwnd, EnumChildProc,
                (LPARAM) &rcClient);
            return 0;
        // Process other messages.

    }
    return DefWindowProc(hwnd, uMsg, wParam, lParam);
}

BOOL CALLBACK EnumChildProc(HWND hwndChild, LPARAM lParam)
{
    LPRECT rcParent;
    int i, idChild;

    // Retrieve the child-window identifier. Use it to set the
    // position of the child window.

    idChild = GetWindowLong(hwndChild, GWL_ID);

    if (idChild == ID_FIRSTCHILD)
        i = 0;
    else if (idChild == ID_SECONDCHILD)
        i = 1;
    else
        i = 2;

    // Size and position the child window.

    rcParent = (LPRECT) lParam;
    MoveWindow(hwndChild,
        (rcParent->right / 3) * i,
        0,
        rcParent->right / 3,
        rcParent->bottom,
        TRUE);

    // Make sure the child window is visible.

    ShowWindow(hwndChild, SW_SHOW);

    return TRUE;
}


Destroying a Window

You can use the DestroyWindow function to destroy a window. Typically, an application sends the WM_CLOSE message before destroying a window, giving the window the opportunity to prompt the user for confirmation before the window is destroyed. A window that includes a window menu automatically receives the WM_CLOSE message when the user clicks Close from the window menu. If the user confirms that the window should be destroyed, the application calls DestroyWindow. The system sends the WM_DESTROY message to the window after removing it from the screen. In response to WM_DESTROY, the window saves its data and frees any resources it allocated. A main window concludes its processing of WM_DESTROY by calling the PostQuitMessage function to quit the application.

The following example shows how to prompt for user confirmation before destroying a window. In response to WM_CLOSE, the example displays a dialog box that contains Yes, OK, and Cancel buttons. If the user clicks Yes, DestroyWindow is called; otherwise, the window is not destroyed. Because the window being destroyed is a main window, the example calls PostQuitMessage in response to WM_DESTROY.

case WM_CLOSE:

    // Create the message box. If the user clicks
    // the Yes button, destroy the main window.

    if (MessageBox(hwnd, szConfirm, szAppName,
            MB_YESNOCANCEL) == IDYES)
        DestroyWindow(hwndMain);
    else
        return 0;

case WM_DESTROY:

    // Post the WM_QUIT message to
    // quit the application terminate.

    PostQuitMessage(0);
    return 0;


Window Reference

The following elements are associated with windows.

  • Window Functions
  • Window Structures
  • Window Messages


Window Functions

The following functions are used to create and manage windows.

AdjustWindowRect
AdjustWindowRectEx
AnimateWindow
ArrangeIconicWindows
BeginDeferWindowPos
BringWindowToTop
CascadeWindows
ChildWindowFromPoint
ChildWindowFromPointEx
CloseWindow
CreateWindow
CreateWindowEx
DeferWindowPos
DestroyWindow
EnableWindow
EndDeferWindowPos
EnumChildProc
EnumChildWindows
EnumThreadWindows
EnumThreadWndProc
EnumWindows
EnumWindowsProc
FindWindow
FindWindowEx
GetClientRect
GetDesktopWindow
GetForegroundWindow
GetLastActivePopup
GetNextWindow
GetParent
GetTopWindow
GetWindow
GetWindowPlacement
GetWindowRect
GetWindowText
GetWindowTextLength
GetWindowThreadProcessId
IsChild
IsIconic
IsWindow
IsWindowUnicode
IsWindowVisible
IsZoomed
MoveWindow
OpenIcon
SetForegroundWindow
SetParent
SetWindowLong
SetWindowPlacement
SetWindowPos
SetWindowText
ShowOwnedPopups
ShowWindow
ShowWindowAsync
TileWindows
WindowFromPoint
WinMain

Obsolete Functions

AnyPopup
EnumTaskWindows
GetSysModalWindow
GetWindowTask
SetSysModalWindow


AdjustWindowRect

The AdjustWindowRect function calculates the required size of the window rectangle, based on the desired client-rectangle size. The window rectangle can then be passed to the CreateWindow function to create a window whose client area is the desired size.

BOOL AdjustWindowRect(
  LPRECT lpRect,  // pointer to client-rectangle structure
  DWORD dwStyle,  // window styles
  BOOL bMenu      // menu-present flag
);

Parameters

lpRect
Pointer to a RECT structure that contains the coordinates of the top-left and bottom-right corners of the desired client area. When the function returns, the structure contains the coordinates of the top-left and bottom-right corners of the window to accommodate the desired client area.
dwStyle
Specifies the window styles of the window whose required size is to be calculated.
bMenu
Specifies whether the window has a menu.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

A client rectangle is the smallest rectangle that completely encloses a client area. A window rectangle is the smallest rectangle that completely encloses the window, which includes the client area and the nonclient area.

The AdjustWindowRect function does not add extra space when a menu bar wraps to two or more rows.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, AdjustWindowRectEx, CreateWindow, RECT


AdjustWindowRectEx

The AdjustWindowRectEx function calculates the required size of the window rectangle, based on the desired size of the client rectangle. The window rectangle can then be passed to the CreateWindowEx function to create a window whose client area is the desired size.

BOOL AdjustWindowRectEx(
  LPRECT lpRect,    // pointer to client-rectangle structure
  DWORD dwStyle,    // window styles
  BOOL bMenu,       // menu-present flag
  DWORD dwExStyle   // extended style
);

Parameters

lpRect
Pointer to a RECT structure that contains the coordinates of the top-left and bottom-right corners of the desired client area. When the function returns, the structure contains the coordinates of the top-left and bottom-right corners of the window to accommodate the desired client area.
dwStyle
Specifies the window styles of the window whose required size is to be calculated.
bMenu
Specifies whether the window has a menu.
dwExStyle
Specifies the extended style of the window whose required size is to be calculated.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

A client rectangle is the smallest rectangle that completely encloses a client area. A window rectangle is the smallest rectangle that completely encloses the window, which includes the client area and the nonclient area.

The AdjustWindowRectEx function does not add extra space when a menu bar wraps to two or more rows.

Windows CE: The bMenu parameter must be FALSE; menu bars are not supported.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, AdjustWindowRect, CreateWindowEx, RECT


AnimateWindow

[This is preliminary documentation and subject to change.]

The AnimateWindow function enables you to produce special effects when showing or hiding windows. There are two types of animation: roll animation and slide animation.

BOOL AnimateWindow(
  HWND hwnd,     // handle to the window to animate
  DWORD dwTime,  // duration of animation
  DWORD dwFlags  // animation type
);

Parameters

hwnd
Specifies a handle to the window to animate.
dwTime
Specifies how long it takes to play the animation, in milliseconds. Typically, an animation takes 200 milliseconds to play.
dwFlags
Specifies the type of animation. This parameter can be one or more of the following flags.
Flag | Description
AW_SLIDE | Uses slide animation. By default, roll animation is used. This flag is ignored when used with the AW_CENTER flag.
AW_ACTIVATE | Activates the window. Do not use this flag with AW_HIDE.
AW_BLEND | Uses a fade effect. This flag can be used only if hwnd is a top-level window.
AW_HIDE | Hides the window. By default, the window is shown.
AW_CENTER | Makes the window appear to collapse inward if the AW_HIDE flag is used or expand outward if the AW_HIDE flag is not used.
AW_HOR_POSITIVE | Animate the window from left to right. This flag can be used with roll or slide animation. It is ignored when used with the AW_CENTER flag.
AW_HOR_NEGATIVE | Animate the window from right to left. This flag can be used with roll or slide animation. It is ignored when used with the AW_CENTER flag.
AW_VER_POSITIVE | Animate the window from top to bottom. This flag can be used with roll or slide animation. It is ignored when used with the AW_CENTER flag.
AW_VER_NEGATIVE | Animate the window from bottom to top. This flag can be used with roll or slide animation. It is ignored when used with the AW_CENTER flag.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. The function will fail in the following situations:

  • The window uses the window region.
  • The window is already visible and you are trying to show the window.
  • The window is already hidden and you are trying to hide the window.

To get extended error information, call the GetLastError function.

Remarks

You can combine the AW_HOR_POSITIVE or AW_HOR_NEGATIVE flag with the AW_VER_POSITIVE or AW_VER_NEGATIVE flag to animate a window diagonally.

The window procedures for the window and its child windows may need to handle any WM_PRINT or WM_PRINTCLIENT messages. Dialog boxes, controls, and common controls already handle WM_PRINTCLIENT. The default window procedure already handles WM_PRINT.

QuickInfo

Windows NT: Requires version 5.0 or later.
Windows: Requires Windows 98 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, WM_PRINT, WM_PRINTCLIENT


AnyPopup

The AnyPopup function indicates whether an owned, visible, top-level pop-up, or overlapped window exists on the screen. The function searches the entire screen, not just the calling application's client area.

AnyPopup is a obsolete and is retained for compatibility with older versions of 16-bit Windows. It is generally not useful.

BOOL AnyPopup(VOID)

Parameters

This function has no parameters.

Return Values

If a pop-up window exists, the return value is nonzero, even if the pop-up window is completely covered by other windows.

If a pop-up window does not exist, the return value is zero.

Remarks

This function does not detect unowned pop-up windows or windows that do not have the WS_VISIBLE style bit set.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, GetLastActivePopup, ShowOwnedPopups


ArrangeIconicWindows

The ArrangeIconicWindows function arranges all the minimized (iconic) child windows of the specified parent window.

UINT ArrangeIconicWindows(
  HWND hWnd   // handle to parent window
);

Parameters

hWnd
Handle to the parent window.

Return Values

If the function succeeds, the return value is the height of one row of icons.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

An application that maintains its own minimized child windows can use the ArrangeIconicWindows function to arrange icons in a parent window. This function can also arrange icons on the desktop. To retrieve the window handle to the desktop window, use the GetDesktopWindow function.

An application sends the WM_MDIICONARRANGE message to the multiple document interface (MDI) client window to prompt the client window to arrange its minimized MDI child windows.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, CloseWindow, GetDesktopWindow


BeginDeferWindowPos

The BeginDeferWindowPos function allocates memory for a multiple-window – position structure and returns the handle to the structure.

HDWP BeginDeferWindowPos(
  int nNumWindows   // number of windows
);

Parameters

nNumWindows
Specifies the initial number of windows for which to store position information. The DeferWindowPos function increases the size of the structure, if necessary.

Return Values

If the function succeeds, the return value identifies the multiple-window – position structure. If insufficient system resources are available to allocate the structure, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The multiple-window – position structure is an internal structure; an application cannot access it directly.

DeferWindowPos fills the multiple-window – position structure with information about the target position for one or more windows about to be moved. The EndDeferWindowPos function accepts the handle to this structure and repositions the windows by using the information stored in the structure.

If any of the windows in the multiple-window – position structure have the SWP_HIDEWINDOW or SWP_SHOWWINDOW flag set, none of the windows are repositioned.

If the system must increase the size of the multiple-window – position structure beyond the initial size specified by the nNumWindows parameter but cannot allocate enough memory to do so, the system fails the entire window positioning sequence (BeginDeferWindowPos, DeferWindowPos, and EndDeferWindowPos). By specifying the maximum size needed, an application can detect and process failure early in the process.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, DeferWindowPos, EndDeferWindowPos, SetWindowPos


BringWindowToTop

The BringWindowToTop function brings the specified window to the top of the Z order. If the window is a top-level window, it is activated. If the window is a child window, the top-level parent window associated with the child window is activated.

BOOL BringWindowToTop(
  HWND hWnd   // handle to window
);

Parameters

hWnd
Handle to the window to bring to the top of the Z order.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Use the BringWindowToTop function to uncover any window that is partially or completely obscured by other windows.

Calling this function is similar to calling the SetWindowPos function to change a window's position in the Z order. BringWindowToTop does not make a window a top-level window.

If an application is not in the foreground and wants to be in the foreground, it should call the SetForegroundWindow function.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, SetWindowPos, SetActiveWindow, SetForegroundWindow


CascadeWindows

The CascadeWindows function cascades the specified child windows of the specified parent window.

WORD WINAPI CascadeWindows(
  HWND hwndParent,        // handle to parent window
  UINT wHow,              // types of windows not to arrange
  CONST RECT *lpRect,     // rectangle to arrange windows in
  UINT cKids,             // number of windows to arrange
  const HWND FAR *lpKids  // array of window handles
);

Parameters

hwndParent
Handle to the parent window. If this parameter is NULL, the desktop window is assumed.
wHow
Specifies a cascade flag. The only flag currently available, MDITILE_SKIPDISABLED, prevents disabled MDI child windows from being cascaded.
lpRect
Pointer to a RECT structure that specifies the rectangular area, in client coordinates, within which the windows are arranged. This parameter can be NULL, in which case the client area of the parent window is used.
cKids
Specifies the number of elements in the array specified by the lpKids parameter. This parameter is ignored if lpKids is NULL.
lpKids
Pointer to an array of handles to the child windows to arrange. If this parameter is NULL, all child windows of the specified parent window (or of the desktop window) are arranged.

Return Values

If the function succeeds, the return value is the number of windows arranged.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Calling CascadeWindows causes all maximized windows to be restored to their previous size.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, RECT


ChildWindowFromPoint

The ChildWindowFromPoint function determines which, if any, of the child windows belonging to a parent window contains the specified point.

HWND ChildWindowFromPoint(
  HWND hWndParent,  // handle to parent window
  POINT Point       // structure with point coordinates
);

Parameters

hWndParent
Handle to the parent window.
Point
Specifies a POINT structure that defines the client coordinates of the point to be checked.

Return Values

The return value is a handle to the child window that contains the point, even if the child window is hidden or disabled. If the point lies outside the parent window, the return value is NULL. If the point is within the parent window but not within any child window, the return value is a handle to the parent window.

Remarks

The system maintains an internal list, containing the handles of the child windows associated with a parent window. The order of the handles in the list depends on the Z order of the child windows. If more than one child window contains the specified point, the system returns a handle to the first window in the list that contains the point.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, ChildWindowFromPointEx, POINT, WindowFromPoint


ChildWindowFromPointEx

The ChildWindowFromPointEx function determines which, if any, of the child windows belonging to the specified parent window contains the specified point. The function can ignore invisible, disabled, and transparent child windows.

HWND ChildWindowFromPointEx(
  HWND hwndParent,   // handle to parent window
  POINT pt,          // structure with point coordinates
  UINT uFlags        // skipping flags
);

Parameters

hwndParent
Handle to the parent window.
pt
Specifies a POINT structure that defines the client coordinates of the point to be checked.
uFlags
Specifies which child windows to skip. This parameter can be a combination of the following values:
Value | Meaning
CWP_ALL | Do not skip any child windows
CWP_SKIPINVISIBLE | Skip invisible child windows
CWP_SKIPDISABLED | Skip disabled child windows
CWP_SKIPTRANSPARENT | Skip transparent child windows

Return Values

The return value is a handle to the first child window that contains the point and meets the criteria specified by uFlags. If the point is within the parent window but not within any child window that meets the criteria, the return value is a handle to the parent window. If the point lies outside the parent window or if the function fails, the return value is NULL.

Remarks

The system maintains an internal list that contains the handles of the child windows associated with a parent window. The order of the handles in the list depends on the Z order of the child windows. If more than one child window contains the specified point, the system returns a handle to the first window in the list that contains the point and meets the criteria specified by uFlags.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, ChildWindowFromPoint, POINT, WindowFromPoint


CloseWindow

The CloseWindow function minimizes (but does not destroy) the specified window.

BOOL CloseWindow(
  HWND hWnd   // handle to window to minimize
);

Parameters

hWnd
Handle to the window to be minimized.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The window is minimized by reducing it to the size of an icon and moving the window to the icon area of the screen. The system displays the window's icon instead of the window and draws the window's title below the icon.

To destroy a window, an application must use the DestroyWindow function.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, ArrangeIconicWindows, DestroyWindow, IsIconic, OpenIcon


CreateWindow

The CreateWindow function creates an overlapped, pop-up, or child window. It specifies the window class, window title, window style, and (optionally) the initial position and size of the window. The function also specifies the window's parent or owner, if any, and the window's menu.

To use extended styles in addition to the styles supported by CreateWindow, use the CreateWindowEx function instead of using CreateWindow.

HWND CreateWindow(
  LPCTSTR lpClassName,  // pointer to registered class name
  LPCTSTR lpWindowName, // pointer to window name
  DWORD dwStyle,        // window style
  int x,                // horizontal position of window
  int y,                // vertical position of window
  int nWidth,           // window width
  int nHeight,          // window height
  HWND hWndParent,      // handle to parent or owner window
  HMENU hMenu,          // handle to menu or child-window identifier
  HANDLE hInstance,     // handle to application instance
  LPVOID lpParam        // pointer to window-creation data
);

Parameters

lpClassName
Pointer to a null-terminated string or is an integer atom. If this parameter is an atom, it must be a global atom created by a previous call to the GlobalAddAtom function. The atom, a 16-bit value less than 0xC000, must be in the low-order word of lpClassName; the high-order word must be zero.

If lpClassName is a string, it specifies the window class name. The class name can be any name registered with the RegisterClassEx function or any of the predefined control-class names. For a complete list, see the Remarks section.

lpWindowName
Pointer to a null-terminated string that specifies the window name.

If the window style specifies a title bar, the window title pointed to by lpWindowName is displayed in the title bar. When using CreateWindow to create controls, such as buttons, check boxes, and static controls, use lpWindowName to specify the text of the control.

dwStyle
Specifies the style of the window being created. This parameter can be a combination of the following window styles, plus the control styles indicated in the Remarks section.
Style | Meaning
WS_BORDER | Creates a window that has a thin-line border.
WS_CAPTION | Creates a window that has a title bar (includes the WS_BORDER style).
WS_CHILD | Creates a child window. This style cannot be used with the WS_POPUP style.
WS_CHILDWINDOW | Same as the WS_CHILD style.
WS_CLIPCHILDREN | Excludes the area occupied by child windows when drawing occurs within the parent window. This style is used when creating the parent window.
WS_CLIPSIBLINGS | Clips child windows relative to each other; that is, when a particular child window receives a WM_PAINT message, the WS_CLIPSIBLINGS style clips all other overlapping child windows out of the region of the child window to be updated. If WS_CLIPSIBLINGS is not specified and child windows overlap, it is possible, when drawing within the client area of a child window, to draw within the client area of a neighboring child window.
WS_DISABLED | Creates a window that is initially disabled. A disabled window cannot receive input from the user.
WS_DLGFRAME | Creates a window that has a border of a style typically used with dialog boxes. A window with this style cannot have a title bar.
WS_GROUP | Specifies the first control of a group of controls. The group consists of this first control and all controls defined after it, up to the next control with the WS_GROUP style. The first control in each group usually has the WS_TABSTOP style so that the user can move from group to group. The user can subsequently change the keyboard focus from one control in the group to the next control in the group by using the direction keys.
WS_HSCROLL | Creates a window that has a horizontal scroll bar.
WS_ICONIC | Creates a window that is initially minimized. Same as the WS_MINIMIZE style.
WS_MAXIMIZE | Creates a window that is initially maximized.
WS_MAXIMIZEBOX | Creates a window that has a Maximize button. Cannot be combined with the WS_EX_CONTEXTHELP style. The WS_SYSMENU style must also be specified.
WS_MINIMIZE | Creates a window that is initially minimized. Same as the WS_ICONIC style.
WS_MINIMIZEBOX | Creates a window that has a Minimize button. Cannot be combined with the WS_EX_CONTEXTHELP style. The WS_SYSMENU style must also be specified.
WS_OVERLAPPED | Creates an overlapped window. An overlapped window has a title bar and a border. Same as the WS_TILED style.
WS_OVERLAPPEDWINDOW | Creates an overlapped window with the WS_OVERLAPPED, WS_CAPTION, WS_SYSMENU, WS_THICKFRAME, WS_MINIMIZEBOX, and WS_MAXIMIZEBOX styles. Same as the WS_TILEDWINDOW style.
WS_POPUP | Creates a pop-up window. This style cannot be used with the WS_CHILD style.
WS_POPUPWINDOW | Creates a pop-up window with WS_BORDER, WS_POPUP, and WS_SYSMENU styles. The WS_CAPTION and WS_POPUPWINDOW styles must be combined to make the window menu visible.
WS_SIZEBOX | Creates a window that has a sizing border. Same as the WS_THICKFRAME style.
WS_SYSMENU | Creates a window that has a window-menu on its title bar. The WS_CAPTION style must also be specified.
WS_TABSTOP | Specifies a control that can receive the keyboard focus when the user presses the tab key. Pressing the tab key changes the keyboard focus to the next control with the WS_TABSTOP style.
WS_THICKFRAME | Creates a window that has a sizing border. Same as the WS_SIZEBOX style.
WS_TILED | Creates an overlapped window. An overlapped window has a title bar and a border. Same as the WS_OVERLAPPED style.
WS_TILEDWINDOW | Creates an overlapped window with the WS_OVERLAPPED, WS_CAPTION, WS_SYSMENU, WS_THICKFRAME, WS_MINIMIZEBOX, and WS_MAXIMIZEBOX styles. Same as the WS_OVERLAPPEDWINDOW style.
WS_VISIBLE | Creates a window that is initially visible.
WS_VSCROLL | Creates a window that has a vertical scroll bar.

x
Specifies the initial horizontal position of the window. For an overlapped or pop-up window, the x parameter is the initial x-coordinate of the window's upper-left corner, in screen coordinates. For a child window, x is the x-coordinate of the upper-left corner of the window relative to the upper-left corner of the parent window's client area.

If this parameter is set to CW_USEDEFAULT, the system selects the default position for the window's upper-left corner and ignores the y parameter. CW_USEDEFAULT is valid only for overlapped windows; if it is specified for a pop-up or child window, the x and y parameters are set to zero.

y
Specifies the initial vertical position of the window. For an overlapped or pop-up window, the y parameter is the initial y-coordinate of the window's upper-left corner, in screen coordinates. For a child window, y is the initial y-coordinate of the upper-left corner of the child window relative to the upper-left corner of the parent window's client area. For a list box, y is the initial y-coordinate of the upper-left corner of the list box's client area relative to the upper-left corner of the parent window's client area.

If an overlapped window is created with the WS_VISIBLE style bit set and the x parameter is set to CW_USEDEFAULT, the system ignores the y parameter.

nWidth
Specifies the width, in device units, of the window. For overlapped windows, nWidth is either the window's width, in screen coordinates, or CW_USEDEFAULT. If nWidth is CW_USEDEFAULT, the system selects a default width and height for the window; the default width extends from the initial x-coordinate to the right edge of the screen, and the default height extends from the initial y-coordinate to the top of the icon area. CW_USEDEFAULT is valid only for overlapped windows; if CW_USEDEFAULT is specified for a pop-up or child window, nWidth and nHeight are set to zero.
nHeight
Specifies the height, in device units, of the window. For overlapped windows, nHeight is the window's height, in screen coordinates. If nWidth is set to CW_USEDEFAULT, the system ignores nHeight.
hWndParent
Handle to the parent or owner window of the window being created. To create a child window or an owned window, supply a valid window handle. This parameter is optional for pop-up windows.

Windows NT 5.0 and later: To create a message-only window, supply HWND_MESSAGE or a handle to an existing message-only window.

hMenu
Handle to a menu, or specifies a child-window identifier depending on the window style. For an overlapped or pop-up window, hMenu identifies the menu to be used with the window; it can be NULL if the class menu is to be used. For a child window, hMenu specifies the child-window identifier, an integer value used by a dialog box control to notify its parent about events. The application determines the child-window identifier; it must be unique for all child windows with the same parent window.
hInstance
Handle to the instance of the module to be associated with the window.
lpParam
A pointer to a value to be passed to the window through the CREATESTRUCT structure passed in the lParam parameter the WM_CREATE message. If an application calls CreateWindow to create a multiple document interface (MDI) client window, lpParam must point to a CLIENTCREATESTRUCT structure.

Return Values

If the function succeeds, the return value is a handle to the new window.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

Before returning, CreateWindow sends a WM_CREATE message to the window procedure. For overlapped, pop-up, and child windows, CreateWindow sends WM_CREATE, WM_GETMINMAXINFO, and WM_NCCREATE messages to the window. The lParam parameter of the WM_CREATE message contains a pointer to a CREATESTRUCT structure. If the WS_VISIBLE style is specified, CreateWindow sends the window all the messages required to activate and show the window.

For information on controlling whether the Taskbar displays a button for the created window, see Visibility of Taskbar Buttons.

The following predefined control classes can be specified in the lpClassName parameter. Note the corresponding control styles you can use in the dwStyle parameter.

Class | Meaning
BUTTON | Designates a small rectangular child window that represents a button the user can click to turn it on or off. Button controls can be used alone or in groups, and they can either be labeled or appear without text. Button controls typically change appearance when the user clicks them. For more information, see Buttons.
 | For a table of the button styles you can specify in the dwStyle parameter, see Button Styles.
COMBOBOX | Designates a control consisting of a list box and a selection field similar to an edit control. When using this style, an application should either display the list box at all times or enable a drop-down list box. If the list box is visible, typing characters into the selection field highlights the first list box entry that matches the characters typed. Conversely, selecting an item in the list box displays the selected text in the selection field. For more information, see Combo Boxes.
 | For a table of the combo box styles you can specify in the dwStyle parameter, see Combo Box Styles.
EDIT | Designates a rectangular child window into which the user can type text from the keyboard. The user selects the control and gives it the keyboard focus by clicking it or moving to it by pressing the tab key. The user can type text when the edit control displays a flashing caret; use the mouse to move the cursor, select characters to be replaced, or position the cursor for inserting characters; or use the backspace key to delete characters. For more information, see Edit Controls.
 | For a table of the edit control styles you can specify in the dwStyle parameter, see Edit Control Styles.
LISTBOX | Designates a list of character strings. Specify this control whenever an application must present a list of names, such as filenames, from which the user can choose. The user can select a string by clicking it. A selected string is highlighted, and a notification message is passed to the parent window. For more information, see List Boxes.
 | For a table of the list box styles you can specify in the dwStyle parameter, see List Box Styles.
MDICLIENT | Designates an MDI client window. This window receives messages that control the MDI application's child windows. The recommended style bits are WS_CLIPCHILDREN and WS_CHILD. Specify the WS_HSCROLL and WS_VSCROLL styles to create an MDI client window that allows the user to scroll MDI child windows into view. For more information, see Multiple Document Interface.
RichEdit | Designates a Rich Edit version 1.0 control. This window lets the user view and edit text with character and paragraph formatting, and can include embedded COM objects. For more information, see Rich Edit Controls.
 | For a table of the rich edit control styles you can specify in the dwStyle parameter, see Rich Edit Control Styles.
RICHEDIT_CLASS | Designates a Rich Edit version 2.0 control. This controls let the user view and edit text with character and paragraph formatting, and can include embedded COM objects. For more information, see Rich Edit Controls.
 | For a table of the rich edit control styles you can specify in the dwStyle parameter, see Rich Edit Control Styles.
SCROLLBAR | Designates a rectangle that contains a scroll box and has direction arrows at both ends. The scroll bar sends a notification message to its parent window whenever the user clicks the control. The parent window is responsible for updating the position of the scroll box, if necessary. For more information, see Scroll Bars.
 | For a table of the scroll bar control styles you can specify in the dwStyle parameter, see Scroll Bar Control Styles.
STATIC | Designates a simple text field, box, or rectangle used to label, box, or separate other controls. Static controls take no input and provide no output. For more information, see Static Controls.
 | For a table of the static control styles you can specify in the dwStyle parameter, see Static Control Styles.

Windows 95: The system can support a maximum of 16,364 window handles.

Note If you specify Windows version 4.x when linking your application, its windows cannot have caption buttons unless they also have window menus. This is not a requirement if you specify Windows version 3.x when linking your application.

Windows CE: CreateWindow is implemented as a macro. It is defined as CreateWindowEx, but with the dwExStyle parameter set to 0L.

Menu bars are not supported. The hMenu parameter must be NULL, unless it is used as a child-window identifier.

The MDICLIENT window class is not supported.

The dwStyle parameter can be a combination of the window styles and control styles documented in:

Dialog Boxes

Windows

Controls

The following dwStyle flags are not supported for windows:

WS_CHILDWINDOW | WS_ICONIC
WS_MAXIMIZE | WS_MAXIMIZEBOX
WS_MINIMIZE | WS_MINIMIZEBOX
WS_OVERLAPPEDWINDOW | WS_POPUPWINDOW
WS_SIZEBOX | WS_THICKFRAME
WS_TILED | WS_TILEDWINDOW

The following dwStyle flags are not supported for controls and dialog boxes:

Unsupported button styles | Unsupported static control styles
BS_LEFTTEXT | SS_BLACKFRAME
BS_MULTILINE | SS_GRAYFRAME
BS_TEXT | SS_METAPICT
BS_USERBUTTON | SS_SIMPLE
Unsupported combo box styles | SS_WHITERECT
CBS_OWNERDRAWFIXED | SS_BLACKRECT
CBS_OWNERDRAWVARIABLE | SS_GRAYRECT
CBS_SIMPLE | SS_RIGHTIMAGE
Unsupported list box control styles | SS_WHITEFRAME
LBS_NODATA | Unsupported dialog box styles
LBS_OWNERDRAWFIXED | DS_ABSALIGN
LBS_OWNERDRAWVARIABLE | DS_CENTERMOUSE
LBS_STANDARD | DS_CONTEXTHELP
Unsupported scroll bar styles | DS_FIXEDSYS
SBS_BOTTOMALIGN | DS_NOFAILCREATE
SBS_RIGHTALIGN | DS_NOIDLEMSG
SBS_SIZEBOXBOTTOMRIGHTALIGN | DS_SYSMODAL
SBS_SIZEGRIP |

You can use the BS_OWNERDRAW style as a substitute for the BS_USERBUTTON style.

You can use the SS_LEFT or SS_LEFTNOWORDWRAP style instead of the SS_SIMPLE style for static controls..

The MDICLIENT window class is not supported.

All windows implicitly have the WS_CLIPSIBLINGS and WS_CLIPCHILDREN styles.

Windows CE 1.0 does not support owned windows, except for dialog boxes. If the hwndParent parameter is not NULL, the window is implicitly given the WS_CHILD style.

Windows CE version 1.0 does not support menu bars.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Windows Overview, Window Functions, CLIENTCREATESTRUCT, CREATESTRUCT, CreateWindowEx, GlobalAddAtom, RegisterClassEx, WM_COMMAND, WM_CREATE, WM_GETMINMAXINFO, WM_NCCREATE, WM_PAINT


CreateWindowEx

The CreateWindowEx function creates an overlapped, pop-up, or child window with an extended style; otherwise, this function is identical to the CreateWindow function. For more information about creating a window and for full descriptions of the other parameters of CreateWindowEx, see CreateWindow.

HWND CreateWindowEx(
  DWORD dwExStyle,      // extended window style
  LPCTSTR lpClassName,  // pointer to registered class name
  LPCTSTR lpWindowName, // pointer to window name
  DWORD dwStyle,        // window style
  int x,                // horizontal position of window
  int y,                // vertical position of window
  int nWidth,           // window width
  int nHeight,          // window height
  HWND hWndParent,      // handle to parent or owner window
  HMENU hMenu,          // handle to menu, or child-window identifier
  HINSTANCE hInstance,  // handle to application instance
  LPVOID lpParam        // pointer to window-creation data
);

Parameters

dwExStyle
Specifies the extended style of the window. This parameter can be one of the following values:
Style | Meaning
WS_EX_ACCEPTFILES | Specifies that a window created with this style accepts drag-drop files.
WS_EX_APPWINDOW | Forces a top-level window onto the taskbar when the window is visible.
WS_EX_CLIENTEDGE | Specifies that a window has a border with a sunken edge.
WS_EX_CONTEXTHELP Includes a question mark in the title bar of the window. When the user clicks the question mark, the cursor changes to a question mark with a pointer. If the user then clicks a child window, the child receives a WM_HELP message. The child window should pass the message to the parent window procedure, which should call the WinHelp function using the HELP_WM_HELP command. The Help application displays a pop-up window that typically contains help for the child window.

WS_EX_CONTEXTHELP cannot be used with the WS_MAXIMIZEBOX or WS_MINIMIZEBOX styles.
WS_EX_CONTROLPARENT | Allows the user to navigate among the child windows of the window by using the tab key.
WS_EX_DLGMODALFRAME | Creates a window that has a double border; the window can, optionally, be created with a title bar by specifying the WS_CAPTION style in the dwStyle parameter.
WS_EX_LEFT | Window has generic "left-aligned" properties. This is the default.
WS_EX_LEFTSCROLLBAR | If the shell language is Hebrew, Arabic, or another language that supports reading order alignment, the vertical scroll bar (if present) is to the left of the client area. For other languages, the style is ignored and not treated as an error.
WS_EX_LTRREADING | The window text is displayed using Left to Right reading-order properties. This is the default.
WS_EX_MDICHILD | Creates an MDI child window.
WS_EX_NOPARENTNOTIFY | Specifies that a child window created with this style does not send the WM_PARENTNOTIFY message to its parent window when it is created or destroyed.
WS_EX_OVERLAPPEDWINDOW | Combines the WS_EX_CLIENTEDGE and WS_EX_WINDOWEDGE styles.
WS_EX_PALETTEWINDOW | Combines the WS_EX_WINDOWEDGE, WS_EX_TOOLWINDOW, and WS_EX_TOPMOST styles.
WS_EX_RIGHT | The window has generic "right-aligned" properties. This depends on the window class. This style has an effect only if the shell language is Hebrew, Arabic, or another language that supports reading order alignment; otherwise, the style is ignored and not treated as an error.
WS_EX_RIGHTSCROLLBAR | Vertical scroll bar (if present) is to the right of the client area. This is the default.
WS_EX_RTLREADING | If the shell language is Hebrew, Arabic, or another language that supports reading order alignment, the window text is displayed using Right to Left reading-order properties. For other languages, the style is ignored and not treated as an error.
WS_EX_STATICEDGE | Creates a window with a three-dimensional border style intended to be used for items that do not accept user input.
WS_EX_TOOLWINDOW | Creates a tool window; that is, a window intended to be used as a floating toolbar. A tool window has a title bar that is shorter than a normal title bar, and the window title is drawn using a smaller font. A tool window does not appear in the taskbar or in the dialog that appears when the user presses alt+tab. If a tool window has a system menu, its icon is not displayed on the title bar. However, you can display the system menu by right-clicking or by typing alt+space.
WS_EX_TOPMOST | Specifies that a window created with this style should be placed above all non-topmost windows and should stay above them, even when the window is deactivated. To add or remove this style, use the SetWindowPos function.
WS_EX_TRANSPARENT Specifies that a window created with this style should not be painted until siblings beneath the window (that were created by the same thread) have been painted. The window appears transparent because the bits of underlying sibling windows have already been painted.

To achieve transparency without these restrictions, use the SetWindowRgn function.
WS_EX_WINDOWEDGE | Specifies that a window has a border with a raised edge.

Using the WS_EX_RIGHT style for static or edit controls has the same effect as using the SS_RIGHT or ES_RIGHT style, respectively. Using this style with button controls has the same effect as using BS_RIGHT and BS_RIGHTBUTTON styles.

lpClassName
Pointer to a null-terminated string or is an integer atom. If lpClassName is an atom, it must be a global atom created by a previous call to GlobalAddAtom. The atom, a 16-bit value less than 0xC000, must be in the low-order word of lpClassName; the high-order word must be zero.

If lpClassName is a string, it specifies the window class name. The class name can be any name registered with the RegisterClassEx function or any of the predefined control-class names.

lpWindowName
Pointer to a null-terminated string that specifies the window name.

If the window style specifies a title bar, the window title pointed to by lpWindowName is displayed in the title bar. When using CreateWindow to create controls, such as buttons, check boxes, and static controls, use lpWindowName to specify the text of the control.

dwStyle
Specifies the style of the window being created. This parameter can be a combination of the following window styles, plus the control styles indicated in the Remarks section.
Style | Meaning
WS_BORDER | Creates a window that has a thin-line border.
WS_CAPTION | Creates a window that has a title bar (includes the WS_BORDER style).
WS_CHILD | Creates a child window. This style cannot be used with the WS_POPUP style.
WS_CHILDWINDOW | Same as the WS_CHILD style.
WS_CLIPCHILDREN | Excludes the area occupied by child windows when drawing occurs within the parent window. This style is used when creating the parent window.
WS_CLIPSIBLINGS | Clips child windows relative to each other; that is, when a particular child window receives a WM_PAINT message, the WS_CLIPSIBLINGS style clips all other overlapping child windows out of the region of the child window to be updated. If WS_CLIPSIBLINGS is not specified and child windows overlap, it is possible, when drawing within the client area of a child window, to draw within the client area of a neighboring child window.
WS_DISABLED | Creates a window that is initially disabled. A disabled window cannot receive input from the user.
WS_DLGFRAME | Creates a window that has a border of a style typically used with dialog boxes. A window with this style cannot have a title bar.
WS_GROUP | Specifies the first control of a group of controls. The group consists of this first control and all controls defined after it, up to the next control with the WS_GROUP style. The first control in each group usually has the WS_TABSTOP style so that the user can move from group to group. The user can subsequently change the keyboard focus from one control in the group to the next control in the group by using the direction keys.
WS_HSCROLL | Creates a window that has a horizontal scroll bar.
WS_ICONIC | Creates a window that is initially minimized. Same as the WS_MINIMIZE style.
WS_MAXIMIZE | Creates a window that is initially maximized.
WS_MAXIMIZEBOX | Creates a window that has a Maximize button. Cannot be combined with the WS_EX_CONTEXTHELP style. The WS_SYSMENU style must also be specified.
WS_MINIMIZE | Creates a window that is initially minimized. Same as the WS_ICONIC style.
WS_MINIMIZEBOX | Creates a window that has a Minimize button. Cannot be combined with the WS_EX_CONTEXTHELP style. The WS_SYSMENU style must also be specified.
WS_OVERLAPPED | Creates an overlapped window. An overlapped window has a title bar and a border. Same as the WS_TILED style.
WS_OVERLAPPEDWINDOW | Creates an overlapped window with the WS_OVERLAPPED, WS_CAPTION, WS_SYSMENU, WS_THICKFRAME, WS_MINIMIZEBOX, and WS_MAXIMIZEBOX styles. Same as the WS_TILEDWINDOW style.
WS_POPUP | Creates a pop-up window. This style cannot be used with the WS_CHILD style.
WS_POPUPWINDOW | Creates a pop-up window with WS_BORDER, WS_POPUP, and WS_SYSMENU styles. The WS_CAPTION and WS_POPUPWINDOW styles must be combined to make the window menu visible.
WS_SIZEBOX | Creates a window that has a sizing border. Same as the WS_THICKFRAME style.
WS_SYSMENU | Creates a window that has a window menu on its title bar. The WS_CAPTION style must also be specified.
WS_TABSTOP | Specifies a control that can receive the keyboard focus when the user presses the tab key. Pressing the tab key changes the keyboard focus to the next control with the WS_TABSTOP style.
WS_THICKFRAME | Creates a window that has a sizing border. Same as the WS_SIZEBOX style.
WS_TILED | Creates an overlapped window. An overlapped window has a title bar and a border. Same as the WS_OVERLAPPED style.
WS_TILEDWINDOW | Creates an overlapped window with the WS_OVERLAPPED, WS_CAPTION, WS_SYSMENU, WS_THICKFRAME, WS_MINIMIZEBOX, and WS_MAXIMIZEBOX styles. Same as the WS_OVERLAPPEDWINDOW style.
WS_VISIBLE | Creates a window that is initially visible.
WS_VSCROLL | Creates a window that has a vertical scroll bar.

x
Specifies the initial horizontal position of the window. For an overlapped or pop-up window, the x parameter is the initial x-coordinate of the window's upper-left corner, in screen coordinates. For a child window, x is the x-coordinate of the upper-left corner of the window relative to the upper-left corner of the parent window's client area.

If x is set to CW_USEDEFAULT, the system selects the default position for the window's upper-left corner and ignores the y parameter. CW_USEDEFAULT is valid only for overlapped windows; if it is specified for a pop-up or child window, the x and y parameters are set to zero.

y
Specifies the initial vertical position of the window. For an overlapped or pop-up window, the y parameter is the initial y-coordinate of the window's upper-left corner, in screen coordinates. For a child window, y is the initial y-coordinate of the upper-left corner of the child window relative to the upper-left corner of the parent window's client area. For a list box, y is the initial y-coordinate of the upper-left corner of the list box's client area relative to the upper-left corner of the parent window's client area.

If an overlapped window is created with the WS_VISIBLE style bit set and the x parameter is set to CW_USEDEFAULT, the system ignores the y parameter.

nWidth
Specifies the width, in device units, of the window. For overlapped windows, nWidth is the window's width, in screen coordinates, or CW_USEDEFAULT. If nWidth is CW_USEDEFAULT, the system selects a default width and height for the window; the default width extends from the initial x-coordinates to the right edge of the screen; the default height extends from the initial y-coordinate to the top of the icon area. CW_USEDEFAULT is valid only for overlapped windows; if CW_USEDEFAULT is specified for a pop-up or child window, the nWidth and nHeight parameter are set to zero.
nHeight
Specifies the height, in device units, of the window. For overlapped windows, nHeight is the window's height, in screen coordinates. If the nWidth parameter is set to CW_USEDEFAULT, the system ignores nHeight.
hWndParent
Handle to the parent or owner window of the window being created. To create a child window or an owned window, supply a valid window handle. This parameter is optional for pop-up windows.

Windows NT 5.0 and later: To create a message-only window, supply HWND_MESSAGE or a handle to an existing message-only window.

hMenu
Handle to a menu, or specifies a child-window identifier, depending on the window style. For an overlapped or pop-up window, hMenu identifies the menu to be used with the window; it can be NULL if the class menu is to be used. For a child window, hMenu specifies the child-window identifier, an integer value used by a dialog box control to notify its parent about events. The application determines the child-window identifier; it must be unique for all child windows with the same parent window.
hInstance
Handle to the instance of the module to be associated with the window.
lpParam
A pointer to a value to be passed to the window through the CREATESTRUCT structure passed in the lParam parameter the WM_CREATE message. If an application calls CreateWindow to create a multiple document interface (MDI) client window, lpParam must point to a CLIENTCREATESTRUCT structure.

Return Values

If the function succeeds, the return value is a handle to the new window.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The CreateWindowEx function sends WM_NCCREATE, WM_NCCALCSIZE, and WM_CREATE messages to the window being created.

For information on controlling whether the Taskbar displays a button for the created window, see Visibility of Taskbar Buttons.

The following predefined control classes can be specified in the lpClassName parameter. Note the corresponding control styles you can use in the dwStyle parameter.

Class | Meaning
BUTTON | Designates a small rectangular child window that represents a button the user can click to turn it on or off. Button controls can be used alone or in groups, and they can either be labeled or appear without text. Button controls typically change appearance when the user clicks them. For more information, see Buttons.
 | For a table of the button styles you can specify in the dwStyle parameter, see Button Styles.
COMBOBOX | Designates a control consisting of a list box and a selection field similar to an edit control. When using this style, an application should either display the list box at all times or enable a drop-down list box. If the list box is visible, typing characters into the selection field highlights the first list box entry that matches the characters typed. Conversely, selecting an item in the list box displays the selected text in the selection field. For more information, see Combo Boxes.
 | For a table of the combo box styles you can specify in the dwStyle parameter, see Combo Box Styles.
EDIT | Designates a rectangular child window into which the user can type text from the keyboard. The user selects the control and gives it the keyboard focus by clicking it or moving to it by pressing the tab key. The user can type text when the edit control displays a flashing caret; use the mouse to move the cursor, select characters to be replaced, or position the cursor for inserting characters; or use the backspace key to delete characters. For more information, see Edit Controls.
 | For a table of the edit control styles you can specify in the dwStyle parameter, see Edit Control Styles.
LISTBOX | Designates a list of character strings. Specify this control whenever an application must present a list of names, such as filenames, from which the user can choose. The user can select a string by clicking it. A selected string is highlighted, and a notification message is passed to the parent window. For more information, see List Boxes.
 | For a table of the list box styles you can specify in the dwStyle parameter, see List Box Styles.
MDICLIENT | Designates an MDI client window. This window receives messages that control the MDI application's child windows. The recommended style bits are WS_CLIPCHILDREN and WS_CHILD. Specify the WS_HSCROLL and WS_VSCROLL styles to create an MDI client window that allows the user to scroll MDI child windows into view. For more information, see Multiple Document Interface.
RichEdit | Designates a Rich Edit version 1.0 control. This window lets the user view and edit text with character and paragraph formatting, and can include embedded COM objects. For more information, see Rich Edit Controls.
 | For a table of the rich edit control styles you can specify in the dwStyle parameter, see Rich Edit Control Styles.
RICHEDIT_CLASS | Designates a Rich Edit version 2.0 control. This controls let the user view and edit text with character and paragraph formatting, and can include embedded COM objects. For more information, see Rich Edit Controls.
 | For a table of the rich edit control styles you can specify in the dwStyle parameter, see Rich Edit Control Styles.
SCROLLBAR | Designates a rectangle that contains a scroll box and has direction arrows at both ends. The scroll bar sends a notification message to its parent window whenever the user clicks the control. The parent window is responsible for updating the position of the scroll box, if necessary. For more information, see Scroll Bars.
 | For a table of the scroll bar control styles you can specify in the dwStyle parameter, see Scroll Bar Control Styles.
STATIC | Designates a simple text field, box, or rectangle used to label, box, or separate other controls. Static controls take no input and provide no output. For more information, see Static Controls.
 | For a table of the static control styles you can specify in the dwStyle parameter, see Static Control Styles.

Windows 95: The system can support a maximum of 16,364 window handles.

Windows CE: Windows CE does not support stand alone menu bars. The hMenu parameter must be NULL, unless it is used as a child-window identifier.

Windows CE versions 2.0 and later support the following two extended window styles:

WS_EX_NOACTIVATE
A top level window created with this style cannot be activated. If a child window has this style, tapping it will not cause its top-level parent to be activated. A window that has this style will receive stylus events, but neither it nor its child windows can get the focus.
WS_EX_NOANIMATION
A window created with this style does not show animated exploding and imploding rectangles, and does not have a button on the taskbar.

The following dwExStyle flags are not supported.

WS_EX_ACCEPTFILES | WS_EX_LEFTSCROLLBAR
WS_EX_LEFT | WS_EX_MDICHILD
WS_EX_LTRREADING | WS_EX_PALETTEWINDOW
WS_EX_NOPARENTNOTIFY | WS_EX_RIGHTSCROLLBAR
WS_EX_RIGHT | WS_EX_TOOLWINDOW
WS_EX_RTLREADING | WS_EX_TRANSPARENT
WS_EX_APPWINDOW |

Windows CE 1.0 does not support the WS_EX_TOPMOST style. Versions 2.0 and later do.

The following dwStyle flags are not supported.

WS_CHILDWINDOW | WS_ICONIC
WS_MAXIMIZE | WS_MAXIMIZEBOX
WS_MINIMIZE | WS_MINIMIZEBOX
WS_OVERLAPPEDWINDOW | WS_POPUPWINDOW
WS_SIZEBOX | WS_THICKFRAME
WS_TILED | WS_TILEDWINDOW

All windows implicitly have the WS_CLIPSIBLINGS and WS_CLIPCHILDREN styles.

Windows CE 1.0 does not support owned windows, except for dialog boxes. If the hwndParent parameter is not NULL, the window is implicitly given the WS_CHILD style.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Windows Overview, Window Functions, CLIENTCREATESTRUCT, CREATESTRUCT, CreateWindow, GlobalAddAtom, RegisterClassEx, SetWindowPos, WM_CREATE, WM_NCCALCSIZE, WM_NCCREATE, WM_PAINT, WM_PARENTNOTIFY


DeferWindowPos

The DeferWindowPos function updates the specified multiple-window – position structure for the specified window. The function then returns a handle to the updated structure. The EndDeferWindowPos function uses the information in this structure to change the position and size of a number of windows simultaneously. The BeginDeferWindowPos function creates the structure.

HDWP DeferWindowPos(
  HDWP hWinPosInfo,      // handle to internal structure
  HWND hWnd,             // handle to window to position
  HWND hWndInsertAfter,  // placement-order handle
  int x,                 // horizontal position
  int y,                 // vertical position
  int cx,                // width
  int cy,                // height
  UINT uFlags            // window-positioning flags
);

Parameters

hWinPosInfo
Handle to a multiple-window – position structure that contains size and position information for one or more windows. This structure is returned by BeginDeferWindowPos or by the most recent call to DeferWindowPos.
hWnd
Handle to the window for which update information is stored in the structure.
hWndInsertAfter
Handle to the window that precedes the positioned window in the Z order. This parameter must be a window handle or one of the following values:
Value | Meaning
HWND_BOTTOM | Places the window at the bottom of the Z order. If the hWnd parameter identifies a topmost window, the window loses its topmost status and is placed at the bottom of all other windows.
HWND_NOTOPMOST | Places the window above all non-topmost windows (that is, behind all topmost windows). This flag has no effect if the window is already a non-topmost window.
HWND_TOP | Places the window at the top of the Z order.
HWND_TOPMOST | Places the window above all non-topmost windows. The window maintains its topmost position even when it is deactivated.

This parameter is ignored if the SWP_NOZORDER flag is set in the uFlags parameter.

x
Specifies the x-coordinate of the window's upper-left corner.
y
Specifies the y-coordinate of the window's upper-left corner.
cx
Specifies the window's new width, in pixels.
cy
Specifies the window's new height, in pixels.
uFlags
Specifies a combination of the following values that affect the size and position of the window:
Value | Meaning
SWP_DRAWFRAME | Draws a frame (defined in the window's class description) around the window.
SWP_FRAMECHANGED | Sends a WM_NCCALCSIZE message to the window, even if the window's size is not being changed. If this flag is not specified, WM_NCCALCSIZE is sent only when the window's size is being changed.
SWP_HIDEWINDOW | Hides the window.
SWP_NOACTIVATE | Does not activate the window. If this flag is not set, the window is activated and moved to the top of either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter parameter).
SWP_NOCOPYBITS | Discards the entire contents of the client area. If this flag is not specified, the valid contents of the client area are saved and copied back into the client area after the window is sized or repositioned.
SWP_NOMOVE | Retains the current position (ignores the X and Y parameters).
SWP_NOOWNERZORDER | Does not change the owner window's position in the Z order.
SWP_NOREDRAW | Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent window uncovered as a result of the window being moved. When this flag is set, the application must explicitly invalidate or redraw any parts of the window and parent window that need redrawing.
SWP_NOREPOSITION | Same as the SWP_NOOWNERZORDER flag.
SWP_NOSENDCHANGING | Prevents the window from receiving the WM_WINDOWPOSCHANGING message.
SWP_NOSIZE | Retains the current size (ignores the cx and cy parameters).
SWP_NOZORDER | Retains the current Z order (ignores the hWndInsertAfter parameter).
SWP_SHOWWINDOW | Displays the window.

Return Values

The return value identifies the updated multiple-window – position structure. The handle returned by this function may differ from the handle passed to the function. The new handle that this function returns should be passed during the next call to the DeferWindowPos or EndDeferWindowPos function.

If insufficient system resources are available for the function to succeed, the return value is NULL. To get extended error information, call GetLastError.

Remarks

If a call to DeferWindowPos fails, the application should abandon the window-positioning operation and not call EndDeferWindowPos.

If SWP_NOZORDER is not specified, the system places the window identified by the hWnd parameter in the position following the window identified by the hWndInsertAfter parameter. If hWndInsertAfter is NULL or HWND_TOP, the system places the hWnd window at the top of the Z order. If hWndInsertAfter is set to HWND_BOTTOM, the system places the hWnd window at the bottom of the Z order.

All coordinates for child windows are relative to the upper-left corner of the parent window's client area.

A window can be made a topmost window either by setting hWndInsertAfter to the HWND_TOPMOST flag and ensuring that the SWP_NOZORDER flag is not set, or by setting the window's position in the Z order so that it is above any existing topmost windows. When a non-topmost window is made topmost, its owned windows are also made topmost. Its owners, however, are not changed.

If neither the SWP_NOACTIVATE nor SWP_NOZORDER flag is specified (that is, when the application requests that a window be simultaneously activated and its position in the Z order changed), the value specified in hWndInsertAfter is used only in the following circumstances:

  • Neither the HWND_TOPMOST nor HWND_NOTOPMOST flag is specified in hWndInsertAfter.
  • The window identified by hWnd is not the active window.

An application cannot activate an inactive window without also bringing it to the top of the Z order. An application can change an activated window's position in the Z order without restrictions, or it can activate a window and then move it to the top of the topmost or non-topmost windows.

A topmost window is no longer topmost if it is repositioned to the bottom (HWND_BOTTOM) of the Z order or after any non-topmost window. When a topmost window is made non-topmost, its owners and its owned windows are also made non-topmost windows.

A non-topmost window may own a topmost window, but not vice versa. Any window (for example, a dialog box) owned by a topmost window is itself made a topmost window to ensure that all owned windows stay above their owner.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, BeginDeferWindowPos, EndDeferWindowPos, ShowWindow


DestroyWindow

The DestroyWindow function destroys the specified window. The function sends WM_DESTROY and WM_NCDESTROY messages to the window to deactivate it and remove the keyboard focus from it. The function also destroys the window's menu, flushes the thread message queue, destroys timers, removes clipboard ownership, and breaks the clipboard viewer chain (if the window is at the top of the viewer chain).

If the specified window is a parent or owner window, DestroyWindow automatically destroys the associated child or owned windows when it destroys the parent or owner window. The function first destroys child or owned windows, and then it destroys the parent or owner window.

DestroyWindow also destroys modeless dialog boxes created by the CreateDialog function.

BOOL DestroyWindow(
  HWND hWnd   // handle to window to destroy
);

Parameters

hWnd
Handle to the window to be destroyed.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

A thread cannot use DestroyWindow to destroy a window created by a different thread.

If the window being destroyed is a child window that does not have the WS_EX_NOPARENTNOTIFY style, a WM_PARENTNOTIFY message is sent to the parent.

Windows CE: The DestroyWindow function does not send the WM_NCDESTROY message.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, CreateDialog, CreateWindow, CreateWindowEx, WM_DESTROY, WM_NCDESTROY, WM_PARENTNOTIFY


EndDeferWindowPos

The EndDeferWindowPos function simultaneously updates the position and size of one or more windows in a single screen-refreshing cycle.

BOOL EndDeferWindowPos(
  HDWP hWinPosInfo   // handle to internal structure
);

Parameters

hWinPosInfo
Handle to a multiple-window – position structure that contains size and position information for one or more windows. This internal structure is returned by the BeginDeferWindowPos function or by the most recent call to the DeferWindowPos function.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The EndDeferWindowPos function sends the WM_WINDOWPOSCHANGING and WM_WINDOWPOSCHANGED messages to each window identified in the internal structure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, BeginDeferWindowPos, DeferWindowPos, WM_WINDOWPOSCHANGED, WM_WINDOWPOSCHANGING


EnumChildProc

The EnumChildProc function is an application-defined callback function used with the EnumChildWindows function. It receives the child window handles. The WNDENUMPROC type defines a pointer to this callback function. EnumChildProc is a placeholder for the application-defined function name.

BOOL CALLBACK EnumChildProc(
  HWND hwnd,      // handle to child window
  LPARAM lParam   // application-defined value
);

Parameters

hwnd
Handle to a child window of the parent window specified in EnumChildWindows.
lParam
Specifies the application-defined value given in EnumChildWindows.

Return Values

To continue enumeration, the callback function must return TRUE; to stop enumeration, it must return FALSE.

Remarks

The callback function can carry out any desired task.

An application must register this callback function by passing its address to EnumChildWindows.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: User-defined.

See Also

Windows Overview, Window Functions, EnumChildWindows


EnumChildWindows

The EnumChildWindows function enumerates the child windows that belong to the specified parent window by passing the handle to each child window, in turn, to an application-defined callback function. EnumChildWindows continues until the last child window is enumerated or the callback function returns FALSE.

BOOL EnumChildWindows(
  HWND hWndParent,         // handle to parent window
  WNDENUMPROC lpEnumFunc,  // pointer to callback function
  LPARAM lParam            // application-defined value
);

Parameters

hWndParent
Handle to the parent window whose child windows are to be enumerated. If this parameter is NULL, the parent window is the desktop window, and the function enumerates all top-level windows.
lpEnumFunc
Pointer to an application-defined callback function. For more information, see EnumChildProc.
lParam
Specifies an application-defined value to be passed to the callback function.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

If a child window has created child windows of its own, EnumChildWindows enumerates those windows as well.

A child window that is moved or repositioned in the Z order during the enumeration process will be properly enumerated. The function does not enumerate a child window that is destroyed before being enumerated or that is created during the enumeration process.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, EnumChildProc, EnumThreadWindows, EnumWindows, GetWindow


EnumTaskWindows

The EnumTaskWindows function is obsolete. It has been superseded by the EnumThreadWindows function.

To maintain compatibility for 16-bit applications, EnumTaskWindows has been replaced with a macro that calls EnumThreadWindows. Earlier applications can continue to call EnumTaskWindows as previously documented, but new applications should use EnumThreadWindows.

See Also

Windows Overview, Window Functions


EnumThreadWindows

The EnumThreadWindows function enumerates all nonchild windows associated with a thread by passing the handle to each window, in turn, to an application-defined callback function. EnumThreadWindows continues until the last window is enumerated or the callback function returns FALSE. To enumerate child windows of a particular window, use the EnumChildWindows function.

BOOL EnumThreadWindows(
  DWORD dwThreadId,  // thread identifier
  WNDENUMPROC lpfn,  // pointer to callback function
  LPARAM lParam      // application-defined value
);

Parameters

dwThreadId
Identifies the thread whose windows are to be enumerated.
lpfn
Pointer to an application-defined callback function. For more information, see EnumThreadWndProc.
lParam
Specifies an application-defined value to be passed to the callback function.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, EnumChildWindows, EnumThreadWndProc, EnumWindows


EnumThreadWndProc

The EnumThreadWndProc function is an application-defined callback function used with the EnumThreadWindows function. It receives the window handles associated with a thread. The WNDENUMPROC type defines a pointer to this callback function. EnumThreadProc is a placeholder for the application-defined function name.

BOOL CALLBACK EnumThreadWndProc(
  HWND hwnd,      // handle to window
  LPARAM lParam   // application-defined value
);

Parameters

hwnd
Handle to a window associated with the thread specified in the EnumThreadWindows function.
lParam
Specifies the application-defined value given in the EnumThreadWindows function.

Return Values

To continue enumeration, the callback function must return TRUE; to stop enumeration, it must return FALSE.

Remarks

An application must register this callback function by passing its address to the EnumThreadWindows function.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: User-defined.

See Also

Windows Overview, Window Functions, EnumThreadWindows


EnumWindows

The EnumWindows function enumerates all top-level windows on the screen by passing the handle to each window, in turn, to an application-defined callback function. EnumWindows continues until the last top-level window is enumerated or the callback function returns FALSE.

BOOL EnumWindows(
  WNDENUMPROC lpEnumFunc,  // pointer to callback function
  LPARAM lParam            // application-defined value
);

Parameters

lpEnumFunc
Pointer to an application-defined callback function. For more information, see EnumWindowsProc.
lParam
Specifies an application-defined value to be passed to the callback function.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The EnumWindows function does not enumerate child windows.

This function is more reliable than calling the GetWindow function in a loop. An application that calls GetWindow to perform this task risks being caught in an infinite loop or referencing a handle to a window that has been destroyed.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, EnumChildWindows, EnumWindowsProc, GetWindow


EnumWindowsProc

The EnumWindowsProc function is an application-defined callback function used with the EnumWindows or EnumDesktopWindows function. It receives top-level window handles. The WNDENUMPROC type defines a pointer to this callback function. EnumWindowsProc is a placeholder for the application-defined function name.

BOOL CALLBACK EnumWindowsProc(
  HWND hwnd,      // handle to parent window
  LPARAM lParam   // application-defined value
);

Parameters

hwnd
Handle to a top-level window.
lParam
Specifies the application-defined value given in EnumWindows or EnumDesktopWindows.

Return Values

To continue enumeration, the callback function must return TRUE; to stop enumeration, it must return FALSE.

Remarks

An application must register this callback function by passing its address to EnumWindows or EnumDesktopWindows.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: User-defined.

See Also

Windows Overview, Window Functions, EnumWindows, EnumDesktopWindows


FindWindow

The FindWindow function retrieves a handle to the top-level window whose class name and window name match the specified strings. This function does not search child windows. This function does not perform a case-sensitive search.

HWND FindWindow(
  LPCTSTR lpClassName,  // pointer to class name
  LPCTSTR lpWindowName  // pointer to window name
);

Parameters

lpClassName
Pointer to a null-terminated string that specifies the class name or is an atom that identifies the class-name string. If this parameter is an atom, it must be a global atom created by a previous call to the GlobalAddAtom function. The atom, a 16-bit value, must be placed in the low-order word of lpClassName; the high-order word must be zero.
lpWindowName
Pointer to a null-terminated string that specifies the window name (the window's title). If this parameter is NULL, all window names match.

Return Values

If the function succeeds, the return value is a handle to the window that has the specified class name and window name.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

Windows CE: If lpClassName is an atom, it must be an atom returned from RegisterClass.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Windows Overview, Window Functions, EnumWindows, FindWindowEx, GetClassName, GlobalAddAtom


FindWindowEx

The FindWindowEx function retrieves a handle to a window whose class name and window name match the specified strings. The function searches child windows, beginning with the one following the given child window. This function does not perform a case-sensitive search.

HWND FindWindowEx(
  HWND hwndParent,      // handle to parent window
  HWND hwndChildAfter,  // handle to a child window
  LPCTSTR lpszClass,    // pointer to class name
  LPCTSTR lpszWindow    // pointer to window name
);

Parameters

hwndParent
Handle to the parent window whose child windows are to be searched.

If hwndParent is NULL, the function uses the desktop window as the parent window. The function searches among windows that are child windows of the desktop.

Windows NT 5.0 and later: If hwndParent is HWND_MESSAGE, the function searches all message-only windows.

hwndChildAfter
Handle to a child window. The search begins with the next child window in the Z order. The child window must be a direct child window of hwndParent, not just a descendant window.

If hwndChildAfter is NULL, the search begins with the first child window of hwndParent.

Note that if both hwndParent and hwndChildAfter are NULL, the function searches all top-level and message-only windows.

lpszClass
Pointer to a null-terminated string that specifies the class name or is an atom that identifies the class-name string. If this parameter is an atom, it must be a global atom created by a previous call to the GlobalAddAtom function. The atom, a 16-bit value, must be placed in the low-order word of lpszClass; the high-order word must be zero.
lpszWindow
Pointer to a null-terminated string that specifies the window name (the window's title). If this parameter is NULL, all window names match.

Return Values

If the function succeeds, the return value is a handle to the window that has the specified class and window names.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Windows Overview, Window Functions, EnumWindows, FindWindow, GetClassName, GlobalAddAtom


GetClientRect

The GetClientRect function retrieves the coordinates of a window's client area. The client coordinates specify the upper-left and lower-right corners of the client area. Because client coordinates are relative to the upper-left corner of a window's client area, the coordinates of the upper-left corner are (0,0).

BOOL GetClientRect(
  HWND hWnd,      // handle to window
  LPRECT lpRect   // address of structure for client coordinates
);

Parameters

hWnd
Handle to the window whose client coordinates are to be retrieved.
lpRect
Pointer to a RECT structure that receives the client coordinates. The left and top members are zero. The right and bottom members contain the width and height of the window.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Windows CE: Command bars are included in the client area.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, GetWindowRect, RECT


GetDesktopWindow

The GetDesktopWindow function returns a handle to the desktop window. The desktop window covers the entire screen. The desktop window is the area on top of which all icons and other windows are painted.

HWND GetDesktopWindow(VOID)

Parameters

This function has no parameters.

Return Values

The return value is a handle to the desktop window.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, GetWindow


GetForegroundWindow

The GetForegroundWindow function returns a handle to the foreground window (the window with which the user is currently working). The system assigns a slightly higher priority to the thread that creates the foreground window than it does to other threads.

HWND GetForegroundWindow(VOID)

Parameters

This function has no parameters.

Return Values

The return value is a handle to the foreground window.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, SetForegroundWindow


GetLastActivePopup

The GetLastActivePopup function determines which pop-up window owned by the specified window was most recently active.

HWND GetLastActivePopup(
  HWND hWnd   // handle to owner window
);

Parameters

hWnd
Handle to the owner window.

Return Values

The return value identifies the most recently active pop-up window. The return value is the same as the hWnd parameter, if any of the following conditions are met:

  • The window identified by hWnd was most recently active.
  • The window identified by hWnd does not own any pop-up windows.
  • The window identified by hWnd is not a top-level window or it is owned by another window.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, AnyPopup, ShowOwnedPopups


GetNextWindow

The GetNextWindow function retrieves a handle to the next or previous window in the Z order. The next window is below the specified window; the previous window is above. If the specified window is a topmost window, the function retrieves a handle to the next (or previous) topmost window. If the specified window is a top-level window, the function retrieves a handle to the next (or previous) top-level window. If the specified window is a child window, the function searches for a handle to the next (or previous) child window.

HWND GetNextWindow(
  HWND hWnd,  // handle to current window
  UINT wCmd   // direction flag
);

Parameters

hWnd
Handle to a window. The window handle retrieved is relative to this window, based on the value of the wCmd parameter.
wCmd
Specifies whether the function returns a handle to the next window or of the previous window. This parameter can be either of the following values:
Value | Meaning
GW_HWNDNEXT | Returns a handle to the window below the given window.
GW_HWNDPREV | Returns a handle to the window above the given window.

Return Values

If the function succeeds, the return value is a handle to the next (or previous) window. If there is no next (or previous) window, the return value is NULL. To get extended error information, call GetLastError.

Remarks

Using this function is the same as calling the GetWindow function with the GW_HWNDNEXT or GW_HWNDPREV flag set.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, GetTopWindow


GetParent

The GetParent function retrieves a handle to the specified child window's parent window.

HWND GetParent(
  HWND hWnd   // handle to child window
);

Parameters

hWnd
Handle to the window whose parent window handle is to be retrieved.

Return Values

If the function succeeds, the return value is a handle to the parent window. If the window has no parent window, the return value is NULL. To get extended error information, call GetLastError.

Remarks

Windows CE: Windows CE version 1.0 does not support owned windows, except for dialog boxes.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, SetParent


GetSysModalWindow

The GetSysModalWindow function is obsolete. This function is provided only for compatibility with 16-bit versions of Windows.

See Also

Windows Overview, Window Functions


GetTopWindow

The GetTopWindow function examines the Z order of the child windows associated with the specified parent window and retrieves a handle to the child window at the top of the Z order.

HWND GetTopWindow(
  HWND hWnd   // handle to parent window
);

Parameters

hWnd
Handle to the parent window whose child windows are to be examined. If this parameter is NULL, the function returns a handle to the window at the top of the Z order.

Return Values

If the function succeeds, the return value is a handle to the child window at the top of the Z order. If the specified window has no child windows, the return value is NULL. To get extended error information, use the GetLastError function.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, GetNextWindow, GetWindow


GetWindow

The GetWindow function retrieves a handle to a window that has the specified relationship (Z order or owner) to the specified window.

HWND GetWindow(
  HWND hWnd,  // handle to original window
  UINT uCmd   // relationship flag
);

Parameters

hWnd
Handle to a window. The window handle retrieved is relative to this window, based on the value of the uCmd parameter.
uCmd
Specifies the relationship between the specified window and the window whose handle is to be retrieved. This parameter can be one of the following values:
Value | Meaning
GW_CHILD | The retrieved handle identifies the child window at the top of the Z order, if the specified window is a parent window; otherwise, the retrieved handle is NULL. The function examines only child windows of the specified window. It does not examine descendant windows.
GW_ENABLEDPOPUP | Windows NT 5.0 and later: The retrieved handle identifies the enabled popup window owned by the specified window (the search uses the first such window found using GW_HWNDNEXT); otherwise, if there are no enabled popup windows, the retrieved handle is that of the specified window.
GW_HWNDFIRST | The retrieved handle identifies the window of the same type that is highest in the Z order. If the specified window is a topmost window, the handle identifies the topmost window that is highest in the Z order. If the specified window is a top-level window, the handle identifies the top-level window that is highest in the Z order. If the specified window is a child window, the handle identifies the sibling window that is highest in the Z order.
GW_HWNDLAST | The retrieved handle identifies the window of the same type that is lowest in the Z order. If the specified window is a topmost window, the handle identifies the topmost window that is lowest in the Z order. If the specified window is a top-level window, the handle identifies the top-level window that is lowest in the Z order. If the specified window is a child window, the handle identifies the sibling window that is lowest in the Z order.
GW_HWNDNEXT | The retrieved handle identifies the window below the specified window in the Z order. If the specified window is a topmost window, the handle identifies the topmost window below the specified window. If the specified window is a top-level window, the handle identifies the top-level window below the specified window. If the specified window is a child window, the handle identifies the sibling window below the specified window.
GW_HWNDPREV | The retrieved handle identifies the window above the specified window in the Z order. If the specified window is a topmost window, the handle identifies the topmost window above the specified window. If the specified window is a top-level window, the handle identifies the top-level window above the specified window. If the specified window is a child window, the handle identifies the sibling window above the specified window.
GW_OWNER | The retrieved handle identifies the specified window's owner window, if any.

Return Values

If the function succeeds, the return value is a window handle. If no window exists with the specified relationship to the specified window, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The EnumChildWindows function is more reliable than calling GetWindow in a loop. An application that calls GetWindow to perform this task risks being caught in an infinite loop or referencing a handle to a window that has been destroyed.

Windows CE: In Windows CE version 1.0, the GW_OWNER flag value for the uCmd parameter is only supported for dialog boxes.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, EnumChildWindows


GetWindowPlacement

The GetWindowPlacement function retrieves the show state and the restored, minimized, and maximized positions of the specified window.

BOOL GetWindowPlacement(
  HWND hWnd,               // handle to window
  WINDOWPLACEMENT *lpwndpl // address of structure for position data
);

Parameters

hWnd
Handle to the window.
lpwndpl
Pointer to the WINDOWPLACEMENT structure that receives the show state and position information.

Before calling GetWindowPlacement, set the length member of the WINDOWPLACEMENT structure to sizeof(WINDOWPLACEMENT). GetWindowPlacement fails if lpwndpl->length is not set correctly.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The flags member of WINDOWPLACEMENT retrieved by this function is always zero. If the window identified by the hWnd parameter is maximized, the showCmd member is SW_SHOWMAXIMIZED. If the window is minimized, showCmd is SW_SHOWMINIMIZED. Otherwise, it is SW_SHOWNORMAL.

The length member of WINDOWPLACEMENT must be set to sizeof(WINDOWPLACEMENT). If this member is not set correctly, the function returns FALSE. For additional remarks on the proper use of window placement coordinates, see WINDOWPLACEMENT.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, SetWindowPlacement, WINDOWPLACEMENT


GetWindowRect

The GetWindowRect function retrieves the dimensions of the bounding rectangle of the specified window. The dimensions are given in screen coordinates that are relative to the upper-left corner of the screen.

BOOL GetWindowRect(
  HWND hWnd,      // handle to window
  LPRECT lpRect   // address of structure for window coordinates
);

Parameters

hWnd
Handle to the window.
lpRect
Pointer to a RECT structure that receives the screen coordinates of the upper-left and lower-right corners of the window.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, GetClientRect, RECT


GetWindowTask

The GetWindowTask function is obsolete. This function is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should use the GetWindowThreadProcessId function.

See Also

Windows Overview, Window Functions


GetWindowText

The GetWindowText function copies the text of the specified window's title bar (if it has one) into a buffer. If the specified window is a control, the text of the control is copied. However, GetWindowText cannot retrieve the text of a control in another application.

int GetWindowText(
  HWND hWnd,        // handle to window or control with text
  LPTSTR lpString,  // address of buffer for text
  int nMaxCount     // maximum number of characters to copy
);

Parameters

hWnd
Handle to the window or control containing the text.
lpString
Pointer to the buffer that will receive the text.
nMaxCount
Specifies the maximum number of characters to copy to the buffer, including the NULL character. If the text exceeds this limit, it is truncated.

Return Values

If the function succeeds, the return value is the length, in characters, of the copied string, not including the terminating null character. If the window has no title bar or text, if the title bar is empty, or if the window or control handle is invalid, the return value is zero. To get extended error information, call GetLastError.

This function cannot retrieve the text of an edit control in another application.

Remarks

If the target window is owned by the current process, GetWindowText causes a WM_GETTEXT message to be sent to the specified window or control. If the target window is owned by another process and has a caption, GetWindowText retrieves the window caption text. If the window does not have a caption, the return value is a null string.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Windows Overview, Window Functions, GetWindowTextLength, SetWindowText, WM_GETTEXT


GetWindowTextLength

The GetWindowTextLength function retrieves the length, in characters, of the specified window's title bar text (if the window has a title bar). If the specified window is a control, the function retrieves the length of the text within the control. However, GetWindowTextLength cannot retrieve the length of the text of an edit control in another application.

int GetWindowTextLength(
  HWND hWnd   // handle to window or control with text
);

Parameters

hWnd
Handle to the window or control.

Return Values

If the function succeeds, the return value is the length, in characters, of the text. Under certain conditions, this value may actually be greater than the length of the text. For more information, see the following Remarks section.

If the window has no text, the return value is zero. To get extended error information, call GetLastError.

Remarks

If the target window is owned by the current process, GetWindowTextLength causes a WM_GETTEXTLENGTH message to be sent to the specified window or control.

Under certain conditions, the GetWindowTextLength function may return a value that is larger than the actual length of the text. This occurs with certain mixtures of ANSI and Unicode, and is due to the system allowing for the possible existence of DBCS characters within the text. The return value, however, will always be at least as large as the actual length of the text; you can thus always use it to guide buffer allocation. This behavior can occur when an application uses both ANSI functions and common dialogs, which use Unicode. It can also occur when an application uses the ANSI version of GetWindowTextLength with a window whose window procedure is Unicode, or the Unicode version of GetWindowTextLength with a window whose window procedure is ANSI. For more information on ANSI and Unicode functions, see Win32 Function Prototypes.

To obtain the exact length of the text, use the WM_GETTEXT, LB_GETTEXT, or CB_GETLBTEXT messages, or the GetWindowText function.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Windows Overview, Window Functions, CB_GETLBTEXT, GetWindowText, LB_GETTEXT, SetWindowText, WM_GETTEXT, WM_GETTEXTLENGTH


GetWindowThreadProcessId

The GetWindowThreadProcessId function retrieves the identifier of the thread that created the specified window and, optionally, the identifier of the process that created the window.

DWORD GetWindowThreadProcessId(
  HWND hWnd,             // handle to window
  LPDWORD lpdwProcessId  // address of variable for process identifier
);

Parameters

hWnd
Handle to the window.
lpdwProcessId
Pointer to a 32-bit value that receives the process identifier. If this parameter is not NULL, GetWindowThreadProcessId copies the identifier of the process to the 32-bit value; otherwise, it does not.

Return Values

The return value is the identifier of the thread that created the window.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions


IsChild

The IsChild function tests whether a window is a child window or descendant window of a specified parent window. A child window is the direct descendant of a specified parent window if that parent window is in the chain of parent windows; the chain of parent windows leads from the original overlapped or pop-up window to the child window.

BOOL IsChild(
  HWND hWndParent,  // handle to parent window
  HWND hWnd         // handle to window to test
);

Parameters

hWndParent
Handle to the parent window.
hWnd
Handle to the window to be tested.

Return Values

If the window is a child or descendant window of the specified parent window, the return value is nonzero.

If the window is not a child or descendant window of the specified parent window, the return value is zero.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, IsWindow, SetParent


IsIconic

The IsIconic function determines whether the specified window is minimized (iconic).

BOOL IsIconic(
  HWND hWnd   // handle to window
);

Parameters

hWnd
Handle to the window to test.

Return Values

If the window is iconic, the return value is nonzero.

If the window is not iconic, the return value is zero.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, IsZoomed


IsWindow

The IsWindow function determines whether the specified window handle identifies an existing window.

BOOL IsWindow(
  HWND hWnd   // handle to window
);

Parameters

hWnd
Handle to the window to test.

Return Values

If the window handle identifies an existing window, the return value is nonzero.

If the window handle does not identify an existing window, the return value is zero.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, IsWindowEnabled, IsWindowVisible


IsWindowUnicode

The IsWindowUnicode function determines whether the specified window is a native Unicode window.

BOOL IsWindowUnicode(
  HWND hWnd   // handle to window
);

Parameters

hWnd
Handle to the window to test.

Return Values

If the window is a native Unicode window, the return value is nonzero.

If the window is not a native Unicode window, the return value is zero. The window is a native ANSI window.

Remarks

The character set of a window is determined by the use of the RegisterClass function. If the window class was registered with the ANSI version of RegisterClass (RegisterClassA), the character set of the window is ANSI. If the window class was registered with the Unicode version of RegisterClass (RegisterClassW), the character set of the window is Unicode.

The system does automatic two-way translation (Unicode to ANSI) for window messages. For example, if an ANSI window message is sent to a window that uses the Unicode character set, the system translates that message into a Unicode message before calling the window procedure. The system calls IsWindowUnicode to determine whether to translate the message.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions


IsWindowVisible

The IsWindowVisible function retrieves the visibility state of the specified window.

BOOL IsWindowVisible(
  HWND hWnd   // handle to window
);

Parameters

hWnd
Handle to the window to test.

Return Values

If the specified window and its parent window have the WS_VISIBLE style, the return value is nonzero.

If the specified window and its parent window do not have the WS_VISIBLE style, the return value is zero. Because the return value specifies whether the window has the WS_VISIBLE style, it may be nonzero even if the window is totally obscured by other windows.

Remarks

The visibility state of a window is indicated by the WS_VISIBLE style bit. When WS_VISIBLE is set, the window is displayed and subsequent drawing into it is displayed as long as the window has the WS_VISIBLE style.

Any drawing to a window with the WS_VISIBLE style will not be displayed if the window is obscured by other windows or is clipped by its parent window.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, ShowWindow


IsZoomed

The IsZoomed function determines whether a window is maximized.

BOOL IsZoomed(
  HWND hWnd   // handle to window
);

Parameters

hWnd
Handle to the window to test.

Return Values

If the window is zoomed, the return value is nonzero.

If the window is not zoomed, the return value is zero.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, IsIconic


MoveWindow

The MoveWindow function changes the position and dimensions of the specified window. For a top-level window, the position and dimensions are relative to the upper-left corner of the screen. For a child window, they are relative to the upper-left corner of the parent window's client area.

BOOL MoveWindow(
  HWND hWnd,      // handle to window
  int X,          // horizontal position
  int Y,          // vertical position
  int nWidth,     // width
  int nHeight,    // height
  BOOL bRepaint   // repaint flag
);

Parameters

hWnd
Handle to the window.
X
Specifies the new position of the left side of the window.
Y
Specifies the new position of the top of the window.
nWidth
Specifies the new width of the window.
nHeight
Specifies the new height of the window.
bRepaint
Specifies whether the window is to be repainted. If this parameter is TRUE, the window receives a WM_PAINT message. If the parameter is FALSE, no repainting of any kind occurs. This applies to the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent window uncovered as a result of moving a child window. If this parameter is FALSE, the application must explicitly invalidate or redraw any parts of the window and parent window that need redrawing.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

If the bRepaint parameter is TRUE, the system sends the WM_PAINT message to the window procedure immediately after moving the window (that is, the MoveWindow function calls the UpdateWindow function). If bRepaint is FALSE, the system places the WM_PAINT message in the message queue associated with the window. The message loop dispatches the WM_PAINT message only after dispatching all other messages in the queue.

MoveWindow sends WM_WINDOWPOSCHANGING, WM_WINDOWPOSCHANGED, WM_MOVE, WM_SIZE, and WM_NCCALCSIZE messages to the window.

Windows CE: The bRepaint parameter is ignored and is assumed to be FALSE.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, SetWindowPos, UpdateWindow, WM_GETMINMAXINFO, WM_PAINT


OpenIcon

The OpenIcon function restores a minimized (iconic) window to its previous size and position; it then activates the window.

BOOL OpenIcon(
  HWND hWnd   // handle to window
);

Parameters

hWnd
Handle to the window to be restored and activated.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

OpenIcon sends a WM_QUERYOPEN message to the given window.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, CloseWindow, IsIconic, ShowWindow


SetForegroundWindow

The SetForegroundWindow function puts the thread that created the specified window into the foreground and activates the window. Keyboard input is directed to the window, and various visual cues are changed for the user. The system assigns a slightly higher priority to the thread that created the foreground window than it does to other threads.

BOOL SetForegroundWindow(
  HWND hWnd   // handle to window to bring to foreground
);

Parameters

hWnd
Handle to the window that should be activated and brought to the foreground.

Return Values

If the window was brought to the foreground, the return value is nonzero.

If the window was not brought to the foreground, the return value is zero.

Remarks

The foreground window is the window at the top of the Z order. It is the window that the user is working with. In a preemptive multitasking environment, you should generally let the user control which window is the foreground window.

Windows NT 5.0 and later: An application cannot force a window to the foreground while the user is working with another window. Instead, SetForegroundWindow will activate the window (see SetActiveWindow) and call the FlashWindowEx function to notify the user.

Windows CE: The thread that owns the window is not given a priority boost.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, FlashWindowEx, GetForegroundWindow, SetActiveWindow


SetParent

The SetParent function changes the parent window of the specified child window.

HWND SetParent(
  HWND hWndChild,      // handle to window whose parent is changing
  HWND hWndNewParent   // handle to new parent window
);

Parameters

hWndChild
Handle to the child window.
hWndNewParent
Handle to the new parent window. If this parameter is NULL, the desktop window becomes the new parent window.

Windows NT 5.0 and later: If this parameter is HWND_MESSAGE, the child window becomes a message-only window.

Return Values

If the function succeeds, the return value is a handle to the previous parent window.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

An application can use the SetParent function to set the parent window of a pop-up, overlapped, or child window. The new parent window and the child window must belong to the same application.

If the window identified by the hWndChild parameter is visible, the system performs the appropriate redrawing and repainting.

For compatibility reasons, SetParent does not modify the WS_CHILD or WS_POPUP window styles of the window whose parent is being changed. Therefore, if hWndNewParent is NULL, you should also clear the WS_CHILD bit and set the WS_POPUP style after calling SetParent. Conversely, if hWndNewParent is not NULL and the window was previously a child of the desktop, you should clear the WS_POPUP style and set the WS_CHILD style before calling SetParent.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, GetParent


SetSysModalWindow

The SetSysModalWindow function is obsolete. This function is provided only for compatibility with 16-bit versions of Windows. The new input model does not allow for system modal windows.

See Also

Windows Overview, Window Functions


SetWindowPlacement

The SetWindowPlacement function sets the show state and the restored, minimized, and maximized positions of the specified window.

BOOL SetWindowPlacement(
  HWND hWnd,                      // handle to window
  CONST WINDOWPLACEMENT *lpwndpl  // address of structure with position data
);

Parameters

hWnd
Handle to the window.
lpwndpl
Pointer to a WINDOWPLACEMENT structure that specifies the new show state and window positions.

Before calling SetWindowPlacement, set the length member of the WINDOWPLACEMENT structure to sizeof(WINDOWPLACEMENT). SetWindowPlacement fails if lpwndpl->length is not set correctly.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

If the information specified in WINDOWPLACEMENT would result in a window that is completely off the screen, the system will automatically adjust the coordinates so that the window is visible, taking into account changes in screen resolution and multiple monitor configuration.

The length member of WINDOWPLACEMENT must be set to sizeof(WINDOWPLACEMENT). If this member is not set correctly, the function returns FALSE. For additional remarks on the proper use of window placement coordinates, see WINDOWPLACEMENT.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, GetWindowPlacement, WINDOWPLACEMENT


SetWindowPos

The SetWindowPos function changes the size, position, and Z order of a child, pop-up, or top-level window. Child, pop-up, and top-level windows are ordered according to their appearance on the screen. The topmost window receives the highest rank and is the first window in the Z order.

BOOL SetWindowPos(
  HWND hWnd,             // handle to window
  HWND hWndInsertAfter,  // placement-order handle
  int X,                 // horizontal position
  int Y,                 // vertical position
  int cx,                // width
  int cy,                // height
  UINT uFlags            // window-positioning flags
);

Parameters

hWnd
Handle to the window.
hWndInsertAfter
Handle to the window to precede the positioned window in the Z order. This parameter must be a window handle or one of the following values:
Value | Meaning
HWND_BOTTOM | Places the window at the bottom of the Z order. If the hWnd parameter identifies a topmost window, the window loses its topmost status and is placed at the bottom of all other windows.
HWND_NOTOPMOST | Places the window above all non-topmost windows (that is, behind all topmost windows). This flag has no effect if the window is already a non-topmost window.
HWND_TOP | Places the window at the top of the Z order.
HWND_TOPMOST | Places the window above all non-topmost windows. The window maintains its topmost position even when it is deactivated.

For more information about how this parameter is used, see the following Remarks section.

X
Specifies the new position of the left side of the window, in client coordinates.
Y
Specifies the new position of the top of the window, in client coordinates.
cx
Specifies the new width of the window, in pixels.
cy
Specifies the new height of the window, in pixels.
uFlags
Specifies the window sizing and positioning flags. This parameter can be a combination of the following values:
Value | Meaning
SWP_ASYNCWINDOWPOS | If the calling thread does not own the window, the system posts the request to the thread that owns the window. This prevents the calling thread from blocking its execution while other threads process the request.
SWP_DEFERERASE | Prevents generation of the WM_SYNCPAINT message.
SWP_DRAWFRAME | Draws a frame (defined in the window's class description) around the window.
SWP_FRAMECHANGED | Sends a WM_NCCALCSIZE message to the window, even if the window's size is not being changed. If this flag is not specified, WM_NCCALCSIZE is sent only when the window's size is being changed.
SWP_HIDEWINDOW | Hides the window.
SWP_NOACTIVATE | Does not activate the window. If this flag is not set, the window is activated and moved to the top of either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter parameter).
SWP_NOCOPYBITS | Discards the entire contents of the client area. If this flag is not specified, the valid contents of the client area are saved and copied back into the client area after the window is sized or repositioned.
SWP_NOMOVE | Retains the current position (ignores the X and Y parameters).
SWP_NOOWNERZORDER | Does not change the owner window's position in the Z order.
SWP_NOREDRAW | Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent window uncovered as a result of the window being moved. When this flag is set, the application must explicitly invalidate or redraw any parts of the window and parent window that need redrawing.
SWP_NOREPOSITION | Same as the SWP_NOOWNERZORDER flag.
SWP_NOSENDCHANGING | Prevents the window from receiving the WM_WINDOWPOSCHANGING message.
SWP_NOSIZE | Retains the current size (ignores the cx and cy parameters).
SWP_NOZORDER | Retains the current Z order (ignores the hWndInsertAfter parameter).
SWP_SHOWWINDOW | Displays the window.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

If the SWP_SHOWWINDOW or SWP_HIDEWINDOW flag is set, the window cannot be moved or sized.

If you have changed certain window data using SetWindowLong, you must call SetWindowPos to have the changes take effect. Use the following combination for uFlags: SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED.

A window can be made a topmost window either by setting the hWndInsertAfter parameter to HWND_TOPMOST and ensuring that the SWP_NOZORDER flag is not set, or by setting a window's position in the Z order so that it is above any existing topmost windows. When a non-topmost window is made topmost, its owned windows are also made topmost. Its owners, however, are not changed.

If neither the SWP_NOACTIVATE nor SWP_NOZORDER flag is specified (that is, when the application requests that a window be simultaneously activated and its position in the Z order changed), the value specified in hWndInsertAfter is used only in the following circumstances:

  • Neither the HWND_TOPMOST nor HWND_NOTOPMOST flag is specified in hWndInsertAfter.
  • The window identified by hWnd is not the active window.

An application cannot activate an inactive window without also bringing it to the top of the Z order. Applications can change an activated window's position in the Z order without restrictions, or it can activate a window and then move it to the top of the topmost or non-topmost windows.

If a topmost window is repositioned to the bottom (HWND_BOTTOM) of the Z order or after any non-topmost window, it is no longer topmost. When a topmost window is made non-topmost, its owners and its owned windows are also made non-topmost windows.

A non-topmost window can own a topmost window, but the reverse cannot occur. Any window (for example, a dialog box) owned by a topmost window is itself made a topmost window, to ensure that all owned windows stay above their owner.

If an application is not in the foreground, and should be in the foreground, it must call the SetForegroundWindow function.

Windows CE: If this is a visible top-level window, and the SWP_NOACTIVATE flag is not specified, this function will activate the window. If this is the currently active window, and either the SWP_NOACTIVATE flag or the SWP_HIDEWINDOW flag is specified, the activation is passed on to another visible top-level window.

When you set the SWP_FRAMECHANGED flag in the nFlags parameter to this function, Windows CE redraws the entire non-client area of the window, which may change the size of the client area. This is the only way to get the non-client area to be recalculated and is typically used after a you've changed the window style by calling SetWindowLong.

SetWindowPos will always cause a WM_WINDOWPOSCHANGED message to be sent to the window. The flags passed in this message are exactly the same as those passed into the function. No other messages are sent by this function.

Windows CE 1.0 does not support the HWND_TOPMOST and HWND_NOTOPMOST constants in the hwndInsertAfter parameter.

Windows CE 1.0 does not support the SWP_DRAWFRAME or SWP_NOCOPYBITS flags in the fuFlags paramete.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, MoveWindow, SetActiveWindow, SetForegroundWindow


SetWindowText

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,         // handle to window or control
  LPCTSTR lpString   // address of string
);

Parameters

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 Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

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.

The SetWindowText function does not expand tab characters (ASCII code 0x09). Tab characters are displayed as vertical bar (|) characters.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.

See Also

Windows Overview, Window Functions, GetWindowText, WM_SETTEXT


ShowOwnedPopups

The ShowOwnedPopups function shows or hides all pop-up windows owned by the specified window.

BOOL ShowOwnedPopups(
  HWND hWnd,  // handle to window
  BOOL fShow  // window visibility flag
);

Parameters

hWnd
Handle to the window that owns the pop-up windows to be shown or hidden.
fShow
Specifies whether pop-up windows are to be shown or hidden. If this parameter is TRUE, all hidden pop-up windows are shown. If this parameter is FALSE, all visible pop-up windows are hidden.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

ShowOwnedPopups shows only windows hidden by a previous call to ShowOwnedPopups. For example, if a pop-up window is hidden by using the ShowWindow function, subsequently calling ShowOwnedPopups with the fShow parameter set to TRUE does not cause the window to be shown.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, IsWindowVisible, ShowWindow


ShowWindow

The ShowWindow function sets the specified window's show state.

BOOL ShowWindow(
  HWND hWnd,     // handle to window
  int nCmdShow   // show state of window
);

Parameters

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:
Value | Meaning
SW_FORCEMINIMIZE | Windows NT 5.0 and later: Minimizes a window, even if the thread that owns the window is hung. This flag should only be used when minimizing windows from a different thread.
SW_HIDE | Hides the window and activates another window.
SW_MAXIMIZE | Maximizes the specified window.
SW_MINIMIZE | Minimizes the specified window and activates the next top-level 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_ flag 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. The active window remains active.
SW_SHOWNA | Displays the window in its current state. The active window remains active.
SW_SHOWNOACTIVATE | Displays a window in its most recent size and position. The active window remains active.
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 Values

If the window was previously visible, the return value is nonzero.

If the window was previously hidden, the return value is zero.

Remarks

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.

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 STARTUPINFO 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.

Windows CE: The nCmdShow parameter does not support the following values:

SW_MAXIMIZE

SW_MINIMIZE

SW_RESTORE

SW_SHOWDEFAULT

SW_SHOWMAXIMIZED

SW_SHOWMINIMIZED

SW_SHOWMINNOACTIVE

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, CreateProcess, CreateWindow, ShowOwnedPopups, STARTUPINFO, WinMain


ShowWindowAsync

The ShowWindowAsync function sets the show state of a window created by a different thread.

BOOL ShowWindowAsync(
  HWND hWnd,    // handle to window
  int nCmdShow  // show state of window
);

Parameters

hWnd
Handle to the window.
nCmdShow
Specifies how the window is to be shown. For a list of possible values, see the description of the ShowWindow function.

Return Values

If the window was previously visible, the return value is nonzero.

If the window was previously hidden, the return value is zero.

Remarks

This function posts a show-window event to the message queue of the given window. An application can use this function to avoid becoming hung while waiting for a hung application to finish processing a show-window event.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, ShowWindow


TileWindows

The TileWindows function tiles the specified child windows of the specified parent window.

WORD WINAPI TileWindows(
  HWND hwndParent,        // handle to parent window
  UINT wHow,              // types of windows not to arrange
  CONST RECT *lpRect,     // rectangle to arrange windows in
  UINT cKids,             // number of windows to arrange
  const HWND FAR *lpKids  // array of window handles
);

Parameters

hwndParent
Handle to the parent window. If this parameter is NULL, the desktop window is assumed.
wHow
Specifies the types of windows not to arrange, and whether to tile vertically or horizontally. This parameter can be one of the following values, optionally combined with MDITILE_SKIPDISABLED to prevent disabled MDI child windows from being tiled:
Value | Meaning
MDITILE_HORIZONTAL | Tiles windows horizontally.
MDITILE_VERTICAL | Tiles windows vertically.

lpRect
Pointer to a RECT structure that specifies the rectangular area, in client coordinates, within which the windows are arranged. If this parameter is NULL, the client area of the parent window is used.
cKids
Specifies the number of elements in the array specified by the lpKids parameter. This parameter is ignored if lpKids is NULL.
lpKids
Pointer to an array of handles to the child windows to arrange. If this parameter is NULL, all child windows of the specified parent window (or of the desktop window) are arranged.

Return Values

If the function succeeds, the return value is the number of windows arranged.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Calling TileWindows causes all maximized windows to be restored to their previous size.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, CascadeWindows, RECT


WindowFromPoint

The WindowFromPoint function retrieves a handle to the window that contains the specified point.

HWND WindowFromPoint(
  POINT Point   // structure with point
);

Parameters

Point
Specifies a POINT structure that defines the point to be checked.

Return Values

The return value is a handle to the window that contains the point. If no window exists at the given point, the return value is NULL. If the point is over a static text control, the return value is a handle to the window under the static text control.

Remarks

The WindowFromPoint function does not retrieve a handle to a hidden or disabled window, even if the point is within the window. An application should use the ChildWindowFromPoint function for a nonrestrictive search.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.

See Also

Windows Overview, Window Functions, ChildWindowFromPoint, POINT, WindowFromDC


WinMain

The WinMain function is called by the system as the initial entry point for a Win32-based application.

int WINAPI WinMain(
  HINSTANCE hInstance,  // handle to current instance
  HINSTANCE hPrevInstance,  // handle to previous instance
  LPSTR lpCmdLine,      // pointer to command line
  int nCmdShow          // show state of window
);

Parameters

hInstance
Handle to the current instance of the application.
hPrevInstance
Handle to the previous instance of the application. For a Win32-based application, this parameter is always NULL.

If you need to detect whether another instance already exists, create a uniquely named mutex using the CreateMutex function. CreateMutex will succeed even if the mutex already exists, but the GetLastError function will return ERROR_ALREADY_EXISTS. This indicates that another instance of your application exists, because it created the mutex first.

lpCmdLine
Pointer to a null-terminated string specifying the command line for the application, excluding the program name. To retrieve the entire command line, use the GetCommandLine function.
nCmdShow
Specifies how the window is to be shown. This parameter can be one of the following values:
Value | Meaning
SW_HIDE | Hides the window and activates another window.
SW_MINIMIZE | Minimizes the specified window and activates the top-level window in the system's list.
SW_RESTORE | Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position (same as SW_SHOWNORMAL).
SW_SHOW | Activates a window and displays it in its current size and position.
SW_SHOWMAXIMIZED | Activates a window and displays it as a maximized window.
SW_SHOWMINIMIZED | Activates a window and displays it as an icon.
SW_SHOWMINNOACTIVE | Displays a window as an icon. The active window remains active.
SW_SHOWNA | Displays a window in its current state. The active window remains active.
SW_SHOWNOACTIVATE | Displays a window in its most recent size and position. The active window remains active.
SW_SHOWNORMAL | Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position (same as SW_RESTORE).

Return Values

If the function succeeds, terminating when it receives a WM_QUIT message, it should return the exit value contained in that message's wParam parameter. If the function terminates before entering the message loop, it should return zero.

Remarks

Your WinMain should initialize the application, display its main window, and enter a message retrieval-and-dispatch loop that is the top-level control structure for the remainder of the application's execution. Terminate the message loop when it receives a WM_QUIT message. At that point, your WinMain should exit the application, returning the value passed in the WM_QUIT message's wParam parameter. If WM_QUIT was received as a result of calling PostQuitMessage, the value of wParam is the value of the PostQuitMessage function's nExitCode parameter. For more information, see Creating a Message Loop.

ANSI applications can use the lpCmdLine parameter of the WinMain function to access the command-line string, excluding the program name. The reason that WinMain cannot return Unicode strings is that lpCmdLine uses the LPSTR data type, not the LPTSTR data type. The GetCommandLine function can be used to access Unicode strings in the command line, because it uses the LPTSTR data type.

Windows CE: Windows CE does not support the following values for the nCmdShow parameter:

SW_MINIMIZE

SW_RESTORE

SW_SHOWMAXIMIZED

SW_SHOWMINIMIZED

SW_SHOWMINNOACTIVE

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winbase.h.
Import Library: User-defined.

See Also

Windows Overview, Window Functions, CreateMutex, DispatchMessage, GetCommandLine, GetMessage, PostQuitMessage, TranslateMessage


Window Structures

The following structures are used to create and manage windows.

CLIENTCREATESTRUCT
CREATESTRUCT
MINMAXINFO
NCCALCSIZE_PARAMS
STYLESTRUCT
WINDOWPLACEMENT
WINDOWPOS


CLIENTCREATESTRUCT

The CLIENTCREATESTRUCT structure contains information about the menu and first multiple document interface (MDI) child window of an MDI client window. An application passes a pointer to this structure as the lpvParam parameter of the CreateWindow function when creating an MDI client window.

typedef struct tagCLIENTCREATESTRUCT { // ccs
    HANDLE hWindowMenu;
    UINT   idFirstChild;
} CLIENTCREATESTRUCT;

Members

hWindowMenu
Handle to the MDI application's window menu. An MDI application can retrieve this handle from the menu of the MDI frame window by using the GetSubMenu function.
idFirstChild
Specifies the child window identifier of the first MDI child window created. The system increments the identifier for each additional MDI child window the application creates, and reassigns identifiers when the application destroys a window to keep the range of identifiers contiguous. These identifiers are used in WM_COMMAND messages sent to the application's MDI frame window when a child window is chosen from the window menu; they should not conflict with any other command identifiers.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Structures, CreateWindow, GetSubMenu, MDICREATESTRUCT, WM_COMMAND


CREATESTRUCT

The CREATESTRUCT structure defines the initialization parameters passed to the window procedure of an application.

typedef struct tagCREATESTRUCT { // cs
    LPVOID    lpCreateParams;
    HINSTANCE hInstance;
    HMENU     hMenu;
    HWND      hwndParent;
    int       cy;
    int       cx;
    int       y;
    int       x;
    LONG      style;
    LPCTSTR   lpszName;
    LPCTSTR   lpszClass;
    DWORD     dwExStyle;
} CREATESTRUCT;

Members

lpCreateParams
Contains additional data which may be used to create the window. If the window is being created as a result of a call to the CreateWindow or CreateWindowEx function, this member contains the value of the lpParam parameter specified in the function call.

If the window being created is an MDI window, this member contains a pointer to an MDICREATESTRUCT structure.

Windows NT: If the window is being created from a dialog template, this member is the address of a SHORT value that specifies the size, in bytes, of the window creation data. The value is immediately followed by the creation data. For more information, see the following Remarks section.

hInstance
Handle to the module that owns the new window.
hMenu
Handle to the menu to be used by the new window.
hwndParent
Handle to the parent window, if the window is a child window. If the window is owned, this member identifies the owner window. If the window is not a child or owned window, this member is NULL.
cy
Specifies the height of the new window, in pixels.
cx
Specifies the width of the new window, in pixels.
y
Specifies the y-coordinate of the upper left corner of the new window. If the new window is a child window, coordinates are relative to the parent window. Otherwise, the coordinates are relative to the screen origin.
x
Specifies the x-coordinate of the upper left corner of the new window. If the new window is a child window, coordinates are relative to the parent window. Otherwise, the coordinates are relative to the screen origin.
style
Specifies the style for the new window.
lpszName
Pointer to a null-terminated string that specifies the name of the new window.
lpszClass
Pointer to a null-terminated string that specifies the class name of the new window.
dwExStyle
Specifies the extended style for the new window.

Remarks

Windows NT: You should access the data represented by the lpCreateParams member using a pointer that has been declared using the UNALIGNED type, because the pointer may not be DWORD aligned. This is demonstrated in the following example:

typedef struct tagMyData
{
    // Define creation data here.
} MYDATA;

typedef struct tagMyDlgData
{
    SHORT   cbExtra;
    MYDATA  myData;
} MYDLGDATA, UNALIGNED *PMYDLGDATA;

PMYDLGDATA pMyDlgdata =
    (PMYDLGDATA) (((LPCREATESTRUCT) lParam)->lpCreateParams);

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Unicode: Defined as Unicode and ANSI structures.

See Also

Windows Overview, Window Structures, CreateWindow, CreateWindowEx, MDICREATESTRUCT


MINMAXINFO

The MINMAXINFO structure contains information about a window's maximized size and position and its minimum and maximum tracking size.

typedef struct tagMINMAXINFO {  // mmi
    POINT ptReserved;
    POINT ptMaxSize;
    POINT ptMaxPosition;
    POINT ptMinTrackSize;
    POINT ptMaxTrackSize;
} MINMAXINFO;

Members

ptReserved
Reserved; do not use.
ptMaxSize
Specifies the maximized width (point.x) and the maximized height (point.y) of the window.
ptMaxPosition
Specifies the position of the left side of the maximized window (point.x) and the position of the top of the maximized window (point.y).
ptMinTrackSize
Specifies the minimum tracking width (point.x) and the minimum tracking height (point.y) of the window.
ptMaxTrackSize
Specifies the maximum tracking width (point.x) and the maximum tracking height (point.y) of the window.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Structures, POINT, WM_GETMINMAXINFO


NCCALCSIZE_PARAMS

The NCCALCSIZE_PARAMS structure contains information that an application can use while processing the WM_NCCALCSIZE message to calculate the size, position, and valid contents of the client area of a window.

typedef struct _NCCALCSIZE_PARAMS { // nccp
    RECT        rgrc[3];
    PWINDOWPOS  lppos;
} NCCALCSIZE_PARAMS;

Members

rgrc
Specifies an array of rectangles. The first contains the new coordinates of a window that has been moved or resized. The second contains the coordinates of the window before it was moved or resized. The third contains the coordinates of the window's client area before the window was moved or resized. If the window is a child window, the coordinates are relative to the client area of the parent window. If the window is a top-level window, the coordinates are relative to the screen origin.
lppos
Pointer to a WINDOWPOS structure that contains the size and position values specified in the operation that moved or resized the window.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Structures, MoveWindow, RECT, SetWindowPos, WINDOWPOS, WM_NCCALCSIZE


STYLESTRUCT

The STYLESTRUCT structure contains the window styles for a window.

typedef struct tagSTYLESTRUCT {  // ss
    DWORD styleOld;
    DWORD styleNew;
} STYLESTRUCT, * LPSTYLESTRUCT;

Members

style
Specifies an array of window style or extended-style flags.

QuickInfo

Windows NT: Requires version 3.5 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Structures, WM_STYLECHANGED, WM_STYLECHANGING


WINDOWPLACEMENT

The WINDOWPLACEMENT structure contains information about the placement of a window on the screen.

typedef struct _WINDOWPLACEMENT {
    UINT  length;
    UINT  flags;
    UINT  showCmd;
    POINT ptMinPosition;
    POINT ptMaxPosition;
    RECT  rcNormalPosition;
} WINDOWPLACEMENT;

Members

length
Specifies the length, in bytes, of the structure. Before calling the GetWindowPlacement or SetWindowPlacement functions, set this member to sizeof(WINDOWPLACEMENT).

GetWindowPlacement and SetWindowPlacement fail if this member is not set correctly.

flags
Specifies flags that control the position of the minimized window and the method by which the window is restored. This member can be one or both of the following values:
Value Meaning
WPF_RESTORETOMAXIMIZED
Specifies that the restored window will be maximized, regardless of whether it was maximized before it was minimized. This setting is only valid the next time the window is restored. It does not change the default restoration behavior. This flag is only valid when the SW_SHOWMINIMIZED value is specified for the showCmd member.
WPF_SETMINPOSITION
Specifies that the coordinates of the minimized window may be specified. This flag must be specified if the coordinates are set in the ptMinPosition member.

showCmd
Specifies the current show state of the window. This member can be one of the following values:
Value | Meaning
SW_HIDE | Hides the window and activates another window.
SW_MINIMIZE | Minimizes the specified window and activates the top-level window in the system's list.
SW_RESTORE | Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position (same as SW_SHOWNORMAL).
SW_SHOW | Activates a window and displays it in its current size and position.
SW_SHOWMAXIMIZED | Activates a window and displays it as a maximized window.
SW_SHOWMINIMIZED | Activates a window and displays it as an icon.
SW_SHOWMINNOACTIVE | Displays a window as an icon. The active window remains active.
SW_SHOWNA | Displays a window in its current state. The active window remains active.
SW_SHOWNOACTIVATE | Displays a window in its most recent size and position. The active window remains active.
SW_SHOWNORMAL | Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position (same as SW_RESTORE).

ptMinPosition
Specifies the coordinates of the window's upper-left corner when the window is minimized.
ptMaxPosition
Specifies the coordinates of the window's upper-left corner when the window is maximized.
rcNormalPosition
Specifies the window's coordinates when the window is in the restored position.

Remarks

If the window is a top-level window that does not have the WS_EX_TOOLWINDOW window style, then the coordinates represented by the following members are in workspace coordinates: ptMinPosition, ptMaxPosition, and rcNormalPosition. Otherwise, these members are in screen coordinates.

Workspace coordinates differ from screen coordinates in that they take the locations and sizes of appbars (including the taskbar) into account. Workspace coordinate (0,0) is the upper-left corner of the "workspace area", the area of the screen not being used by appbars.

The coordinates used in a WINDOWPLACEMENT structure should be used only by the GetWindowPlacement and SetWindowPlacement functions. Passing workspace coordinates to functions which expect screen coordinates (such as SetWindowPos) will result in the window appearing in the wrong location. For example, if the taskbar is at the top of the screen, saving window coordinates using GetWindowPlacement and restoring them using SetWindowPos causes the window to appear to "creep" up the screen.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Structures, GetWindowPlacement, SetWindowPlacement, SetWindowPos, ShowWindow, POINT, RECT


WINDOWPOS

The WINDOWPOS structure contains information about the size and position of a window.

typedef struct _WINDOWPOS { // wp
    HWND hwnd;
    HWND hwndInsertAfter;
    int  x;
    int  y;
    int  cx;
    int  cy;
    UINT flags;
} WINDOWPOS;

Members

hwnd
Handle to the window.
hwndInsertAfter
Specifies the position of the window in Z order (front-to-back position). This member can be a handle to the window behind which this window is placed, or can be one of the special values listed with the SetWindowPos function.
x
Specifies the position of the left edge of the window.
y
Specifies the position of the top edge of the window.
cx
Specifies the window width, in pixels.
cy
Specifies the window height, in pixels.
flags
Specifies the window position. This member can be one of the following values:
Value | Meaning
SWP_DRAWFRAME | Draws a frame (defined in the window's class description) around the window.
SWP_FRAMECHANGED | Sends a WM_NCCALCSIZE message to the window, even if the window's size is not being changed. If this flag is not specified, WM_NCCALCSIZE is sent only when the window's size is being changed.
SWP_HIDEWINDOW | Hides the window.
SWP_NOACTIVATE | Does not activate the window. If this flag is not set, the window is activated and moved to the top of either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter parameter).
SWP_NOCOPYBITS | Discards the entire contents of the client area. If this flag is not specified, the valid contents of the client area are saved and copied back into the client area after the window is sized or repositioned.
SWP_NOMOVE | Retains the current position (ignores the X and Y parameters).
SWP_NOOWNERZORDER | Does not change the owner window's position in the Z order.
SWP_NOREDRAW | Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent window uncovered as a result of the window being moved. When this flag is set, the application must explicitly invalidate or redraw any parts of the window and parent window that need redrawing.
SWP_NOREPOSITION | Same as the SWP_NOOWNERZORDER flag.
SWP_NOSENDCHANGING | Prevents the window from receiving the WM_WINDOWPOSCHANGING message.
SWP_NOSIZE | Retains the current size (ignores the cx and cy parameters).
SWP_NOZORDER | Retains the current Z order (ignores the hWndInsertAfter parameter).
SWP_SHOWWINDOW | Displays the window.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Structures, EndDeferWindowPos, SetWindowPos, WM_NCCALCSIZE


Window Messages

The following messages are used to create and manage windows.

WM_ACTIVATE
WM_ACTIVATEAPP
WM_CANCELMODE
WM_CHILDACTIVATE
WM_CLOSE
WM_COMPACTING
WM_CREATE
WM_DESTROY
WM_ENABLE
WM_ENTERSIZEMOVE
WM_EXITSIZEMOVE
WM_GETICON
WM_GETMINMAXINFO
WM_GETTEXT
WM_GETTEXTLENGTH
WM_INPUTLANGCHANGE
WM_INPUTLANGCHANGEREQUEST
WM_MOVE
WM_MOVING
WM_NCACTIVATE
WM_NCCALCSIZE
WM_NCCREATE
WM_NCDESTROY
WM_PARENTNOTIFY
WM_QUERYDRAGICON
WM_QUERYOPEN
WM_QUIT
WM_SETICON
WM_SETTEXT
WM_SETTINGCHANGE
WM_SHOWWINDOW
WM_SIZE
WM_SIZING
WM_STYLECHANGED
WM_STYLECHANGING
WM_USERCHANGED
WM_WINDOWPOSCHANGED
WM_WINDOWPOSCHANGING
WM_WININICHANGE


WM_ACTIVATEAPP

The WM_ACTIVATEAPP message is sent when a window belonging to a different application than the active window is about to be activated. The message is sent to the application whose window is being activated and to the application whose window is being deactivated.

WM_ACTIVATEAPP
fActive = (BOOL) wParam;        // activation flag
dwThreadID = (DWORD) lParam:    // thread identifier

Parameters

fActive
Value of wParam. Specifies whether the window is being activated or deactivated. This parameter is TRUE if the window is being activated; it is FALSE if the window is being deactivated.
dwThreadID
Value of lParam. Specifies a thread identifier. If the fActive parameter is TRUE, dwThreadID is the identifier of the thread that owns the window being deactivated. If fActive is FALSE, dwThreadID is the identifier of the thread that owns the window being activated.

Return Values

If an application processes this message, it should return zero.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, WM_ACTIVATE


WM_CANCELMODE

The WM_CANCELMODE message is sent to cancel certain modes, such as mouse capture. For example, the system sends this message to the active window when a dialog box or message box is displayed. Certain functions also send this message explicitly to the specified window regardless of whether it is the active window. For example, the EnableWindow function sends this message when disabling the specified window.

WM_CANCELMODE

Parameters

This message has no parameters.

Return Values

If an application processes this message, it should return zero.

Default Action

The DefWindowProc function cancels internal processing of standard scroll bar input, cancels internal menu processing, and releases the mouse capture.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, DefWindowProc, EnableWindow, ReleaseCapture


WM_CHILDACTIVATE

The WM_CHILDACTIVATE message is sent to a multiple document interface (MDI) child window when the user clicks the window's title bar or when the window is activated, moved, or sized.

WM_CHILDACTIVATE

Parameters

This message has no parameters.

Return Values

If an application processes this message, it should return zero.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, MoveWindow, SetWindowPos


WM_CLOSE

The WM_CLOSE message is sent as a signal that a window or an application should terminate.

WM_CLOSE

Parameters

This message has no parameters.

Return Values

If an application processes this message, it should return zero.

Default Action

The DefWindowProc function calls the DestroyWindow function to destroy the window.

Remarks

An application can prompt the user for confirmation, prior to destroying a window, by processing the WM_CLOSE message and calling the DestroyWindow function only if the user confirms the choice.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, DefWindowProc, DestroyWindow


WM_COMPACTING

The WM_COMPACTING message is sent to all top-level windows when the system detects more than 12.5 percent of system time over a 30- to 60-second interval is being spent compacting memory. This indicates that system memory is low.

WM_COMPACTING
wCompactRatio = wParam; // compacting ratio

Parameters

wCompactRatio
Value of wParam. Specifies the ratio of central processing unit (CPU) time currently spent by the system compacting memory to CPU time currently spent by the system performing other operations. For example, 0x8000 represents 50 percent of CPU time spent compacting memory.

Return Values

If an application processes this message, it should return zero.

Remarks

When an application receives this message, it should free as much memory as possible, taking into account the current level of activity of the application and the total number of applications running on the system.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages


WM_CREATE

The WM_CREATE message is sent when an application requests that a window be created by calling the CreateWindowEx or CreateWindow function. The window procedure of the new window receives this message after the window is created, but before the window becomes visible. The message is sent before the CreateWindowEx or CreateWindow function returns.

WM_CREATE
lpcs = (LPCREATESTRUCT) lParam; // structure with creation data

Parameters

lParam
Value of lParam. Pointer to a CREATESTRUCT structure that contains information about the window being created. The members of CREATESTRUCT are identical to the parameters of the CreateWindowEx function.

Return Values

If an application processes this message, it should return 0 to continue creation of the window. If the application returns –1, the window is destroyed and the CreateWindowEx or CreateWindow function returns a NULL handle.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, CreateWindow, CreateWindowEx, CREATESTRUCT, WM_NCCREATE


WM_DESTROY

The WM_DESTROY message is sent when a window is being destroyed. It is sent to the window procedure of the window being destroyed after the window is removed from the screen.

This message is sent first to the window being destroyed and then to the child windows (if any) as they are destroyed. During the processing of the message, it can be assumed that all child windows still exist.

WM_DESTROY

Parameters

This message has no parameters.

Return Values

If an application processes this message, it should return zero.

Remarks

If the window being destroyed is part of the clipboard viewer chain (set by calling the SetClipboardViewer function), the window must remove itself from the chain by processing the ChangeClipboardChain function before returning from the WM_DESTROY message.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, ChangeClipboardChain, DestroyWindow, PostQuitMessage, SetClipboardViewer, WM_CLOSE


WM_ENABLE

The WM_ENABLE message is sent when an application changes the enabled state of a window. It is sent to the window whose enabled state is changing. This message is sent before the EnableWindow function returns, but after the enabled state (WS_DISABLED style bit) of the window has changed.

WM_ENABLE
fEnabled = (BOOL) wParam;   // enabled/disabled flag

Parameters

fEnabled
Value of wParam. Specifies whether the window has been enabled or disabled. This parameter is TRUE if the window has been enabled or FALSE if the window has been disabled.

Return Values

If an application processes this message, it should return zero.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, EnableWindow


WM_ENTERSIZEMOVE

The WM_ENTERSIZEMOVE message is sent one time to a window after it enters the moving or sizing modal loop. The window enters the moving or sizing modal loop when the user clicks the window's title bar or sizing border, or when the window passes the WM_SYSCOMMAND message to the DefWindowProc function and the wParam parameter of the message specifies the SC_MOVE or SC_SIZE value. The operation is complete when DefWindowProc returns.

The system sends the WM_ENTERSIZEMOVE message regardless of whether the dragging of full windows is enabled.

WM_ENTERSIZEMOVE
wParam = 0;  // not used, must be zero
lParam = 0;  // not used, must be zero

Parameters

This message has no parameters.

Return Values

An application should return zero if it processes this message.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, DefWindowProc, WM_EXITSIZEMOVE, WM_SYSCOMMAND


WM_EXITSIZEMOVE

The WM_EXITSIZEMOVE message is sent one time to a window, after it has exited the moving or sizing modal loop. The window enters the moving or sizing modal loop when the user clicks the window's title bar or sizing border, or when the window passes the WM_SYSCOMMAND message to the DefWindowProc function and the wParam parameter of the message specifies the SC_MOVE or SC_SIZE value. The operation is complete when DefWindowProc returns.

WM_EXITSIZEMOVE
wParam = 0;  // not used; must be zero
lParam = 0;  // not used; must be zero

Parameters

This message has no parameters.

Return Values

An application should return zero if it processes this message.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, DefWindowProc, WM_ENTERSIZEMOVE


WM_GETICON

The WM_GETICON message is sent to a window to retrieve a handle to the large or small icon associated with a window. The system displays the large icon in the Alt+Tab dialog, and the small icon in the window caption.

WM_GETICON
fType = wParam;  // icon type

Parameters

fType
Value of wParam. Specifies the type of icon being retrieved. This parameter can be one of the following values:
Value | Meaning
ICON_BIG | Retrieve the large icon for the window.
ICON_SMALL | Retrieve the small icon for the window.

Return Values

The return value is a handle to the large or small icon, depending on the value of fType. When an application receives this message, it can return a handle to a large or small icon, or pass the message to DefWindowProc.

Default Action

DefWindowProc returns a handle to the large or small icon associated with the window, depending on the value of fType.

Remarks

When an application receives this message, it can return a handle to a large or small icon, or pass the message to DefWindowProc.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, DefWindowProc, WM_SETICON


WM_GETMINMAXINFO

The WM_GETMINMAXINFO message is sent to a window when the size or position of the window is about to change. An application can use this message to override the window's default maximized size and position, or its default minimum or maximum tracking size.

WM_GETMINMAXINFO
lpmmi = (LPMINMAXINFO) lParam; // address of structure

Parameters

lpmmi
Value of lParam. Pointer to a MINMAXINFO structure that contains the default maximized position and dimensions, and the default minimum and maximum tracking sizes. An application can override the defaults by setting the members of this structure.

Return Values

If an application processes this message, it should return zero.

Remarks

The maximum tracking size is the largest window size that can be produced by using the borders to size the window. The minimum tracking size is the smallest window size that can be produced by using the borders to size the window.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, MoveWindow, SetWindowPos, MINMAXINFO


WM_GETTEXT

An application sends a WM_GETTEXT message to copy the text that corresponds to a window into a buffer provided by the caller.

WM_GETTEXT
wParam = (WPARAM) cchTextMax;   // number of characters to copy
lParam = (LPARAM) lpszText;     // address of buffer for text

Parameters

cchTextMax
Value of wParam. Specifies the maximum number of characters to be copied, including the terminating null character.
lpszText
Value of lParam. Pointer to the buffer that is to receive the text.

Return Values

The return value is the number of characters copied.

Default Action

The DefWindowProc function copies the text associated with the window into the specified buffer and returns the number of characters copied.

Remarks

For an edit control, the text to be copied is the content of the edit control. For a combo box, the text is the content of the edit control (or static-text) portion of the combo box. For a button, the text is the button name. For other windows, the text is the window title. To copy the text of an item in a list box, an application can use the LB_GETTEXT message.

When the WM_GETTEXT message is sent to a static control with the SS_ICON style, a handle to the icon will be returned in the first four bytes of the buffer pointed to by lpszText. This is true only if the WM_SETTEXT message has been used to set the icon.

In a rich edit control, if the text to be copied exceeds 64K, use either the message EM_STREAMOUT or EM_GETSELTEXT.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, DefWindowProc, EM_GETSELTEXT, EM_STREAMOUT, GetWindowText, GetWindowTextLength, LB_GETTEXT, WM_GETTEXTLENGTH, WM_SETTEXT


WM_GETTEXTLENGTH

An application sends a WM_GETTEXTLENGTH message to determine the length, in characters, of the text associated with a window. The length does not include the terminating null character.

WM_GETTEXTLENGTH
wParam = 0; // not used; must be zero
lParam = 0; // not used; must be zero

Parameters

This message has no parameters.

Return Values

The return value is the length, in characters, of the text.

Default Action

The DefWindowProc function returns the length, in characters, of the text. Under certain conditions, this value may actually be greater than the length of the text. For more information, see the following Remarks section.

Remarks

For an edit control, the text to be copied is the content of the edit control. For a combo box, the text is the content of the edit control (or static-text) portion of the combo box. For a button, the text is the button name. For other windows, the text is the window title. To determine the length of an item in a list box, an application can use the LB_GETTEXTLEN message.

Under certain conditions, the DefWindowProc function returns a value that is larger than the actual length of the text. This occurs with certain mixtures of ANSI and Unicode, and is due to the system allowing for the possible existence of DBCS characters within the text. The return value, however, will always be at least as large as the actual length of the text; you can thus always use it to guide buffer allocation. This behavior can occur when an application uses both ANSI functions and common dialogs, which use Unicode.

To obtain the exact length of the text, use the WM_GETTEXT, LB_GETTEXT, or CB_GETLBTEXT messages, or the GetWindowText function.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, CB_GETLBTEXT, DefWindowProc, GetWindowText, GetWindowTextLength, LB_GETTEXT, LB_GETTEXTLEN, WM_GETTEXT


WM_INPUTLANGCHANGE

The WM_INPUTLANGCHANGE message is sent to the topmost affected window after an application's input language has been changed. You should make any application-specific settings and pass the message to the DefWindowProc function, which passes the message to all first-level child windows. These child windows can pass the message to DefWindowProc to have it pass the message to their child windows, and so on.

WM_INPUTLANGCHANGE
charset = wParam;
hkl = (HKL) lParam;

Parameters

charset
Specifies the character set of the new keyboard layout.
hkl
Handle to the new keyboard layout.

Return Values

An application should return nonzero if it processes this message.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, DefWindowProc, WM_INPUTLANGCHANGEREQUEST


WM_INPUTLANGCHANGEREQUEST

The WM_INPUTLANGCHANGEREQUEST message is posted to the window with the focus when the user chooses a new input language, either with the hotkey (specified in the Keyboard control panel application) or from the indicator on the system taskbar. An application can accept the change by passing the message to the DefWindowProc function or reject the change (and prevent it from taking place) by returning immediately.

WM_INPUTLANGCHANGEREQUEST
fSysCharSet = (BOOL) wParam
hkl = (HKL) lParam;

Parameters

wParam
The lowest bit of this parameter is set if the handle to the keyboard layout can be used with the system character set. The other bits are reserved.
hkl
Handle to the new keyboard layout.

Return Values

This message is posted, not sent, to the application, so the return value is ignored. To accept the change, the application should pass the message to DefWindowProc. To reject the change, the application should return zero without calling DefWindowProc.

Default Action

When the DefWindowProc function receives the WM_INPUTLANGCHANGEREQUEST message, it activates the new input locale and notifies the application of the change by sending the WM_INPUTLANGCHANGE message.

Remarks

The language indicator is only present on the taskbar if you have installed more than one keyboard layout and if you have enabled the indicator using the Keyboard control panel application.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, DefWindowProc, WM_INPUTLANGCHANGE


WM_MOVE

The WM_MOVE message is sent after a window has been moved.

WM_MOVE
xPos = (int)(short) LOWORD(lParam);    // horizontal position
yPos = (int)(short) HIWORD(lParam);    // vertical position

Parameters

xPos
Value of the low-order word of lParam. Specifies the x-coordinate of the upper-left corner of the client area of the window.
yPos
Value of the high-order word of lParam. Specifies the y-coordinate of the upper-left corner of the client area of the window.

Return Values

If an application processes this message, it should return zero.

Remarks

The xPos and yPos parameters are given in screen coordinates for overlapped and pop-up windows and in parent-client coordinates for child windows.

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, MAKEPOINTS, POINTS


WM_MOVING

The WM_MOVING message is sent to a window that the user is moving. By processing this message, an application can monitor the size and position of the drag rectangle and, if needed, change its size or position.

fwSide = wParam;           // edge of window to be moved
lprc = (LPRECT) lParam;    // screen coordinates of drag rectangle

Parameters

fwSide
Value of wParam. Indicates which edge of the window is being moved. This parameter can be a combination of the following values:
Value | Meaning
WMSZ_BOTTOM | Bottom edge
WMSZ_BOTTOMLEFT | Bottom-left corner
WMSZ_BOTTOMRIGHT | Bottom-right corner
WMSZ_LEFT | Left edge
WMSZ_RIGHT | Right edge
WMSZ_TOP | Top edge
WMSZ_TOPLEFT | Top-left corner
WMSZ_TOPRIGHT | Top-right corner

lprc
Value of lParam. Address of a RECT structure with the screen coordinates of the drag rectangle. To change the size or position of the drag rectangle, an application must change the members of this structure.

Return Values

  • An application should return TRUE if it processes this message.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, RECT, WM_MOVE, WM_SIZING


WM_NCACTIVATE

The WM_NCACTIVATE message is sent to a window when its nonclient area needs to be changed to indicate an active or inactive state.

WM_NCACTIVATE
fActive = (BOOL) wParam;   // new state of the title bar or icon

Parameters

fActive
Value of wParam. Specifies when a title bar or icon needs to be changed to indicate an active or inactive state. If an active title bar or icon is to be drawn, the fActive parameter is TRUE. It is FALSE for an inactive title bar or icon.

Return Values

When the fActive parameter is FALSE, an application should return TRUE to indicate that the system should proceed with the default processing, or it should return FALSE to prevent the title bar or icon from being deactivated. When fActive is TRUE, the return value is ignored.

Default Action

The DefWindowProc function draws the title bar or icon title in its active colors when the fActive parameter is TRUE and in its inactive colors when fActive is FALSE.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, DefWindowProc


WM_NCCALCSIZE

The WM_NCCALCSIZE message is sent when the size and position of a window's client area must be calculated. By processing this message, an application can control the content of the window's client area when the size or position of the window changes.

WM_NCCALCSIZE
fCalcValidRects = (BOOL) wParam;        // valid area flag

lpncsp = (LPNCCALCSIZE_PARAMS) lParam;  // size calculation data

   or

lpncsp = (LPRECT) lParam;               // new window coordinates

Parameters

fCalcValidRects
The value of wParam. If wParam is TRUE, it specifies that the application should indicate which part of the client area contains valid information. The system copies the valid information to the specified area within the new client area.

If wParam is FALSE, the application does not need to indicate the valid part of the client area.

lpncsp
Value of lParam. If wParam is TRUE, lParam points to an NCCALCSIZE_PARAMS structure that contains information an application can use to calculate the new size and position of the client rectangle.

If wParam is FALSE, lParam points to a RECT structure. On entry, the structure contains the proposed window rectangle for the window. On exit, the structure should contain the screen coordinates of the corresponding window client area.

Return Values

If the fCalcValidRects parameter is FALSE, the application should return zero.

If fCalcValidRects is TRUE, the application should return zero or a combination of the following values:

Value | Meaning
WVR_ALIGNTOP, WVR_ALIGNLEFT, WVR_ALIGNBOTTOM, WVR_ALIGNRIGHT
 | These values, used in combination, specify that the client area of the window is to be preserved and aligned appropriately relative to the new position of the window. For example, to align the client area to the lower-left corner, return the WVR_ALIGNLEFT and WVR_ALIGNBOTTOM values.
WVR_HREDRAW, WVR_VREDRAW
 | These values, used in combination with any other values, cause the window to be completely redrawn if the client rectangle changes size horizontally or vertically. These values are similar to the CS_HREDRAW and CS_VREDRAW class styles.
WVR_REDRAW
 | This value causes the entire window to be redrawn. It is a combination of WVR_HREDRAW and WVR_VREDRAW values.
WVR_VALIDRECTS
 | This value indicates that, upon return from WM_NCCALCSIZE, the rectangles specified by the rgrc[1] and rgrc[2] members of the NCCALCSIZE_PARAMS structure contain valid destination and source area rectangles, respectively. The system combines these rectangles to calculate the area of the window to be preserved. The system copies any part of the window image that is within the source rectangle and clips the image to the destination rectangle. Both rectangles are in parent-relative or screen-relative coordinates.
 | This return value allows an application to implement more elaborate client-area preservation strategies, such as centering or preserving a subset of the client area.

If fCalcValidRects is TRUE and an application returns zero, the old client area is preserved and is aligned with the upper-left corner of the new client area.

Default Action

The window may be redrawn, depending on whether the CS_HREDRAW or CS_VREDRAW class style is specified. This is the default, backward-compatible processing of this message by the DefWindowProc function (in addition to the usual client rectangle calculation described in the preceding table).

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, DefWindowProc, MoveWindow, SetWindowPos, NCCALCSIZE_PARAMS, RECT


WM_NCCREATE

The WM_NCCREATE message is sent prior to the WM_CREATE message when a window is first created.

WM_NCCREATE
lpcs = (LPCREATESTRUCT) lParam;  // structure with creation data

Parameters

lpcs
Value of lParam. Pointer to the CREATESTRUCT structure that contains information about the window being created. The members of CREATESTRUCT are identical to the parameters of the CreateWindowEx function. .

Return Values

If an application processes this message, it should return TRUE to continue creation of the window. If the application returns FALSE, the CreateWindow or CreateWindowEx function will return a NULL handle.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, CreateWindow, CreateWindowEx, DefWindowProc, CREATESTRUCT, WM_CREATE


WM_NCDESTROY

The WM_NCDESTROY message informs a window that its nonclient area is being destroyed. The DestroyWindow function sends the WM_NCDESTROY message to the window following the WM_DESTROY message. WM_DESTROY is used to free the allocated memory object associated with the window.

WM_NCDESTROY

Parameters

This message has no parameters.

Return Values

If an application processes this message, it should return zero.

Remarks

This message frees any memory internally allocated for the window.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, DestroyWindow, WM_DESTROY, WM_NCCREATE


WM_PARENTNOTIFY

The WM_PARENTNOTIFY message is sent to the parent of a child window when the child window is created or destroyed, or when the user clicks a mouse button while the cursor is over the child window. When the child window is being created, the system sends WM_PARENTNOTIFY just before the CreateWindow or CreateWindowEx function that creates the window returns. When the child window is being destroyed, the system sends the message before any processing to destroy the window takes place.

WM_PARENTNOTIFY
fwEvent = LOWORD(wParam);  // event flags
idChild = HIWORD(wParam);  // identifier of child window
lValue = lParam;           // child handle, or cursor coordinates

Parameters

fwEvent
Value of the low-order word of wParam. Specifies the event for which the parent is being notified. This parameter can be one of the following values:
Value | Meaning
WM_CREATE | The child window is being created.
WM_DESTROY | The child window is being destroyed.
WM_LBUTTONDOWN | The user has placed the cursor over the child window and has clicked the left mouse button.
WM_MBUTTONDOWN | The user has placed the cursor over the child window and has clicked the middle mouse button.
WM_RBUTTONDOWN | The user has placed the cursor over the child window and has clicked the right mouse button.

idChild
Value of the high-order word of wParam. If the fwEvent parameter is the WM_CREATE or WM_DESTROY value, idChild specifies the identifier of the child window. Otherwise, idChild is undefined.
lValue
Contains a handle to the child window, if the fwEvent parameter is the WM_CREATE or WM_DESTROY value; otherwise, lValue contains the x- and y-coordinates of the cursor. The x-coordinate is in the low-order word and the y-coordinate is in the high-order word.

Return Values

If an application processes this message, it should return zero.

Remarks

This message is also sent to all ancestor windows of the child window, including the top-level window.

All child windows, except those that have the WS_EX_NOPARENTNOTIFY extended window style, send this message to their parent windows. By default, child windows in a dialog box have the WS_EX_NOPARENTNOTIFY style, unless the CreateWindowEx function is called to create the child window without this style.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, CreateWindow, CreateWindowEx, WM_CREATE, WM_DESTROY, WM_LBUTTONDOWN, WM_MBUTTONDOWN, WM_RBUTTONDOWN


WM_QUERYDRAGICON

The WM_QUERYDRAGICON message is sent to a minimized (iconic) window. The window is about to be dragged by the user but does not have an icon defined for its class. An application can return a handle to an icon or cursor. The system displays this cursor or icon while the user drags the icon.

WM_QUERYDRAGICON

Parameters

This message has no parameters.

Return Values

An application should return a handle to a cursor or icon that the system is to display while the user drags the icon. The cursor or icon must be compatible with the display driver's resolution. If the application returns NULL, the system displays the default cursor.

Default Action

The DefWindowProc function returns a handle to the default cursor.

Remarks

When the user drags the icon of a window without a class icon, the system replaces the icon with a default cursor. If the application requires a different cursor to be displayed during dragging, it must return a handle to the cursor or icon compatible with the display driver's resolution. If an application returns a handle to a color cursor or icon, the system converts the cursor or icon to black and white. The application can call the LoadCursor or LoadIcon function to load a cursor or icon from the resources in its executable (.EXE) file and to retrieve this handle.

If a dialog box procedure handles this message, it should cast the desired return value to a BOOL and return the value directly. The DWL_MSGRESULT value set by the SetWindowLong function is ignored.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, DefWindowProc, LoadCursor, LoadIcon


WM_QUERYOPEN

The WM_QUERYOPEN message is sent to an icon when the user requests that the window be restored to its previous size and position.

WM_QUERYOPEN

Parameters

This message has no parameters.

Return Values

If the icon can be opened, an application that processes this message should return TRUE; otherwise, it should return FALSE to prevent the icon from being opened.

Default Action

The DefWindowProc function returns TRUE.

Remarks

While processing this message, the application should not perform any action that would cause an activation or focus change (for example, creating a dialog box).

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, DefWindowProc


WM_QUIT

The WM_QUIT message indicates a request to terminate an application and is generated when the application calls the PostQuitMessage function. It causes the GetMessage function to return zero.

WM_QUIT
nExitCode = (int) wParam;   // exit code

Parameters

nExitCode
Value of wParam. Specifies the exit code given in the PostQuitMessage function.

Return Values

This message does not have a return value, because it causes the message loop to terminate before the message is sent to the application's window procedure.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, GetMessage, PostQuitMessage


WM_SETICON

An application sends the WM_SETICON message to associate a new large or small icon with a window. The system displays the large icon in the ALT+TAB dialog, and the small icon in the window caption.

WM_SETICON
wParam = (WPARAM) fType;          // icon type
lParam = (LPARAM) (HICON) hicon;  // handle to icon

Parameters

fType
Value of wParam. Specifies the type of icon being set. This parameter can be one of the following values:
Value | Meaning
ICON_BIG | Set the large icon for the window.
ICON_SMALL | Set the small icon for the window.
hicon
Value of lParam. Handle to the new large or small icon. If this parameter is NULL, the icon indicated by fType is removed.

Return Values

The return value is a handle to the previous large or small icon, depending on the value of fType. It is NULL if the window previously had no icon of the type indicated by fType.

Default Action

The DefWindowProc function returns a handle to the previous large or small icon associated with the window, depending on the value of fType.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, DefWindowProc, WM_GETICON


WM_SETTEXT

An application sends a WM_SETTEXT message to set the text of a window.

WM_SETTEXT
wParam = 0;                     // not used; must be zero
lParam = (LPARAM)(LPCTSTR)lpsz; // address of window-text string

Parameters

lpsz
Value of lParam. Pointer to a null-terminated string that is the window text.

Return Values

The return value is TRUE if the text is set. It is FALSE (for an edit control), LB_ERRSPACE (for a list box), or CB_ERRSPACE (for a combo box) if insufficient space is available to set the text in the edit control. It is CB_ERR if this message is sent to a combo box without an edit control.

Default Action

The DefWindowProc function sets and displays the window text.

Remarks

For an edit control, the text is the contents of the edit control. For a combo box, the text is the contents of the edit-control portion of the combo box. For a button, the text is the button name. For other windows, the text is the window title.

This message does not change the current selection in the list box of a combo box. An application should use the CB_SELECTSTRING message to select the item in a list box that matches the text in the edit control.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, DefWindowProc, CB_SELECTSTRING, WM_GETTEXT


WM_SETTINGCHANGE

The system sends the WM_SETTINGCHANGE message to all top-level windows when the SystemParametersInfo function changes a system-wide setting. The system sends this message only if the SystemParametersInfo caller specifies the SPIF_SENDCHANGE flag.

An application can send WM_SETTINGCHANGE to all top-level windows when it makes changes to system parameters. For example, you can send this message after a call to the WriteProfileString, WriteProfileSection, or SetLocaleInfo functions, or after making changes to system parameters in the registry.

The WM_SETTINGCHANGE message is the same as the older WM_WININICHANGE message.

WM_SETTINGCHANGE
wParam = wFlag;                         // system-wide parameter flag
lParam = (LPARAM) (LPCTSTR) pszSection; // name of changed section or registry

Parameters

wFlag
Value of wParam. When the system sends the message as a result of a SystemParametersInfo call, this parameter is a flag that indicates the system parameter that was changed. For a list of values, see the SystemParametersInfo function.

When an application sends the message, this parameter must be NULL.

pszMetrics
Value of lParam. Pointer to a string that indicates the area containing the system parameter that was changed. For example, this string can be the name of a registry key or the name of a section in the WIN.INI file.

This parameter is not particularly useful in determining which system parameter changed. For example, when the string is a registry name, it typically indicates only the leaf node in the registry, not the whole path. In addition, some applications send this message with lParam set to NULL. In general, when you receive this message, you should check and reload any system parameter settings that are used by your application.

Return Values

If you process this message, return zero.

Remarks

To send the WM_SETTINGCHANGE message to all top-level windows, use the SendMessageTimeout function with the hwnd parameter set to HWND_BROADCAST.

Calls to functions that change the WIN.INI file might be mapped to the registry instead. This mapping occurs when the WIN.INI file and the section being changed are specified in the registry under the following keys:

HKEY_LOCAL_MACHINE\Software\Microsoft\
Windows NT\CurrentVersion\IniFileMapping

The change in the storage location has no effect on the behavior of this message.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, SendMessageTimeout, SetLocaleInfo, SystemParametersInfo, WM_WININICHANGE, WriteProfileSection, WriteProfileString


WM_SHOWWINDOW

The WM_SHOWWINDOW message is sent to a window when the window is about to be hidden or shown.

WM_SHOWWINDOW
fShow = (BOOL) wParam;      // show/hide flag
fnStatus = (int) lParam;    // status flag

Parameters

fShow
Value of wParam. Specifies whether a window is being shown. It is TRUE if the window is being shown or FALSE if the window is being hidden.
fnStatus
Value of lParam. Specifies the status of the window being shown. The fnStatus parameter is zero if the message is sent because of a call to the ShowWindow function; otherwise, fnStatus is one of the following values:
Value | Meaning
SW_OTHERUNZOOM | The window is being uncovered because a maximize window was restored or minimized.
SW_OTHERZOOM | The window is being covered by another window that has been maximized.
SW_PARENTCLOSING | The window's owner window is being minimized.
SW_PARENTOPENING | The window's owner window is being restored.

Return Values

If an application processes this message, it should return zero.

Default Action

The DefWindowProc function hides or shows the window, as specified by the message.

Remarks

If a window has the WS_VISIBLE style when it is created, the window receives this message after it is created, but before it is displayed. A window also receives this message when its visibility state is changed by the ShowWindow or ShowOwnedPopups function.

The WM_SHOWWINDOW message is not sent under the following circumstances:

  • When a top-level, overlapped window is created with the WS_MAXIMIZE or WS_MINIMIZE style.
  • When the SW_SHOWNORMAL flag is specified in the call to the ShowWindow function.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 2.0 or later.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, DefWindowProc, ShowOwnedPopups, ShowWindow


WM_SIZE

The WM_SIZE message is sent to a window after its size has changed.

WM_SIZE
fwSizeType = wParam;      // resizing flag
nWidth = LOWORD(lParam);  // width of client area
nHeight = HIWORD(lParam); // height of client area

Parameters

fwSizeType
Value of wParam. Specifies the type of resizing requested. This parameter can be one of the following values:
Value | Meaning
SIZE_MAXHIDE | Message is sent to all pop-up windows when some other window is maximized.
SIZE_MAXIMIZED | The window has been maximized.
SIZE_MAXSHOW | Message is sent to all pop-up windows when some other window has been restored to its former size.
SIZE_MINIMIZED | The window has been minimized.
SIZE_RESTORED | The window has been resized, but neither the SIZE_MINIMIZED nor SIZE_MAXIMIZED value applies.

nWidth
Value of the low-order word of lParam. Specifies the new width of the client area.
nHeight
Value of the high-order word of lParam. Specifies the new height of the client area.

Return Values

If an application processes this message, it should return zero.

Remarks

If the SetScrollPos or MoveWindow function is called for a child window as a result of the WM_SIZE message, the bRedraw parameter should be nonzero to cause the window to be repainted.

Although the width and height of a window are 32-bit values, the nWidth and nHeight parameters of the WM_SIZE message contain only the low-order 16 bits.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, MoveWindow, SetScrollPos


WM_SIZING

The WM_SIZING message is sent to a window that the user is resizing. By processing this message, an application can monitor the size and position of the drag rectangle and, if needed, change its size or position.

fwSide = wParam;         // edge of window being sized
lprc = (LPRECT) lParam;  // screen coordinates of drag rectangle

Parameters

fwSide
Value of wParam. Indicates which edge of the window is being sized. This parameter can be a combination of the following values:
Value | Meaning
WMSZ_BOTTOM | Bottom edge
WMSZ_BOTTOMLEFT | Bottom-left corner
WMSZ_BOTTOMRIGHT | Bottom-right corner
WMSZ_LEFT | Left edge
WMSZ_RIGHT | Right edge
WMSZ_TOP | Top edge
WMSZ_TOPLEFT | Top-left corner
WMSZ_TOPRIGHT | Top-right corner

lprc
Address of a RECT structure with the screen coordinates of the drag rectangle. To change the size or position of the drag rectangle, an application must change the members of this structure.

Return Values

  • An application should return TRUE if it processes this message.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, RECT, WM_MOVING, WM_SIZE


WM_STYLECHANGED

The WM_STYLECHANGED message is sent to a window after the SetWindowLong function has changed one or more of the window's styles.

WM_STYLECHANGED
wStyleType = wParam;            // windows styles or extended styles
lpss = (LPSTYLESTRUCT) lParam;  // structure containing new styles

Parameters

wStyleType
Value of wParam. Specifies whether the window's styles or extended styles have changed. This parameter can be a combination of the following values:
Value | Meaning
GWL_EXSTYLE | The window's extended styles have changed.
GWL_STYLE | The window's styles have changed.

lpss
Value of lParam. Pointer to a STYLESTRUCT structure that contains the new styles for the window. An application can examine the styles, but can not change them.

Return Values

An application should return zero if it processes this message.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, SetWindowLong, STYLESTRUCT, WM_STYLECHANGING


WM_STYLECHANGING

The WM_STYLECHANGING message is sent to a window when the SetWindowLong function is about to change one or more of the window's styles.

WM_STYLECHANGING
wStyleType = wParam;            // window styles or extended styles
lpss = (LPSTYLESTRUCT) lParam;  // structure containing new styles

Parameters

wStyleType
Value of wParam. Specifies whether the window's styles or extended styles have changed. This parameter can be a combination of the following values:
Value | Meaning
GWL_EXSTYLE | The window's extended styles are changing.
GWL_STYLE | The window's styles are changing.

lpss
Value of lParam. Pointer to a STYLESTRUCT structure that contains the proposed new styles for the window. An application can examine the styles and, if necessary, change them.

Return Values

An application should return zero if it processes this message.

QuickInfo

Windows NT: Requires version 3.51 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, STYLESTRUCT, WM_STYLECHANGED


WM_USERCHANGED

The WM_USERCHANGED message is sent to all windows after the user has logged on or off. When the user logs on or off, the system updates the user-specific settings. The system sends this message immediately after updating the settings.

WM_USERCHANGED
wParam = 0;       // not used, must be zero
lParam = 0;       // not used, must be zero

Return Values

An application should return zero if it processes this message.

QuickInfo

Windows NT: Requires version 4.0 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages


WM_WINDOWPOSCHANGED

The WM_WINDOWPOSCHANGED message is sent to a window whose size, position, or place in the Z order has changed as a result of a call to the SetWindowPos function or another window-management function.

WM_WINDOWPOSCHANGED
lpwp = (LPWINDOWPOS) lParam; // points to size and position data

Parameters

lpwp
Value of lParam. Pointer to a WINDOWPOS structure that contains information about the window's new size and position.

Return Values

If an application processes this message, it should return zero.

Default Action

The DefWindowProc function sends the WM_SIZE and WM_MOVE messages to the window.

Remarks

The WM_SIZE and WM_MOVE messages are not sent if an application handles the WM_WINDOWPOSCHANGED message without calling DefWindowProc. It is more efficient to perform any move or size change processing during the WM_WINDOWPOSCHANGED message without calling DefWindowProc.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, DefWindowProc, EndDeferWindowPos, SetWindowPos, WINDOWPOS, WM_MOVE, WM_SIZE, WM_WINDOWPOSCHANGING


WM_WINDOWPOSCHANGING

The WM_WINDOWPOSCHANGING message is sent to a window whose size, position, or place in the Z order is about to change as a result of a call to the SetWindowPos function or another window-management function.

WM_WINDOWPOSCHANGING
lpwp = (LPWINDOWPOS) lParam; // points to size and position data

Parameters

lpwp
Value of lParam. Pointer to a WINDOWPOS structure that contains information about the window's new size and position.

Return Values

If an application processes this message, it should return zero.

Default Action

For a window with the WS_OVERLAPPED or WS_THICKFRAME style, the DefWindowProc function sends the WM_GETMINMAXINFO message to the window. This is done to validate the new size and position of the window and to enforce the CS_BYTEALIGNCLIENT and CS_BYTEALIGNWINDOW client styles. By not passing the WM_WINDOWPOSCHANGING message to the DefWindowProc function, an application can override these defaults.

Remarks

While this message is being processed, modifying any of the values in WINDOWPOS affects the window's new size, position, or place in the Z order. An application can prevent changes to the window by setting or clearing the appropriate bits in the flags member of WINDOWPOS.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages, DefWindowProc, EndDeferWindowPos, SetWindowPos, WINDOWPOS, WM_GETMINMAXINFO, WM_MOVE, WM_SIZE, WM_WINDOWPOSCHANGED


WM_WININICHANGE

The WM_WININICHANGE message is obsolete. It is included for compatibility with earlier versions of the system. New applications should use the WM_SETTINGCHANGE message.

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Messages


Window Macros

The following macros are used to create and manage windows.

GET_X_LPARAM
GET_Y_LPARAM
HIBYTE
HIWORD
LOBYTE
LOWORD
MAKELONG
MAKELPARAM
MAKELRESULT
MAKEWORD
MAKEWPARAM

See Also

Windows Overview, Window Messages


GET_X_LPARAM

The GET_X_LPARAM macro retrieves the signed x-coordinate from the given LPARAM value.

int GET_X_LPARAM(
  LPARAM lParam  // value from which the signed x-coordinate is retrieved
);

Parameters

lParam
Specifies the value to be converted.

Return Values

The return value is the low-order int of the specified value.

Remarks

The GET_X_LPARAM macro is defined as follows:

#define GET_X_LPARAM(lp)   ((int)(short)LOWORD(lp))

See Also

Windows Overview, Window Macros, GET_Y_LPARAM, HIWORD, LOWORD


GET_Y_LPARAM

The GET_Y_LPARAM macro retrieves the signed y-coordinate from the given LPARAM value.

int GET_Y_LPARAM(
  LPARAM lParam  // value from which the signed y-coordinate is retrieved
);

Parameters

lParam
Specifies the value to be converted.

Return Values

The return value is the high-order int of the specified value.

Remarks

The GET_Y_LPARAM macro is defined as follows:

#define GET_Y_LPARAM(lp)   ((int)(short)HIWORD(lp))

See Also

Windows Overview, Window Macros, GET_X_LPARAM, HIWORD, LOWORD


HIBYTE

The HIBYTE macro retrieves the high-order byte from the given 16-bit value.

BYTE HIBYTE(
  WORD wValue  // value from which high-order byte is retrieved
);

Parameters

wValue
Specifies the value to be converted.

Return Values

The return value is the high-order byte of the specified value.

Remarks

The HIBYTE macro is defined as follows:

#define HIBYTE(w)   ((BYTE) (((WORD) (w) >> 8) & 0xFF))

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in windef.h.

See Also

Windows Overview, Window Macros, HIWORD, LOBYTE


HIWORD

The HIWORD macro retrieves the high-order word from the given 32-bit value.

WORD HIWORD(
  DWORD dwValue  // value from which high-order word is retrieved
);

Parameters

dwValue
Specifies the value to be converted.

Return Values

The return value is the high-order word of the specified value.

Remarks

The HIWORD macro is defined as follows:

#define HIWORD(l)   ((WORD) (((DWORD) (l) >> 16) & 0xFFFF))

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in windef.h.

See Also

Windows Overview, Window Macros, HIBYTE, LOWORD


LOBYTE

The LOBYTE macro retrieves the low-order byte from the given 16-bit value.

BYTE LOBYTE(
  WORD wValue  // value from which low-order byte is retrieved
);

Parameters

wValue
Specifies the value to be converted.

Return Values

The return value is the low-order byte of the specified value.

Remarks

The LOBYTE macro is defined as follows:

#define LOBYTE(w)   ((BYTE) (w))

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in windef.h.

See Also

Windows Overview, Window Macros, HIBYTE, LOWORD


LOWORD

The LOWORD macro retrieves the low-order word from the given 32-bit value.

WORD LOWORD(
  DWORD dwValue  // value from which low-order word is retrieved
);

Parameters

dwValue
Specifies the value to be converted.

Return Values

The return value is the low-order word of the specified value.

Remarks

The LOWORD macro is defined as follows:

#define LOWORD(l)   ((WORD) (l))

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in windef.h.

See Also

Windows Overview, Window Macros, HIWORD, LOBYTE


MAKELONG

The MAKELONG macro creates an unsigned 32-bit value by concatenating two given 16-bit values.

DWORD MAKELONG(
  WORD wLow,  // low-order word of long value
  WORD wHigh  // high-order word of long value
);

Parameters

wLow
Specifies the low-order word of the new long value.
wHigh
Specifies the high-order word of the new long value.

Return Values

The return value is an unsigned 32-bit value.

Remarks

The MAKELONG macro is defined as follows:

#define MAKELONG(a, b) \
    ((LONG) (((WORD) (a)) | ((DWORD) ((WORD) (b))) << 16))

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in windef.h.

See Also

Windows Overview, Window Macros


MAKELPARAM

The MAKELPARAM macro creates an unsigned 32-bit value for use as an lParam parameter in a message. The macro concatenates two given 16-bit values.

LPARAM MAKELPARAM(
  WORD wLow,  // low-order word
  WORD wHigh  // high-order word
);

Parameters

wLow
Specifies the low-order word of the new long value.
wHigh
Specifies the high-order word of the new long value.

Return Values

The return value is an unsigned 32-bit value.

Remarks

The MAKELPARAM macro is defined as follows:

#define MAKELPARAM(l, h)   ((LPARAM) MAKELONG(l, h))

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Macros, MAKELONG, MAKELRESULT, MAKEWPARAM


MAKELRESULT

The MAKELRESULT macro creates an unsigned 32-bit value for use as a return value from a window procedure. The macro concatenates two given 16-bit values.

LRESULT MAKELRESULT(
  WORD wLow,  // low-order word
  WORD wHigh  // high-order word
);

Parameters

wLow
Specifies the low-order word of the new long value.
wHigh
Specifies the high-order word of the new long value.

Return Values

The return value is an unsigned 32-bit value.

Remarks

The MAKELRESULT macro is defined as follows:

#define MAKELRESULT(l, h)   ((LRESULT) MAKELONG(l, h))

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Macros, MAKELONG, MAKELPARAM, MAKEWPARAM


MAKEWORD

The MAKEWORD macro creates an unsigned 16-bit integer by concatenating two given unsigned character values.

WORD MAKEWORD(
  BYTE bLow,  // low-order byte of short value
  BYTE bHigh  // high-order byte of short value
);

Parameters

bLow
Specifies the low-order byte of the new short value.
bHigh
Specifies the high-order byte of the new short value.

Return Values

The return value is an unsigned 16-bit integer value.

Remarks

The MAKEWORD macro is defined as follows:

#define MAKEWORD(a, b) \
    ((WORD) (((BYTE) (a)) | ((WORD) ((BYTE) (b))) << 8))

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in windef.h.

See Also

Windows Overview, Window Macros


MAKEWPARAM

The MAKEWPARAM macro creates an unsigned 32-bit value for use as a wParam parameter in a message. The macro concatenates two given 16-bit values.

LPARAM MAKEWPARAM(
  WORD wLow,  // low-order word
  WORD wHigh  // high-order word
);

Parameters

wLow
Specifies the low-order word of the new long value.
wHigh
Specifies the high-order word of the new long value.

Return Values

The return value is an unsigned 32-bit value.

Remarks

The MAKEWPARAM macro is defined as follows:

#define MAKEWPARAM(l, h)   ((LPARAM) MAKELONG(l, h))

QuickInfo

Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Windows Overview, Window Macros, MAKELONG, MAKELPARAM, MAKELRESULT


Topic Not Found

No matching topic was found. Some possible reasons and remedies are as follows:

  • The file (.chm) that contains the destination topic is not in the expected location.

Remedy: Rerun the MSDN Library Setup.

  • The file (.chm) that contains the current topic or destination topic is out-of-date and the link is no longer valid.

Remedy: Install the latest version of the MSDN Library.

  • The MSDN Library CD is not in the CD-ROM drive.

Remedy: Insert the MSDN Library CD into the CD-ROM drive.


Application Desktop Toolbars

An application desktop toolbar (also called an appbar) is a window that is similar to the Microsoft® Windows® taskbar. It is anchored to an edge of the screen, and it typically contains buttons that give the user quick access to other applications and windows. The system prevents other applications from using the desktop area occupied by an appbar. Any number of appbars can exist on the desktop at any given time.