Windows User Interface

Purpose

The Microsoft® Windows® user interface is the portion of the Win32® API that enables applications to interact with the user and to display windows, menus, and controls. Applications that use the Windows user interface have a consistent look and feel, which makes them easier for users to learn.

Where Applicable

The user interface functions and messages can be used in all Windows-based applications.

Developer Audience

The Win32 API is designed for use by C/C++ programmers. Familiarity with the Windows graphical user interface and message-driven architecture is required.

Run-time Requirements

Applications that use the Win32 API require Windows NT®, Windows 2000, Whistler, or Windows 95/98/Me. For information on which operating systems are required to use a particular function, see the Requirements section of the documentation for the function.

See Also

Active Accessibility

Common Controls

Windows Shell

Overview

General information about the user interface functions and messages.

Reference

Documentation of user interface functions, interfaces, and messages.

Feedback

Make error reports and feature requests directly to Microsoft.

Microsoft Platform SDK, February 2001 Edition.
This content last built on Thursday, February 01, 2001.


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
  • Control Reference


About Controls

Controls, like other windows, each belong to a window class, either predefined or owner-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.

For more information, see the following topics:

  • Predefined Controls
  • Custom Controls
  • Control Notification Messages
  • Control Messages


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

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.

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

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. 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 elements are used with controls.

  • Control Messages


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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_GETFONT,               // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_SETFONT,               // message to send
  (WPARAM) wParam,          // handle to font
  (LPARAM) lParam          // redraw option
);

Parameters

wParam
Handle to the font. If this parameter is NULL, the control uses the default system font to draw text.
lParam
The low-order word of lParam specifies whether the control should be redrawn immediately upon setting the font. If this parameter is TRUE, the control redraws 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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

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


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
  • Using Buttons
  • Button Reference


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

The default push button cannot be a check box, a radio button, or an ownerdraw button at the same time.


Check Boxes

A check box consists of a square box and application-defined text (label), an icon, or a bitmap, that indicates a choice the user can make by selecting the button. Applications typically display check boxes in a group box to permit the user to choose from a set of related, but independent options. For example, an application might present a group of check boxes from which the user can select error conditions that produce warning beeps.

A check box can be one of four styles: standard, automatic, three-state, and automatic three-state, as defined by the constants BS_CHECKBOX, BS_AUTOCHECKBOX, BS_3STATE, and BS_AUTO3STATE, respectively. Each style can assume two check states: checked (a check mark inside the box) or cleared (no check mark). In addition, a three-state check box can assume an indeterminate state (a grayed box inside the check box). Repeatedly clicking a standard or automatic check box toggles it from checked to cleared and back again. Repeatedly clicking a three-state check box toggles it from checked to cleared to indeterminate and back again.

When the user clicks a check box (of any style), the check box receives the keyboard focus. The system sends the check box's parent window a WM_COMMAND message containing the BN_CLICKED notification code. The parent window doesn't acknowledge this message if it comes from an automatic check box or automatic 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 cleared (no dot in the button). Repeatedly selecting a radio button (standard or automatic) toggles it from checked to cleared and back again.

When the user selects either state, the radio button receives the keyboard focus. The system sends the button's parent window a WM_COMMAND message containing the BN_CLICKED notification code. The parent window doesn't acknowledge this message if it comes from an automatic radio button because the system automatically sets the check state for that style. But the parent window should acknowledge the message if it comes from a radio button because the parent window is responsible for setting the check state for that style. Regardless of the radio button style, the system automatically repaints the button as its state changes.

When the user selects an automatic radio button, the system automatically sets the check state of all other radio buttons within the same group to cleared. 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, cleared, or (for three-state check boxes) indeterminate. A check box is checked when it contains a check mark, and is cleared when it does not. A radio button is checked when it contains a black dot; and is cleared when it does not. A three-state check box is checked when it contains a check mark, is cleared 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 clicks a button, its state changes, and the button sends notification messages to its parent window. For example, a push button control sends the BN_CLICKED notification message whenever the user chooses the button. In all cases, 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 or BN_DOUBLECLICKED | The user double-clicked a button.
BN_DISABLE | A button is disabled.
BN_PUSHED or BN_HILITE | The user pushed a button.
BN_KILLFOCUS | The button lost the keyboard focus.
BN_PAINT | The button should be painted.
BN_SETFOCUS | The button gained the keyboard focus.
BN_UNPUSHED or BN_UNHILITE | The button is no longer pushed.

A button sends the BN_DISABLE, BN_PUSHED, BN_KILLFOCUS, BN_PAINT, BN_SETFOCUS, and BN_UNPUSHED notification messages only if it has the BS_NOTIFY style. BN_DBLCLK notification messages are sent automatically for BS_USERBUTTON, BS_RADIOBUTTON, and BS_OWNERDRAW buttons. Other button types send BN_DBLCLK only if they have the BS_NOTIFY style. All buttons send the BN_CLICKED notification message regardless of their button styles.

For automatic buttons, the system changes the push state and paints the button. In this case, the application typically processes only the BN_CLICKED and BN_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. An application can retrieve the default values for these colors by calling the GetSysColor function, or set the values by calling the SetSysColors function. 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.

However, calling SetSysColors affects all applications, so you should not call this function to customize buttons for your application.

The system sends a WM_CTLCOLORBTN message to a button's parent window before drawing a button. 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. However, only owner-drawn buttons respond to the parent window processing the message.


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. Clears a check box or automatic check box when the user presses the minus (–) key.
WM_ENABLE | Paints the button.
WM_ERASEBKGND | Erases the background for owner-drawn buttons. The backgrounds of other buttons are erased as part of the WM_PAINT and WM_ENABLE processing.
WM_GETDLGCODE | Returns values indicating the type of input processed by the default button procedure, as shown in the following table.

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

Message | Default action
WM_GETFONT | Returns a handle to the current font.
WM_KEYDOWN | Pushes the button if the user presses the SPACEBAR.
WM_KEYUP | Releases the mouse capture for all cases except the TAB key.
WM_KILLFOCUS | Removes the focus rectangle from a button. For push buttons and default push buttons, the focus rectangle is invalidated. If the button has the mouse capture, the capture is released, the button is not clicked, and any push state is removed.
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 clear 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
  • WM_DRAWITEM

When you must paint an owner-drawn button, the system sends the parent window a WM_DRAWITEM message whose lParam parameter is a pointer 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.

Function | Description
CheckDlgButton | Changes the check state of a button control.
CheckRadioButton | Adds a check mark to a specified radio button in a group and removes a check mark from all other radio buttons in the group.
IsDlgButtonChecked | Determines whether a button control has a check mark next to it or whether a three-state button control is grayed, checked, or neither.


CheckDlgButton

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

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

Parameters

hDlg
[in] Handle to the dialog box that contains the button.
nIDButton
[in] Specifies the identifier of the button to modify.
uCheck
[in] 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 cleared

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.

For an example, see Creating a Modeless Dialog Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 button in group
  int nIDLastButton,  // identifier of last button in group
  int nIDCheckButton  // identifier of button to select
);

Parameters

hDlg
[in] Handle to the dialog box that contains the radio button.
nIDFirstButton
[in] Specifies the identifier of the first radio button in the group.
nIDLastButton
[in] Specifies the identifier of the last radio button in the group.
nIDCheckButton
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
[in] Handle to the dialog box that contains the button control.
nIDButton
[in] Specifies the 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 cleared

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.

For an example, see Creating a Modeless Dialog Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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_DOUBLECLICKED
BN_KILLFOCUS
BN_SETFOCUS
WM_CTLCOLORBTN

Obsolete Messages

These notification message are provided only for compatibility with 16-bit versions of Windows earlier than version 3.0.

BN_DISABLE
BN_HILITE
BN_PAINT
BN_PUSHED
BN_UNHILITE
BN_UNPUSHED


BM_CLICK

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

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  BM_CLICK,                 // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  BM_GETCHECK,              // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // 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 cleared

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  BM_GETIMAGE,              // message to send
  (WPARAM) wParam,          // image type
  (LPARAM) lParam          // not used; must be zero
);

Parameters

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

IMAGE_BITMAP
IMAGE_ICON

lParam
This parameter is not used.

Return Values

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

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  BM_GETSTATE,              // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // 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 values 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 cleared; 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 cleared. Same as a return value of zero.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  BM_SETCHECK,              // message to send
  (WPARAM) wParam,          // check state
  (LPARAM) lParam          // not used; must be zero
);

Parameters

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

lParam
This parameter is not used.

Return Values

This message always returns zero.

Remarks

The BM_SETCHECK message has no effect on push buttons.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  BM_SETIMAGE,              // message to send
  (WPARAM) wParam,          // image type
  (LPARAM) lParam          // handle to the image (HANDLE)
);

Parameters

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

IMAGE_BITMAP
IMAGE_ICON

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.

Remarks

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  BM_SETSTATE,              // message to send
  (WPARAM) wParam,          // highlight state
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies whether the button is to be highlighted. A value of TRUE highlights the button. A value of FALSE removes any highlighting.
lParam
This parameter is not used.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  BM_SETSTYLE,              // message to send
  (WPARAM) wParam,          // button style
  (LPARAM) lParam          // redraw state
);

Parameters

wParam
Specifies the new button style. This parameter can be a combination of button styles. For a table of button styles, see Button Styles.
lParam
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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Buttons Overview, Button Messages, LOWORD


BN_CLICKED

The BN_CLICKED notification code is sent when the user clicks a button.

The parent window of the button receives the BN_CLICKED notification code through the WM_COMMAND message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // identifier of button, BN_CLICKED
  LPARAM lParam    // handle to button (HWND)
);

Parameters

wParam
The low-order word contains the button's control identifier.

The high-order word specifies the notification message.

lParam
Handle to the button.

Remarks

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Buttons Overview, Button Messages, HIWORD, LOWORD, WM_COMMAND


BN_DBLCLK

The BN_DBLCLK notification code is sent when the user double-clicks a button. This notification is sent automatically for BS_USERBUTTON, BS_RADIOBUTTON, and BS_OWNERDRAW buttons. Other button types send BN_DBLCLK only if they have the BS_NOTIFY style.

The parent window of the button receives the BN_DBLCLK notification code through the WM_COMMAND message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // identifier of button, BN_DBLCLK
  LPARAM lParam    // handle to button (HWND)
);

Parameters

wParam
The low-order word contains the button's control identifier.

The high-order word specifies the notification message.

lParam
Handle to the button.

Remarks

BN_DBLCLK is the same as the BN_DOUBLECLICKED notification message.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Buttons Overview, Button Messages, BN_CLICKED, BN_DOUBLECLICKED, HIWORD, LOWORD, WM_COMMAND


BN_DISABLE

The BN_DISABLE notification code is sent when a button is disabled.

Note This notification message is provided only for compatibility with 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.

The parent window of the button receives the BN_DISABLE notification code through the WM_COMMAND message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // identifier of button, BN_DISABLE
  LPARAM lParam    // handle to button (HWND)
);

Parameters

wParam
The low-order word contains the button's control identifier.

The high-order word specifies the notification message.

lParam
Handle to the button.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Buttons Overview, Button Messages, DRAWITEMSTRUCT, HIWORD, LOWORD, WM_COMMAND, WM_DRAWITEM


BN_DOUBLECLICKED

The BN_DOUBLECLICKED notification code is sent when the user double-clicks a button. This notification is sent automatically for BS_USERBUTTON, BS_RADIOBUTTON, and BS_OWNERDRAW buttons. Other button types send BN_DOUBLECLICKED only if they have the BS_NOTIFY style.

The parent window of the button receives the BN_DOUBLECLICKED notification code through the WM_COMMAND message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // identifier of button, BN_DOUBLECLICKED
  LPARAM lParam    // handle to button (HWND)
);

Parameters

wParam
The low-order word contains the button's control identifier.

The high-order word specifies the notification message.

lParam
Handle to the button.

Remarks

BN_DOUBLECLICKED is the same as the BN_DBLCLK notification message.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

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


BN_HILITE

The BN_HILITE notification code is sent when the user selects a button.

Note This notification message is provided only for compatibility with 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.

The parent window of the button receives the BN_HILITE notification code through the WM_COMMAND message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // identifier of button, BN_HILITE
  LPARAM lParam    // handle to button (HWND)
);

Parameters

wParam
The low-order word contains the button's control identifier.

The high-order word specifies the notification message.

lParam
Handle to the button.

Remarks

BN_HILITE is the same as the BN_PUSHED notification message.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

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


BN_KILLFOCUS

The BN_KILLFOCUS notification code 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 the BN_KILLFOCUS notification code through the WM_COMMAND message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // identifier of button, BN_KILLFOCUS
  LPARAM lParam    // handle to button (HWND)
);

Parameters

wParam
The low-order word contains the button's control identifier.

The high-order word specifies the notification message.

lParam
Handle to the button.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Buttons Overview, Button Messages, BN_SETFOCUS, HIWORD, LOWORD, WM_COMMAND


BN_PAINT

The BN_PAINT notification code is sent when a button should be painted.

Note This notification message is provided only for compatibility with 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.

The parent window of the button receives the BN_PAINT notification code through the WM_COMMAND message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // identifier of button, BN_PAINT
  LPARAM lParam    // handle to button (HWND)
);

Parameters

wParam
The low-order word contains the button's control identifier.

The high-order word specifies the notification message.

lParam
Handle to the button.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Buttons Overview, Button Messages, DRAWITEMSTRUCT, HIWORD, LOWORD, WM_COMMAND, WM_DRAWITEM


BN_PUSHED

The BN_PUSHED notification code is sent when the push state of a button is set to pushed.

Note This notification message is provided only for compatibility with 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.

The parent window of the button receives the BN_PUSHED notification code through the WM_COMMAND message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // identifier of button, BN_PUSHED
  LPARAM lParam    // handle to button (HWND)
);

Parameters

wParam
The low-order word contains the button's control identifier.

The high-order word specifies the notification message.

lParam
Handle to the button.

Remarks

BN_PUSHED is the same as the BN_HILITE notification message.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

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


BN_SETFOCUS

The BN_SETFOCUS notification code 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 the BN_SETFOCUS notification code through the WM_COMMAND message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // identifier of button, BN_SETFOCUS
  LPARAM lParam    // handle to button (HWND)
);

Parameters

wParam
The low-order word contains the button's control identifier.

The high-order word specifies the notification message.

lParam
Handle to the button.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Buttons Overview, Button Messages, BN_KILLFOCUS, HIWORD, LOWORD, WM_COMMAND


BN_UNHILITE

The BN_UNHILITE notification code is sent when the highlight should be removed from a button.

Note This notification message is provided only for compatibility with 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.

The parent window of the button receives the BN_UNHILITE notification code through the WM_COMMAND message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // identifier of button, BN_UNHILITE
  LPARAM lParam    // handle to button (HWND)
);

Parameters

wParam
The low-order word contains the button's control identifier.

The high-order word specifies the notification message.

lParam
Handle to the button.

Remarks

BN_UNHILITE is the same as the BN_UNPUSHED notification message.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

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


BN_UNPUSHED

The BN_UNPUSHED notification code is sent when the push state of a button is set to unpushed.

Note This notification message is provided only for compatibility with 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.

The parent window of the button receives the BN_UNPUSHED notification code through the WM_COMMAND message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // identifier of button, BN_UNPUSHED
  LPARAM lParam    // handle to button (HWND)
);

Parameters

wParam
The low-order word contains the button's control identifier.

The high-order word specifies the notification message.

lParam
Handle to the button.

Remarks

BN_UNPUSHED is the same as the BN_UNHILITE notification message.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

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


WM_CTLCOLORBTN

The WM_CTLCOLORBTN message is sent to the parent window of a button before drawing the button. The parent window can change the button's text and background colors. However, only owner-drawn buttons respond to the parent window processing this message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_CTLCOLORBTN
  WPARAM wParam,   // handle to button display context (HDC)
  LPARAM lParam    // handle to button (HWND)
);

Parameters

wParam
Handle to the display context for the button.
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.

Remarks

By default, the DefWindowProc function selects the default system colors for the button. Buttons with the BS_PUSHBUTTON, BS_DEFPUSHBUTTON, or BS_PUSHLIKE styles do not use the returned brush. Buttons with these styles are always drawn with the default system colors. Drawing push buttons requires several different brushes-face, highlight and shadow-but the WM_CTLCOLORBTN message allows only one brush to be returned. To provide a custom appearance for push buttons, use an owner-drawn button.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Buttons Overview, Button Messages, DefWindowProc, RealizePalette, SelectPalette,


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 following button styles.

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 cleared. 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 cleared.
BS_AUTOCHECKBOX | Creates a button that is the same as a check box, except that the check state automatically toggles between checked and cleared 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 cleared.
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_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_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. To get BN_DBLCLK notification messages, the button must have the BS_RADIOBUTTON or BS_OWNERDRAW 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
  • Using Combo Boxes
  • Combo Box Reference


About Combo Boxes

The Microsoft® Win32® API provides three types of combo boxes:

  • Simple combo boxes (CBS_SIMPLE)
  • Drop-down combo boxes (CBS_DROPDOWN)
  • 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 that 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 available 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 available in the list; otherwise, the user can only select items in the list.

The following table shows the three combo box types and indicates their drop-down list and edit control attributes.

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 notification when the 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 that the user has finished, and that the selection should be processed. CBN_SELENDCANCEL is sent when the user selects an item, but then selects another control, presses ESC while the drop-down list is open, or closes the dialog box. This indicates that the user's selection should be ignored. CBN_SELENDOK is sent before every CBN_SELCHANGE message.

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 combo box 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. The CBN_EDITUPDATE message 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, like bitmaps of different size, 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 a pointer to the window procedure. To subclass a window, an application calls the SetClassLong function to replace the pointer to that procedure with a pointer to 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 ESC 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 this message specifies the attributes of the files to add, and the lParam parameter is a pointer to the text string that defines the file specification.

You can use the DlgDirListComboBox function to replace the contents of a combo box in a dialog box. The function fills the combo box with the names of drives, directories, and files that match a specified set of criteria. The DlgDirSelectComboBoxEx function retrieves the current selection in a combo box initialized by DlgDirListComboBox. These functions make it possible for the user to select a drive, directory, or file from a combo box without typing the location and name of the file.

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 following table 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 file names 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 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 TCHARs, 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 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;

        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 that 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 is a pointer 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 is a pointer 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 list box was closed , 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 selections 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 pointer to the class window procedure with a pointer to the application-defined SubClassProc function. The pointer to the original window procedure is saved in the global variable lpfnEditWndProc.

SubClassProc intercepts TAB, ENTER, and ESC 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 this, 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, ENTER, or ESC 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.

Function | Description
DlgDirListComboBox | Replaces the contents of a combo box with the names of specified subdirectories and files.
DlgDirSelectComboBoxEx | Retrieves the current selection from a combo box filled by using the DlgDirListComboBox function.
GetComboBoxInfo | Retrieves information about a specified combo box.


DlgDirListComboBox

The DlgDirListComboBox function replaces the contents of a combo box with the names of the subdirectories and files in a specified directory. You can filter the list of names by specifying a set of file attributes. The list of names can include mapped drive letters.

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

Parameters

hDlg
[in] Handle to the dialog box that contains the combo box.
lpPathSpec
[in/out] Pointer to a buffer containing a null-terminated string that specifies an absolute path, relative path, or file name. An absolute path can begin with a drive letter (for example, d:\) or a UNC name (for example, \\machinename\sharename).

The function splits the string into a directory and a file name. The function searches the directory for names that match the file name. If the string does not specify a directory, the function searches the current directory.

If the string includes a file name, the file name must contain at least one wildcard character (? or *). If the string does not include a file name, the function behaves as if you had specified the asterisk wildcard character (*) as the file name. All names in the specified directory that match the file name and have the attributes specified by the uFileType parameter are added to the list displayed in the combo box.

nIDComboBox
[in] Specifies the identifier of a combo box in the hDlg dialog box. If this parameter is zero, DlgDirListComboBox does not try to fill a combo box.
nIDStaticPath
[in] Specifies the identifier of a static control in the hDlg dialog box. DlgDirListComboBox sets the text of this control to display the current drive and directory. This parameter can be zero if you don't want to display the current drive and directory.
uFiletype
[in] A set of bit flags that specify the attributes of the files or directories to be added to the combo box. This parameter can be a combination of the following values.
Value | Meaning
DDL_ARCHIVE | Includes archived files.
DDL_DIRECTORY | Includes subdirectories, which are enclosed in square brackets ([ ]).
DDL_DRIVES | All mapped drives are added to the list. 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. This is the default setting.
DDL_SYSTEM | Includes system files.
DDL_POSTMSGS | If this flag is set, DlgDirListComboBox uses the PostMessage function to send messages to the combo box. If this flag is not set, DlgDirListComboBox uses the SendMessage function.

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 lpPathSpec specifies a directory, DlgDirListComboBox changes the current directory to the specified directory before filling the combo box. The text of the static control identified by the nIDStaticPath parameter is set to the name of the new current directory.

DlgDirListComboBox sends the CB_RESETCONTENT and CB_DIR messages to the combo box.

Windows NT 4.0 and later: If uFileType includes the DDL_DIRECTORY flag and lpPathSpec specifies a first-level directory, such as C:\TEMP, the combo box will always include a ".." entry for the root directory. This is true even if the root directory has hidden or system attributes and the DDL_HIDDEN and DDL_SYSTEM flags are not specified. The root directory of an NTFS volume has hidden and system attributes.

Windows NT/2000: The list displays long file names, if any.

Windows 95: The list displays short file names (the 8.3 form). You can use the SHGetFileInfo or GetFullPathName functions to get the corresponding long file name.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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 a dialog box
  LPTSTR lpString,  // pointer to buffer for path string
  int nCount,       // number of characters in path string
  int nIDComboBox   // combo box identifier
);

Parameters

hDlg
[in] Handle to the dialog box that contains the combo box.
lpString
[out] Pointer to the buffer that receives the selected path.
nCount
[in] Specifies the length, in characters, of the buffer pointed to by the lpString parameter.
nIDComboBox
[in] 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 file name. If there is no selection, the contents of the buffer pointed to by lpString do not change.

The DlgDirSelectComboBoxEx function does not allow more than one file name 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).

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

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


GetComboBoxInfo

The GetComboBoxInfo function retrieves information about the specified combo box.

BOOL GetComboBoxInfo(
  HWND hwndCombo,      // handle to combo box
  PCOMBOBOXINFO pcbi   // combo box information
);

Parameters

hwndCombo
[in] Handle to the combo box.
pcbi
[out] Pointer to a COMBOBOXINFO structure that receives the 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

The CB_GETCOMBOBOXINFO message is equivalent to this function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP6 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Combo Boxes Overview, Combo Box Functions, CB_GETCOMBOBOXINFO, COMBOBOXINFO, GetListBoxInfo


Combo Box Structures

The following structures are used with combo boxes.

COMBOBOXINFO
COMPAREITEMSTRUCT
DRAWITEMSTRUCT
MEASUREITEMSTRUCT


COMBOBOXINFO

The COMBOBOXINFO structure contains combo box status information.

typedef struct tagCOMBOBOXINFO {
  DWORD cbSize;
  RECT  rcItem;
  RECT  rcButton;
  DWORD stateButton;
  HWND  hwndCombo;
  HWND  hwndItem;
  HWND  hwndList;
} COMBOBOXINFO, *PCOMBOBOXINFO, *LPCOMBOBOXINFO;

Members

cbSize
Specifies the size, in bytes, of the structure.
rcItem
A RECT structure that specifies the coordinates of the edit box.
rcButton
A RECT structure that specifies the coordinates of the button that contains the drop-down arrow.
stateButton
Specifies the combo box button state. This parameter can be one of the following values.
Value | Meaning
0 | The button exists and is not pressed.
STATE_SYSTEM_INVISIBLE | There is no button.
STATE_SYSTEM_PRESSED | The button is pressed.

hwndCombo
Handle to the combo box.
hwndItem
Handle to the edit box.
hwndList
Handle to the drop-down list.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP6 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Combo Boxes Overview, Combo Box Structures, GetComboBoxInfo, RECT


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 {
  UINT      CtlType;
  UINT      CtlID;
  HWND      hwndItem;
  UINT      itemID1;
  ULONG_PTR itemData1;
  UINT      itemID2;
  ULONG_PTR itemData2;
  DWORD     dwLocaleId;
} 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.

dwLocaleId
Specifies the locale identifier. To create a locale identifier, use the MAKELCID macro.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Combo Boxes Overview, Combo Box Structures, MAKELCID, 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 {
  UINT      CtlType;
  UINT      CtlID;
  UINT      itemID;
  UINT      itemAction;
  UINT      itemState;
  HWND      hwndItem;
  HDC       hDC;
  RECT      rcItem;
  ULONG_PTR itemData;
} DRAWITEMSTRUCT;

Members

CtlType
Specifies the control type. This member can be one of the values shown in the following table.
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 values shown in the following table.
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 values shown in the following table.
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_HOTLIGHT | Windows 98/Me, Windows 2000 or later: The item is being hot-tracked, that is, the item will be highlighted when the mouse is on the item.
ODS_INACTIVE | Windows 98/Me, Windows 2000 or later: The item is inactive and the window associated with the menu is inactive.
ODS_NOACCEL | Windows 2000 or later: The control is drawn without the keyboard accelerator cues.
ODS_NOFOCUSRECT | Windows 2000 or later: The control is drawn without focus indicator cues.
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 is a handle to 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 that 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 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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 {
  UINT      CtlType;
  UINT      CtlID;
  UINT      itemID;
  UINT      itemWidth;
  UINT      itemHeight;
  ULONG_PTR itemData;
} MEASUREITEMSTRUCT;

Members

CtlType
Specifies the control type. This member can be one of the values shown in the following table.
Value | Meaning
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 or list box. 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 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 except the owner-drawn button control whose size is predetermined by its window.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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_GETCOMBOBOXINFO
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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_ADDSTRING,             // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // string to add (LPCTSTR)
);

Parameters

wParam
This parameter is not used.
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 lParam 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.

If the combo box has WS_HSCROLL style and you add a string wider than the combo box, send a LB_SETHORIZONTALEXTENT message to ensure the horizontal scrollbar appears.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

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


CB_DELETESTRING

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

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_DELETESTRING,          // message to send
  (WPARAM) wParam,          // item to delete
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the zero-based index of the string to delete.
lParam
This parameter is not used.

Return Values

The return value is a count of the strings remaining in the list. If the wParam 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_RESETCONTENT, WM_DELETEITEM


CB_DIR

An application sends a CB_DIR message to a combo box to add names to the list displayed by the combo box. The message adds the names of directories and files that match a specified string and set of file attributes. CB_DIR can also add mapped drive letters to the list.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_DIR,                   // message to send
  (WPARAM) wParam,          // file attributes (UINT)
  (LPARAM) lParam          // filename (LPCTSTR)
);

Parameters

wParam
Specifies the attributes of the files or directories to be added to the combo box. This parameter can be one or more of the following values.
Value | Meaning
DDL_ARCHIVE | Includes archived files.
DDL_DIRECTORY | Includes subdirectories, which are enclosed in square brackets ([ ]).
DDL_DRIVES | All mapped drives are added to the list. 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. This is the default.
DDL_SYSTEM | Includes system files.

lParam
Pointer to a null-terminated string that specifies an absolute path, relative path, or file name. An absolute path can begin with a drive letter (for example, d:\) or a UNC name (for example, \\machinename\sharename).

If the string specifies a file name or directory that has the attributes specified by the wParam parameter, the file name or directory is added to the list. If the file name or directory name contains wildcard characters (? or *), all files or directories that match the wildcard expression and have the attributes specified by the wParam parameter are added to the list displayed in the combo box.

Return Values

If the message succeeds, the return value is the zero-based index of the last name added to the list.

If an error occurs, the return value is CB_ERR. If there is insufficient space to store the new strings, the return value is CB_ERRSPACE.

Remarks

Windows NT 4.0 and later: If wParam includes the DDL_DIRECTORY flag and lParam specifies all the subdirectories of a first-level directory, such as C:\TEMP\*, the list box will always include a ".." entry for the root directory. This is true even if the root directory has hidden or system attributes and the DDL_HIDDEN and DDL_SYSTEM flags are not specified. The root directory of an NTFS volume has hidden and system attributes.

Windows NT/2000: The list displays long file names, if any.

Windows 95: The list displays short file names (the 8.3 form). You can use the SHGetFileInfo or GetFullPathName functions to get the corresponding long file name.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_ADDSTRING, CB_INSERTSTRING, 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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_FINDSTRING,            // message to send
  (WPARAM) wParam,          // index of item preceding start
  (LPARAM) lParam          // search string (LPCSTR)
);

Parameters

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 wParam parameter. If wParam is –1, the entire list box is searched from the beginning.
lParam
Pointer to the null-terminated string that contains the characters for which to search. 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 lParam parameter.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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 lParam parameter.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_FINDSTRINGEXACT,       // message to send
  (WPARAM) wParam,          // index of item preceding start
  (LPARAM) lParam          // search string (LPCSTR)
);

Parameters

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 wParam parameter. If wParam is –1, the entire list box is searched from the beginning.
lParam
Pointer to the null-terminated string for which to search. This string can contain a complete file name, 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

This function is successful only if the specified string and a combo box item have the same length (except for the terminating null character) and the same characters.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

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


CB_GETCOMBOBOXINFO

[This is preliminary documentation and subject to change.]

An application sends the CB_GETCOMBOBOXINFO message to retrieve information about the specified combo box.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to combo box
  LB_GETCOMBOBOXINFO,       // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) pcbi             // pointer to COMBOBOXINFO
);

Parameters

wParam
This parameter is not used.
pcbi
[out] Pointer to a COMBOBOXINFO structure that receives the 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

This message is equivalent to GetComboBoxInfo.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Combo Boxes Overview, Combo Box Messages, COMBOBOXINFO, GetComboBoxInfo


CB_GETCOUNT

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

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_GETCOUNT,              // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_GETCURSEL,             // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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 a combo box in its dropped-down state.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_GETDROPPEDCONTROLRECT, // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // screen coordinates (RECT *)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to the RECT structure that receives the coordinates of the combo box in its dropped-down state.

Return Values

If the message succeeds, the return value is nonzero.

If the message fails, the return value is zero.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_GETDROPPEDSTATE,       // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_GETDROPPEDWIDTH,       // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // 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 zero. The width of the list box is either the minimum allowable width or the combo box width, whichever is larger.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_GETEDITSEL,            // message to send
  (WPARAM) wParam,          // starting position (LPDWORD)
  (LPARAM) lParam          // ending position (LPDWORD)
);

Parameters

wParam
Pointer to a DWORD value that receives the starting position of the selection. This parameter can be NULL.
lParam
Pointer to a DWORD value that receives the ending position of the selection. This parameter can be NULL.

Return Values

The return value is a zero-based DWORD 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_SETEDITSEL, HIWORD, LOWORD


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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_GETEXTENDEDUI,         // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_GETHORIZONTALEXTENT,   // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

The return value is the scrollable width, in pixels.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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 value associated with the specified item in the combo box.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_GETITEMDATA,           // message to send
  (WPARAM) wParam,          // item index
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the zero-based index of the item.
lParam
This parameter is not used.

Return Values

The return value is the 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 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_GETITEMHEIGHT,         // message to send
  (WPARAM) wParam,          // item index
  (LPARAM) lParam          // not used; must be zero
);

Parameters

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 wParam parameter is the zero-based index of a specific list item.

lParam
This parameter is not used.

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 the height of the item specified by the wParam parameter. If wParam 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_GETLBTEXT,             // message to send
  (WPARAM) wParam,          // item index
  (LPARAM) lParam          // receives string (LPCSTR)
);

Parameters

wParam
Specifies the zero-based index of the string to retrieve.
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 TCHARs, of the string. If it is an ANSI string this is the number of bytes, but if it is a Unicode string this is the number of characters.

Return Values

The return value is the length of the string, in TCHARs, excluding the terminating null character. If wParam 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 lParam receives the data associated with the item.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_GETLBTEXTLEN,          // message to send
  (WPARAM) wParam,          // item index
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the zero-based index of the string.
lParam
This parameter is not used.

Return Values

The return value is the length of the string, in TCHARs, excluding the terminating null character. If an ANSI string this is the number of bytes, and if it is a Unicode string this is the number of characters. Under certain conditions, this value may actually be greater than the length of the text. For more information, see the Remarks section.

If the wParam 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_GETLOCALE,             // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

The return value specifies the current locale of the combo box. The high word contains the country/region 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_ADDSTRING, CB_SETLOCALE, HIWORD, LOWORD, 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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_GETTOPINDEX,           // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_SETTOPINDEX


CB_INITSTORAGE

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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_INITSTORAGE,           // message to send
  (WPARAM) wParam,          // number of items to add
  (LPARAM) lParam          // memory to allocate
);

Parameters

wParam
Specifies the number of items to add.
lParam
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/2000: 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 wParam parameter. For Windows 2000, 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 wParam and lParam parameters. If you overestimate, the extra memory is allocated, if you underestimate, the normal allocation is used for items that exceed the requested amount.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_INSERTSTRING,          // message to send
  (WPARAM) wParam,          // item index
  (LPARAM) lParam          // string to insert (LPCTSTR)
);

Parameters

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.
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 lParam parameter is stored rather than the string to which it would otherwise point.

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.

If the combo box has WS_HSCROLL style and you insert a string wider than the combo box, you should send a LB_SETHORIZONTALEXTENT message to ensure the horizontal scrollbar appears.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_ADDSTRING, LB_SETHORIZONTALEXTENT, 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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_LIMITTEXT,             // message to send
  (WPARAM) wParam,          // max characters
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the maximum number of characters the user can enter, not including the null terminator. If this parameter is zero, the text length is limited to 0x7FFFFFFE characters.
lParam
This parameter is not used.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_RESETCONTENT,          // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_SELECTSTRING,          // message to send
  (WPARAM) wParam,          // item of item preceding start
  (LPARAM) lParam          // search string
);

Parameters

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 wParam parameter. If wParam is –1, the entire list is searched from the beginning.
lParam
Pointer to the null-terminated string that contains the characters for which to search. 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 lParam parameter.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_SETCURSEL,             // message to send
  (WPARAM) wParam,          // item index
  (LPARAM) lParam          // not used; must be zero
);

Parameters

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

Return Values

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_SETDROPPEDWIDTH,       // message to send
  (WPARAM) wParam,          // width of list box
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the width of the list box, in pixels.
lParam
This parameter is not used.

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-down list box is zero. The width of the list box is either the minimum allowable width or the combo box width, whichever is larger.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_SETEDITSEL,            // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // start and end position
);

Parameters

wParam
This parameter is not used.
lParam
The low-order word of lParam specifies the starting position. If the low-order word is –1, the selection, if any, is removed.

The high-order word of lParam specifies the ending position. If the high-order word is –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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_GETEDITSEL, MAKELPARAM


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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_SETEXTENDEDUI,         // message to send
  (WPARAM) wParam,          // user interface type
  (LPARAM) lParam          // not used; must be zero
);

Parameters

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.
lParam
This parameter is not used.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_SETHORIZONTALEXTENT,   // message to send
  (WPARAM) wParam,          // scrollable width
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the scrollable width of the list box, in pixels.
lParam
This parameter is not used.

Return Values

No return value.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Combo Boxes Overview, Combo Box Messages, CB_GETHORIZONTALEXTENT


CB_SETITEMDATA

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

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_SETITEMDATA,           // message to send
  (WPARAM) wParam,          // item index
  (LPARAM) lParam          // item data (DWORD)
);

Parameters

wParam
Specifies the item's zero-based index.
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 value in the lParam parameter of the CB_ADDSTRING or CB_INSERTSTRING message that added the item to the combo box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_SETITEMHEIGHT,         // message to send
  (WPARAM) wParam,          // item index
  (LPARAM) lParam          // item height
);

Parameters

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 wParam parameter is the zero-based index of a specific list item.

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

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_SETLOCALE,             // message to send
  (WPARAM) wParam,          // locale identifier (WORD)
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the locale identifier for the combo box to use for sorting when adding text.
lParam
This parameter is not used.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_SETTOPINDEX,           // message to send
  (WPARAM) wParam,          // item list index
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the zero-based index of the list item.
lParam
This parameter is not used.

Return Values

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

If the message fails, the return value is CB_ERR.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CB_SHOWDROPDOWN,          // message to send
  (WPARAM) wParam,          // show state
  (LPARAM) lParam          // not used; must be zero
);

Parameters

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.
lParam
This parameter is not used.

Return Values

The return value is always TRUE.

Remarks

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // combo box identifier, CBN_CLOSEUP
  LPARAM lParam    // handle to combo box (HWND)
);

Parameters

wParam
The low-order word specifies the control identifier of the combo box.

The high-order word specifies the notification message.

lParam
Handle to the 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Combo Boxes Overview, Combo Box Messages, CBN_DROPDOWN, CBN_SELCHANGE, HIWORD, LOWORD, 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.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // combo box identifier, CBN_DBLCLK
  LPARAM lParam    // handle to combo box (HWND)
);

Parameters

wParam
The low-order word specifies the control identifier of the combo box.

The high-order word specifies the notification message.

lParam
Handle to the 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Combo Boxes Overview, Combo Box Messages, CBN_SELCHANGE, HIWORD, LOWORD, 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.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // combo box identifier, CBN_DROPDOWN
  LPARAM lParam    // handle to combo box (HWND)
);

Parameters

wParam
The low-order word specifies the control identifier of the combo box.

The high-order word specifies the notification message.

lParam
Handle to the combo box.

Remarks

This notification message is only sent if the combo box has the CBS_DROPDOWN or CBS_DROPDOWNLIST style.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Combo Boxes Overview, Combo Box Messages, CBN_CLOSEUP, HIWORD, LOWORD, 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.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // combo box identifier, CBN_EDITCHANGE
  LPARAM lParam    // handle to combo box (HWND)
);

Parameters

wParam
The low-order word specifies the control identifier of the combo box.

The high-order word specifies the notification message.

lParam
Handle to the combo box.

Remarks

If the combo box has the CBS_DROPDOWNLIST style, this notification message is not sent.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Combo Boxes Overview, Combo Box Messages, CBN_EDITUPDATE, HIWORD, LOWORD, 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.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // combo box identifier, CBN_EDITUPDATE
  LPARAM lParam    // handle to combo box (HWND)
);

Parameters

wParam
The low-order word specifies the control identifier of the combo box.

The high-order word specifies the notification message.

lParam
Handle to the combo box.

Remarks

If the combo box has the CBS_DROPDOWNLIST style, this notification message is not sent.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Combo Boxes Overview, Combo Box Messages, CBN_EDITCHANGE, HIWORD, LOWORD, 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.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // combo box identifier, CBN_ERRSPACE
  LPARAM lParam    // handle to combo box (HWND)
);

Parameters

wParam
The low-order word specifies the control identifier of the combo box.

The high-order word specifies the notification message.

lParam
Handle to the combo box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Combo Boxes Overview, Combo Box Messages, HIWORD, LOWORD, 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.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // combo box identifier, CBN_KILLFOCUS
  LPARAM lParam    // handle to combo box (HWND)
);

Parameters

wParam
The low-order word specifies the control identifier of the combo box.

The high-order word specifies the notification message.

lParam
Handle to the combo box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Combo Boxes Overview, Combo Box Messages, CBN_SETFOCUS, HIWORD, LOWORD, 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.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // combo box identifier, CBN_SELCHANGE
  LPARAM lParam    // handle to combo box (HWND)
);

Parameters

wParam
The low-order word specifies the control identifier of the combo box.

The high-order word specifies the notification message.

lParam
Handle to the 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Combo Boxes Overview, Combo Box Messages, CBN_CLOSEUP, CBN_DBLCLK, HIWORD, LOWORD, 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.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // combo box identifier, CBN_SELENDCANCEL
  LPARAM lParam    // handle to combo box (HWND)
);

Parameters

wParam
The low-order word specifies the control identifier of the combo box.

The high-order word specifies the notification message.

lParam
Handle to the 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Combo Boxes Overview, Combo Box Messages, CBN_SELCHANGE, CBN_SELENDOK, HIWORD, LOWORD, 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.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // combo box identifier, CBN_SELENDOK
  LPARAM lParam    // handle to combo box (HWND)
);

Parameters

wParam
The low-order word specifies the control identifier of the combo box.

The high-order word specifies the notification message.

lParam
Handle to the 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Combo Boxes Overview, Combo Box Messages, CBN_SELCHANGE, CBN_SELENDCANCEL, HIWORD, LOWORD, 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.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // combo box identifier, CBN_SETFOCUS
  LPARAM lParam    // handle to combo box (HWND)
);

Parameters

wParam
The low-order word specifies the control identifier of the combo box.

The high-order word specifies the notification message.

lParam
Handle to the combo box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Combo Boxes Overview, Combo Box Messages, CBN_KILLFOCUS, HIWORD, LOWORD, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMPAREITEM (UINT)
  WPARAM wParam,   // control identifier
  LPARAM lParam    // item data (LPCOMPAREITEMSTRUCT)
);

Parameters

wParam
Specifies the identifier of the control that sent the WM_COMPAREITEM message.
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 values shown in the following table.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_DRAWITEM
  WPARAM wParam,   // control identifier (UINT)
  LPARAM lParam    // item data (LPDRAWITEMSTRUCT)
);

Parameters

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

Remarks

By default, the DefWindowProc function draws the focus rectangle for an owner-drawn list box item.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Combo Boxes Overview, Combo Box Messages, DefWindowProc, DRAWITEMSTRUCT


WM_MEASUREITEM

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

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_MEASUREITEM
  WPARAM wParam,   // control identifier (UINT)
  LPARAM lParam    // item data (LPMEASUREITEMSTRUCT)
);

Parameters

wParam
Contains the value of the CtlID member of the MEASUREITEMSTRUCT structure pointed to by the lParam 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 lParam is (UINT)–1, the message was sent by a combo edit field.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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. For accessibility issues, see Exposing Owner Drawn Combo Box Items
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 file names 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

The Microsoft® Win32® API provides 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 by typing on the keyboard.

Edit controls support both the Unicode character set in which characters are two bytes, and ANSI character sets in which characters are one byte. For more information about Unicode and ANSI character sets, see Unicode and Character Sets.

The Win32 API also provides support for rich edit controls, which support many features not available in system edit controls. For more information, see Rich Edit Controls.

  • About Edit Controls
  • Using Edit Controls
  • Edit Control Reference


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 edited by using the keyboard or the mouse. An edit control can send notification messages to its parent window in the form of WM_COMMAND messages. 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 (sometimes called SLEs) and multiline edit controls (sometimes called MLEs). Edit controls belong to the EDIT window class.

A combo box is a control that combines much of the functionality of an edit control and a list box. In a combo box, the edit control displays the current selection and the list box presents options a user can select. 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 also 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 file name) 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 digits only in the edit control. 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 a single-line 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. For information on wordwrap and line breaks, see Handling Wordwrap and Line Breaks.

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

To save the current buffer and obtain a new one

  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 flag or the 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 Wordwrap and Line Breaks
  • Retrieving Points and Characters
  • Complex Scripts in Edit Controls


Selecting an Edit Control

The user can select an edit control by clicking it with the mouse or by pressing the TAB key to move 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 indexes 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 Microsoft® 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 right-clicks the control. The commands 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. The application can then 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 KB. An application can change the default limit 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 (1,000 bytes total). If the application then sends an EM_SETLIMITTEXT message limiting user-entered text to 300 bytes, the 1,000 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 1,300 bytes, the 1,000 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

The Win32 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. For example, in a single-line edit control that contains n characters, the line index is zero and the characters are indexed from zero to n-1. In a multiline edit control that contains 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. The EM_LINEFROMCHAR message returns the index of the line containing a specified character index. The EM_LINEINDEX message 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. The wParam parameter specifies the scrolling action. The EM_SCROLL message applies to multiline edit controls only. EM_SCROLL has the same effect as the WM_VSCROLL message.

The EM_SCROLLCARET message scrolls the caret into view in an edit control. This was done in 16-bit Microsoft® 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 the 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 just wide enough to accommodate the largest character horizontal overhang (negative ABC widths) for the current font being used 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 a single-line 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 or undo the most recent operation on the edit control (undoing 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 Wordwrap and Line Breaks

An application can use wordwrap functions with multiline edit controls to locate the word or word fragment that should be wrapped to the next line. Using the default wordwrap function provided by the system, lines always end at the spaces between words. An application can specify its own wordwrap function by supplying a EditWordBreakProc wordwrap function and sending the edit control an EM_SETWORDBREAKPROC message. An application can retrieve the address of the current wordwrap 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 line feed) 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 line feed entered by the user). Also 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.


Retrieving Points and Characters

To determine the character closest to a specified point in the client area of an edit control, send the EM_CHARFROMPOS message to the control. The message returns the character index and line index of the character nearest the point. Similarly, you can retrieve the client area coordinates of a specified character by sending the EM_POSFROMCHAR message. The message returns the x and y coordinates of the upper-left corner of the specified character.


Autocompletion of Strings

Autocompletion expands strings that have been partially entered in an edit control into complete strings. For example, when a user starts to enter a URL in the Address edit control that is embedded in the Microsoft® Internet Explorer toolbar, autocompletion expands the string into one or more complete URLs that are consistent with the existing partial string. A partial URL string such as "mic" might be expanded to "http://www.microsoft.com" or "http://www.microsoft.com/windows". Autocompletion is typically used with edit controls or with controls that have an embedded edit control.

For more information, see the IAutoComplete and IAutoComplete2 interface documentation.


Complex Scripts in Edit Controls

A complex script is a language whose printed form is not laid out in a simple way. For example, a complex script may allow bidirectional rendering, contextual shaping of glyphs, or combining characters. The standard edit controls have been extended to support multilingual text and complex scripts. This includes not only input and display, but also correct cursor movement over character clusters (in Thai and Devanagari script, for example).

A well-written application will receive this support automatically, without modification. Again, you should consider adding support for right-to-left reading order and right alignment. In this case, toggle the extended style flags of the edit control window to control these attributes, as shown in the following example:

// ID_EDITCONTROL is the control ID in the resource file.
HANDLE hWndEdit = GetDlgItem(hDlg, ID_EDITCONTROL);
LONG lAlign = GetWindowLong(hWndEdit, GWL_EXSTYLE) ;

// To toggle alignment
lAlign ^= WS_EX_RIGHT ;

// To toggle reading order
lAlign ^= WS_EX_RTLREADING ;

After setting the lAlign value, enable the new display by setting the extended style of the edit control window as follows:

// This assumes your edit control is in a dialog box. If not,
// get the edit control handle from another source.

SetWindowLong(hWndEdit, GWL_EXSTYLE, lAlign);
InvalidateRect(hWndEdit, NULL, FALSE);

Beginning in Windows 2000, the standard edit control supports a context menu that allows the user to toggle the reading order and insert/display Unicode bidirectional control characters.

Uniscribe is another set of functions that provide fine control for processing complex scripts. For more information, see Uniscribe.


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 or has scrolled the mouse wheel over the edit control. The system sends this message before updating the screen.

In addition, the system sends a WM_CTLCOLOREDIT message to an edit control's parent window before the edit control is drawn. This message contains a handle of the edit control's display context (DC) and a handle of the child window. The parent window can use these handles to change the edit control's text and background colors.


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 line feed) to the ends of wrapped lines in a multiline edit control. It is not processed by single-line edit controls.
EM_GETFIRSTVISIBLELINE | Returns the zero-based index of the first visible character in a single-line edit control or the zero-based index of the uppermost visible line in a multiline edit control.
EM_GETHANDLE | Returns a handle identifying the buffer containing the multiline edit control's text. It is not processed by 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 in the vertical scroll bar in a multiline edit control.
EM_GETWORDBREAKPROC | Returns the address of the current wordwrap function in an edit control.
EM_LINEFROMCHAR | Returns the zero-based number of the line in a multiline edit control that contains a specified character index. 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/2000 or later: For single-line edit controls, this value is either 0x7FFFFFFE or the value of the wParam parameter, whichever is smaller. For multiline edit controls, this value is either –1 or the value of the wParam parameter, whichever is smaller.

Windows 95/98/Me: For single-line edit controls, this value is either 0x7FFE or the value of the wParam parameter, whichever is smaller. For multiline edit controls, this value is either 0xFFFF or the value of the wParam parameter, whichever is smaller.
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 wordwrap function with an application-defined wordwrap function.
EM_UNDO | Removes any text that was just inserted or inserts any deleted characters and sets the selection to the inserted text. If necessary, sends the EN_UPDATE and EN_CHANGE notification messages to the parent window.
WM_CHAR | Writes a character to the single-line edit control and sends the EN_UPDATE and EN_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 depressed, extends the selection to the word under the cursor.
WM_LBUTTONDOWN | Changes the current insertion point. If the SHIFT key is depressed, extends the selection to the position of the cursor. In multiline edit controls, also sets the timer to automatically scroll when the user holds down the mouse button outside the multiline edit control window.
WM_LBUTTONUP | Releases the mouse capture and sets the text insertion point in the single-line edit control. In a multiline edit control, also kills the timer set in the 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 takes no action.
WM_SYSKEYDOWN | Undoes the last action if the user presses ALT+BACKSPACE; otherwise takes no action.
WM_TIMER | Scrolls the text in the edit control window if the user holds down the mouse button outside the multiline edit control window.
WM_UNDO | Removes any text that was just inserted or inserts any deleted characters and sets the selection to the inserted text. If necessary, sends the EN_UPDATE and EN_CHANGE notification messages to the parent window.
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 wordwrap 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.

Function | Description
EditWordBreakProc | An application-defined callback function used with the EM_SETWORDBREAKPROC message.


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 to 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,     // text string
  int ichCurrent,  // index of starting point
  int cch,         // length of text string
  int code         // action to take
);

Parameters

lpch
[in] Pointer to the text of the edit control.
ichCurrent
[in] 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
[in] Specifies the number of TCHARs in the edit control text. For the ANSI text, this is the number of bytes; for the Unicode text, this is the numer of characters.
code
[in] Specifies the action to be taken by the callback function. This parameter can be one of the following values.
Value | Action
WB_CLASSIFY | Retrieves 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 | Checks whether the character at the specified position is a delimiter.
WB_LEFT | Finds the beginning of a word to the left of the specified position.
WB_LEFTBREAK | Finds the end-of-word delimiter to the left of the specified position. This value is for use with rich edit controls.
WB_MOVEWORDLEFT | Finds 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 | Finds 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 | Finds the beginning of a word to the right of the specified position. This is useful in right-aligned edit controls.
WB_RIGHTBREAK | Finds 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 line feed must be treated as a single word by the callback function. Two carriage returns followed by a line feed 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.

Rich Edit 1.0: 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.

Rich Edit 2.0 and later: EditWordBreakProc has been extended to support rich text by passing in Unicode.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.
Unicode: Declared as Unicode and ANSI prototypes.

See Also

Edit Controls Overview, Edit Control Functions, EditWordBreakProcEx, SendMessage, EM_FINDWORDBREAK, EM_SETWORDBREAKPROC, EM_SETWORDBREAKPROCEX


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_ALIGN_LTR_EC
EN_ALIGN_RTL_EC
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

The EM_CANUNDO message determines whether there are any actions in an edit control's undo queue. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_CANUNDO,               // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

If there are actions in the control's undo queue, the return value is nonzero.

If the undo queue is empty, the return value is zero.

Remarks

If the undo queue is not empty, you can send the EM_UNDO message to the control to undo the most recent operation.

Edit controls and Rich Edit 1.0: The undo queue contains only the most recent operation.

Rich Edit 2.0 and later: The undo queue can contain multiple operations.

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_UNDO


EM_CHARFROMPOS

The EM_CHARFROMPOS message retrieves information about the character closest to a specified point in the client area of an edit control. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_CHARFROMPOS,           // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // point coordinates
);

Parameters

wParam
This parameter is not used.
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: This is a pointer to a POINTL structure that contains the horizontal and vertical coordinates.

Edit controls: The low-order word contains the horizontal coordinate. The high-order word contains the vertical coordinate.

Return Values

Rich edit controls: The return value specifies the zero-based character index of the character nearest the specified point. The return value indicates the last character in the edit control if the specified point is beyond the last character in the control.

Edit controls: The low-order word 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-order word 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.

Remarks

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_POSFROMCHAR, MAKELPARAM, POINTL


EM_EMPTYUNDOBUFFER

The EM_EMPTYUNDOBUFFER message resets the undo flag of an edit control. The undo flag is set whenever an operation within the edit control can be undone. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_EMPTYUNDOBUFFER,       // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // 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.

Edit controls and Rich Edit 1.0: The control can only undo or redo the most recent operation.

Rich Edit 2.0 and later: The EM_EMPTYUNDOBUFFER message empties all undo and redo buffers. Rich edit controls enable the user to undo or redo multiple operations.

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_CANUNDO, EM_SETHANDLE, EM_UNDO, WM_SETTEXT


EM_FMTLINES

The EM_FMTLINES message sets a flag that determines whether a multiline edit control includes soft line-break characters. A soft line break consists of two carriage returns and a line feed and is inserted at the end of a line that is broken because of wordwrapping.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_FMTLINES,              // message to send
  (WPARAM) wParam,          // line break option
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies whether soft line-break characters are to be inserted. A value of TRUE inserts the characters; a value of FALSE removes them.
lParam
This parameter is not used.

Return Values

The return value is identical to the wParam 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 line feed.

Note The size of the text changes when this message is processed.

Rich Edit: The EM_FMTLINES message is not supported.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_GETHANDLE, WM_GETTEXT


EM_GETFIRSTVISIBLELINE

The EM_GETFIRSTVISIBLELINE message retrieves the zero-based index of the uppermost visible line in a multiline edit control. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETFIRSTVISIBLELINE,   // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // 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.

Edit controls: For single-line edit controls, the return value is the zero-based index of the first visible character.

Rich edit controls: For single-line rich edit controls, the return value is zero.

Remarks

The number of lines and the length of the lines in an edit control depend on the width of the control and the current wordwrap setting.

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages


EM_GETHANDLE

The EM_GETHANDLE message retrieves a handle of the memory currently allocated for a multiline edit control's text.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETHANDLE,             // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // 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.

Rich Edit: The EM_GETHANDLE message is not supported. Rich edit controls do not store text as a simple array of characters.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_SETHANDLE


EM_GETIMESTATUS

The EM_GETIMESTATUS message retrieves a set of status flags that indicate how the edit control interacts with the input method editor (IME).

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETIMESTATUS,          // message to send
  (WPARAM) wParam,          // status values
  (LPARAM) lParam          // not used; must be zero
);

Parameters

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

lParam
This parameter is not used.

Return Values

Data specific to the type of status to retrieve. With the EMSIS_COMPOSITIONSTRING value for status, this return value is one or more of the following values.

Value | Meaning
EIMES_GETCOMPSTRATONCE | If this flag is set, the edit control hooks the WM_IME_COMPOSITION message with fFlags set to GCS_RESULTSTR 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.

Remarks

Rich Edit: The EM_GETIMESTATUS message is not supported.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_SETIMESTATUS


EM_GETLIMITTEXT

The EM_GETLIMITTEXT message retrieves the current text limit for an edit control. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETLIMITTEXT,          // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

The return value is the text limit.

Remarks

Edit controls, Rich Edit 2.0 and later: The text limit is the maximum amount of text, in TCHARs, that the control can contain. For ANSI text, this is the number of bytes; for Unicode text, this is the numer of characters. Two documents with the same character limit will yield the same text limit, even if one is ANSI and the other is Unicode.

Rich Edit 1.0: The text limit is the maximum amount of text, in bytes, that the rich edit control can contain.

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_SETLIMITTEXT


EM_GETLINE

The EM_GETLINE message copies a line of text from an edit control and places it in a specified buffer. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETLINE,               // message to send
  (WPARAM) wParam,          // line number
  (LPARAM) lParam          // line buffer (LPCTSTR)
);

Parameters

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.
lParam
Pointer to the buffer that receives a copy of the line. Before sending the message, set the first word of this buffer to the size, in TCHARs, of the buffer. For ANSI text, this is the number of bytes; for Unicode text, this is the numer of characters. The size in the first word is overwritten by the copied line.

Return Values

The return value is the number of TCHARs copied. The return value is zero if the line number specified by the wParam parameter is greater than the number of lines in the edit control.

Remarks

Edit controls: The copied line does not contain a terminating null character.

Rich edit controls: The copied line does not contain a terminating null character, unless no text was copied. If no text was copied, the message places a null character at the beginning of the buffer. For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_LINELENGTH, WM_GETTEXT


EM_GETLINECOUNT

The EM_GETLINECOUNT message retrieves the number of lines in a multiline edit control. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETLINECOUNT,          // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

The return value is an integer specifying the total number of text lines in the multiline edit control or rich edit control. If the control has no text, the return value is 1. The return value will never be less than 1.

Remarks

The EM_GETLINECOUNT message retrieves the total number of text lines, not just the number of lines that are currently visible.

If the wordwrap feature is enabled, the number of lines can change when the dimensions of the editing window change.

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETMARGINS,            // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // 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.

Remarks

Rich Edit: The EM_GETMARGINS message is not supported.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_SETMARGINS


EM_GETMODIFY

The EM_GETMODIFY message retrieves the state of an edit control's modification flag. The flag indicates whether the contents of the edit control have been modified. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETMODIFY,             // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

If the contents of edit control have been modified, the return value is nonzero; otherwise, it is zero.

Remarks

The system automatically clears the modification flag to zero when the control is created. If the user changes the control's text, the system sets the flag to nonzero. You can send the EM_SETMODIFY message to the edit control to set or clear the flag.

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_SETMODIFY


EM_GETPASSWORDCHAR

The EM_GETPASSWORDCHAR message retrieves the password character that an edit control displays when the user enters text. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETPASSWORDCHAR,       // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // 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 any characters typed by the user. If the return value is NULL, there is no password character, and the control displays the characters typed by the user.

Remarks

If an edit control is created with the ES_PASSWORD style, the default password character is set to an asterisk (*). If an edit control is created without the ES_PASSWORD style, there is no password character. To change the password character, send the EM_SETPASSWORDCHAR message.

Edit controls: Multiline edit controls do not support the password style or messages.

Rich edit controls: Both single-line and multiline edit controls support the password style and messages.

Rich Edit 2.0 and later: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_SETPASSWORDCHAR


EM_GETRECT

The EM_GETRECT message retrieves the formatting rectangle of an edit control. The formatting rectangle is the limiting rectangle into which the control draws the text. The limiting rectangle is independent of the size of the edit-control window. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETRECT,               // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // formatting rectangle (LPRECT)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to a RECT structure that receives the formatting rectangle.

Return Values

The return value is not meaningful.

Remarks

You can modify the formatting rectangle of a multiline edit control by using the EM_SETRECT and EM_SETRECTNP messages.

Under certain conditions, EM_GETRECT might not return the exact values that EM_SETRECT or EM_SETRECTNP set—it will be approximately correct, but it can be off by a few pixels.

Rich edit controls: The formatting rectangle does not include the selection bar, which is an unmarked area to the left of each paragraph. When clicked, the selection bar selects the line.

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_SETRECT, EM_SETRECTNP, RECT


EM_GETSEL

The EM_GETSEL message retrieves the starting and ending character positions of the current selection in an edit control. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETSEL,                // message to send
  (WPARAM) wParam,          // starting position (LPDWORD)
  (LPARAM) lParam          // ending position (LPDWORD)
);

Parameters

wParam
Pointer to a buffer that receives the starting position of the selection. This parameter can be NULL.
lParam
Pointer to a buffer 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 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.

It is better to use the values returned in wParam and lParam because they are full 32-bit values.

Remarks

Rich edit controls: You can also use the EM_EXGETSEL message to retrieve the same information. EM_EXGETSEL also returns starting and ending character positions as 32-bit values.

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_EXGETSEL, EM_SETSEL


EM_GETTHUMB

The EM_GETTHUMB message retrieves the position of the scroll box (thumb) in the vertical scroll bar of a multiline edit control. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETTHUMB,              // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

The return value is the position of the scroll box.

Remarks

Rich Edit 2.0 and later: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages


EM_GETWORDBREAKPROC

The EM_GETWORDBREAKPROC message retrieves the address of the current wordwrap function. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETWORDBREAKPROC,      // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

The return value specifies the address of the application-defined wordwrap function. The return value is NULL if no wordwrap function exists.

Remarks

A wordwrap 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 wordwrap function places this word at the beginning of the next line on the display. A wordwrap 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.

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EditWordBreakProc, EM_FMTLINES, EM_SETWORDBREAKPROC


EM_LIMITTEXT

The EM_LIMITTEXT message sets the text limit of an edit control. The text limit is the maximum amount of text, in TCHARs, that the user can type into the edit control. You can send this message to either an edit control or a rich edit control.

For edit controls and Rich Edit 1.0, bytes are used. For Rich Edit 2.0 and later, characters are used.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_LIMITTEXT,             // message to send
  (WPARAM) wParam,          // text length
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the maximum number of TCHARs the user can enter. For ANSI text, this is the number of bytes; for Unicode text, this is the numer of characters. This number does not include the null terminator.

Rich edit controls: If this parameter is zero, the text length is set to 64K characters.

Edit controls on Windows NT/2000 or later: If this parameter is zero, the text length is set to 0x7FFFFFFE characters for single-line edit controls or –1 for multiline edit controls.

Edit controls on Windows 95/98/Me: If this parameter is zero, the text length is set to 0x7FFE characters for single-line edit controls or 0xFFFF for multiline edit controls.

lParam
This parameter is not used.

Return Values

This message does not return a value.

Remarks

The EM_LIMITTEXT message limits only the text the user can enter. It does not affect 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.

Before EM_LIMITTEXT is called, the default limit for the amount of text a user can enter in an edit control is 32,767 characters.

Edit controls on Windows NT/2000 or later: 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 –1 bytes or the value of the wParam parameter, whichever is smaller.

Edit controls on Windows 95/98/Me: 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.

Rich edit controls: Use the message EM_EXLIMITTEXT for text length values greater than 64K. For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_EXLIMITTEXT, WM_SETTEXT


EM_LINEFROMCHAR

The EM_LINEFROMCHAR message retrieves the index of the line that contains the specified character index in a multiline edit control. A character index is the zero-based index of the character from the beginning of the edit control. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_LINEFROMCHAR,          // message to send
  (WPARAM) wParam,          // character index
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the character index of the character contained in the line whose number is to be retrieved. If this parameter is –1, EM_LINEFROMCHAR retrieves either the line number of the current line (the line containing the caret) or, if there is a selection, the line number of the line containing the beginning of the selection.
lParam
This parameter is not used.

Return Values

The return value is the zero-based line number of the line containing the character index specified by wParam.

Remarks

Rich edit controls: If the character index is greater than 64K, use the EM_EXLINEFROMCHAR message. For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_EXLINEFROMCHAR, EM_LINEINDEX


EM_LINEINDEX

The EM_LINEINDEX message retrieves the character index of the first character of a specified line in a multiline edit control. A character index is the zero-based index of the character from the beginning of the edit control. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_LINEINDEX,             // message to send
  (WPARAM) wParam,          // line number
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the zero-based line number. A value of –1 specifies the current line number (the line that contains the caret).
lParam
This parameter is not used.

Return Values

The return value is the character index of the line specified in the wParam parameter, or it is –1 if the specified line number is greater than the number of lines in the edit control.

Remarks

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_LINEFROMCHAR


EM_LINELENGTH

The EM_LINELENGTH message retrieves the length, in characters, of a line in an edit control. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_LINELENGTH,            // message to send
  (WPARAM) wParam,          // character index
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the character index of a character in the line whose length is to be retrieved. If this parameter is greater than the number of characters in the control, the return value is zero.

This parameter can be –1. In this case, 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).

lParam
This parameter is not used.

Return Values

For multiline edit controls, the return value is the length, in TCHARs, of the line specified by the wParam parameter. For ANSI text, this is the number of bytes; for Unicode text, this is the numer of characters. It does not include the carriage-return character at the end of the line.

For single-line edit controls, the return value is the length, in TCHARs, of the text in the edit control.

If wParam is greater than the number of characters in the control, the return value is zero.

Remarks

Use the EM_LINEINDEX message to retrieve a character index for a given line number within a multiline edit control.

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_LINEINDEX


EM_LINESCROLL

The EM_LINESCROLL message scrolls the text in a multiline edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_LINESCROLL,            // message to send
  (WPARAM) wParam,          // horizontal scroll increment
  (LPARAM) lParam          // vertical scroll increment
);

Parameters

wParam
Edit controls: Specifies the number of characters to scroll horizontally.

Rich edit controls: This parameter is not used; it must be zero.

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

Edit controls: The EM_LINESCROLL message scrolls the text vertically or horizontally in a multiline edit control. The EM_LINESCROLL message can be used to scroll horizontally past the last character of any line.

Rich Edit: The EM_LINESCROLL message scrolls the text vertically in a multiline edit control. For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages


EM_POSFROMCHAR

The EM_POSFROMCHAR message retrieves the client area coordinates of a specified character in an edit control. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_POSFROMCHAR,           // message to send
  (WPARAM) wParam,          // coordinates or index
  (LPARAM) lParam          // index or not used
);

Parameters

wParam
Rich Edit 1.0 and 3.0: Pointer to a POINTL structure that receives the client area coordinates of the character. The coordinates are in screen units and are relative to the upper-left corner of the control's client area.

Edit controls and Rich Edit 2.0: Specifies the zero-based index of the character.

lParam
Rich Edit 1.0 and 3.0: Specifies the zero-based index of the character.

Edit controls and Rich Edit 2.0: This parameter is not used.

Return Values

Rich Edit 1.0 and 3.0: The return value is not used.

Edit controls and Rich Edit 2.0: The return value contains the client area coordinates of the character. The low-order word contains the horizontal coordinate and the high-order word contains the vertical coordinate.

Remarks

A returned coordinate can be a negative value if the specified character is not displayed in the edit control's client area. The coordinates are truncated to integer values.

If the character is a line delimiter, the returned coordinates indicate a point just beyond the last visible character in the line. If the specified index is greater than the index of the last character in the control, the returned coordinates indicate the position just past the last character in the control.

Rich Edit 3.0 and later: For backward compatibility, Rich Edit 3.0 supports the syntax used by Rich Edit 2.0. If Rich Edit 3.0 detects that wParam is not a valid POINTL pointer, it assumes the message was sent using the Rich Edit 2.0 syntax. In this case, it uses the return value to return the coordinates.

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_CHARFROMPOS, POINTL


EM_REPLACESEL

The EM_REPLACESEL message replaces the current selection in an edit control with the specified text. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_REPLACESEL,            // message to send
  (WPARAM) wParam,          // undo option
  (LPARAM) lParam          // text string (LPCTSTR)
);

Parameters

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

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, WM_SETTEXT


EM_SCROLL

The EM_SCROLL message scrolls the text vertically in a multiline edit control. This message is equivalent to sending a WM_VSCROLL message to the edit control. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SCROLL,                // message to send
  (WPARAM) wParam,          // scroll action
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the action the scroll bar is to take. This parameter can 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.

lParam
This parameter is not used.

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 wParam parameter specifies an invalid value, the return value is FALSE.

Remarks

To scroll to a specific line or character position, use the EM_LINESCROLL message. To scroll the caret into view, use the EM_SCROLLCARET message.

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_LINESCROLL, EM_SCROLLCARET, WM_VSCROLL


EM_SCROLLCARET

The EM_SCROLLCARET message scrolls the caret into view in an edit control. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SCROLLCARET,           // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
This parameter is reserved for future use. It should be set to zero.
lParam
This parameter is reserved for future use. It should be set to zero.

Return Values

The return value is not meaningful.

Remarks

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_LINESCROLL, EM_SCROLL, WM_VSCROLL


EM_SETHANDLE

The EM_SETHANDLE message sets the handle of the memory that will be used by a multiline edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETHANDLE,             // message to send
  (WPARAM) wParam,          // memory buffer (HLOCAL)
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Handle to the memory buffer the edit control uses to store the currently displayed text instead of allocating its own memory. If necessary, the control reallocates this memory.
lParam
This parameter is not used.

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.

Rich Edit: The EM_SETHANDLE message is not supported. Rich edit controls do not store text as a simple array of characters.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_CANUNDO, EM_GETHANDLE, EM_GETMODIFY


EM_SETIMESTATUS

The EM_SETIMESTATUS message sets the status flags that determine how an edit control interacts with the input method editor (IME).

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETIMESTATUS,          // message to send
  (WPARAM) wParam,          // status type
  (LPARAM) lParam          // status data
);

Parameters

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

lParam
Data specific to the status type. If wParam is EMSIS_COMPOSITIONSTRING, this parameter can be one or more of the following values.
Value | Meaning
EIMES_GETCOMPSTRATONCE | If this flag is set, the edit control hooks the WM_IME_COMPOSITION message with lParam set to GCS_RESULTSTR 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 lParam parameter.

Remarks

Rich Edit: The EM_SETIMESTATUS message is not supported.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_GETIMESTATUS


EM_SETLIMITTEXT

The EM_SETLIMITTEXT message is identical to the EM_LIMITTEXT message.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_GETLIMITTEXT


EM_SETMARGINS

The EM_SETMARGINS message sets the widths of the left and right margins for an edit control. The message redraws the control to reflect the new margins. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETMARGINS,            // message to send
  (WPARAM) wParam,          // margins
  (LPARAM) lParam          // new margin width
);

Parameters

wParam
Specifies the margins to set. This parameter can be one or more of the following values.
Value | Meaning
EC_LEFTMARGIN | Sets the left margin.
EC_RIGHTMARGIN | Sets the right margin.
EC_USEFONTINFO Rich edit controls: Sets the left and right margins to a narrow width calculated using the text metrics of the control's current font. If no font has been set for the control, the margins are set to zero. The lParam parameter is ignored.

Edit controls: The EC_USEFONTINFO cannot be used in the wParam parameter. It can only be used in the lParam parameter.

lParam
The low-order word specifies the new width of the left margin, in pixels. This value is ignored if wParam does not include EC_LEFTMARGIN.

Edit controls and Rich Edit 3.0 and later: The low-order word can specify the EC_USEFONTINFO value to set the left margin to a narrow width calculated using the text metrics of the control's current font. If no font has been set for the control, the margin is set to zero.

The high-order word specifies the new width of the right margin, in pixels. This value is ignored if wParam does not include EC_RIGHTMARGIN.

Edit controls and Rich Edit 3.0 and later: The high-order word can specify the EC_USEFONTINFO value to set the right margin to a narrow width calculated using the text metrics of the control's current font. If no font has been set for the control, the margin is set to zero.

Return Values

This message does not return a value.

Remarks

Edit controls: You cannot use EC_USEFONTINFO in the wParam parameter, but you can use it in the lParam parameter.

Rich Edit: All rich edit versions support the use of EC_USEFONTINFO in the wParam parameter. However, only Rich Edit 3.0 and later support the use of EC_USEFONTINFO in the lParam parameter. For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_GETMARGINS


EM_SETMODIFY

The EM_SETMODIFY message sets or clears the modification flag for an edit control. The modification flag indicates whether the text within the edit control has been modified. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETMODIFY,             // message to send
  (WPARAM) wParam,          // modification flag setting
  (LPARAM) lParam          // not used; must be zero
);

Parameters

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.
lParam
This parameter is not used.

Return Values

This message does not return a value.

Remarks

The system automatically clears the modification flag to zero when the control is created. If the user changes the control's text, the system sets the flag to nonzero. You can send the EM_GETMODIFY message to the edit control to retrieve the current state of the flag.

Rich Edit 1.0: Objects created without the REO_DYNAMICSIZE flag will lock in their extents when the modify flag is set to FALSE.

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_GETMODIFY, REOBJECT


EM_SETPASSWORDCHAR

The EM_SETPASSWORDCHAR message sets or removes the password character for an edit control. When a password character is set, that character is displayed in place of the characters typed by the user. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETPASSWORDCHAR,       // message to send
  (WPARAM) wParam,          // character
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the character to be displayed in place of the characters typed by the user. If this parameter is zero, the control removes the current password character and displays the characters typed by the user.
lParam
This parameter is not used.

Return Values

This message does not return a value.

Remarks

When an edit control receives the EM_SETPASSWORDCHAR message, the control redraws all visible characters using the character specified by the wParam parameter. If wParam is zero, the control redraws all visible characters using the characters typed by the user.

If an edit control is created with the ES_PASSWORD style, the default password character is set to an asterisk (*). If an edit control is created without the ES_PASSWORD style, there is no password character. The ES_PASSWORD style is removed if an EM_SETPASSWORDCHAR message is sent with the wParam parameter set to zero.

Edit controls: Multiline edit controls do not support the password style or messages.

Rich Edit: Both single-line and multiline edit controls support the password style and messages. For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 2.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_GETPASSWORDCHAR


EM_SETREADONLY

The EM_SETREADONLY message sets or removes the read-only style (ES_READONLY) of an edit control. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETREADONLY,           // message to send
  (WPARAM) wParam,          // read-only option
  (LPARAM) lParam          // not used; must be zero
);

Parameters

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.
lParam
This parameter is not used.

Return Values

If the operation succeeds, the return value is nonzero.

If the operation fails, the return value 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.

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, GetWindowLong


EM_SETRECT

The EM_SETRECT message sets the formatting rectangle of a multiline edit control. The formatting rectangle is the limiting rectangle into which the control draws the text. The limiting rectangle is independent of the size of the edit control window.

This message is processed only by multiline edit controls. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETRECT,               // message to send
  (WPARAM) wParam,          // coordinate type
  (LPARAM) lParam          // new rectangle (LPRECT)
);

Parameters

wParam
Rich Edit 2.0 and later: Indicates whether lParam specifies absolute or relative coordinates. A value of zero indicates absolute coordinates. A value of 1 indicates offsets relative to the current formatting rectangle. (The offsets can be positive or negative.)

Edit controls and Rich Edit 1.0: This parameter is not used and must be zero.

lParam
Pointer to a RECT structure that specifies the new dimensions of the rectangle. If this parameter is NULL, the formatting rectangle is set to its default values.

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.

When an edit control is first created, the formatting rectangle is set to a default size. You can use the EM_SETRECT message to make the formatting rectangle larger or smaller than the edit control window.

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.

Rich Edit: The formatting rectangle does not include the selection bar, which is an unmarked area to the left of each paragraph. When the user clicks in the selection bar, the corresponding line is selected. For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_GETRECT, EM_SETRECTNP, RECT


EM_SETRECTNP

The EM_SETRECTNP message sets the formatting rectangle of a multiline edit control. The EM_SETRECTNP message is identical to the EM_SETRECT message, except that EM_SETRECTNP does not redraw the edit control window.

The formatting rectangle is the limiting rectangle into which the control draws the text. The limiting rectangle is independent of the size of the edit control window.

This message is processed only by multiline edit controls. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETRECTNP,             // message to send
  (WPARAM) wParam,          // coordinate type
  (LPARAM) lParam          // new rectangle (LPRECT)
);

Parameters

wParam
Rich Edit 3.0 and later: Indicates whether the new rectangle contains absolute or relative coordinates. A value of zero indicates absolute coordinates. A value of 1 indicates offsets relative to the current formatting rectangle. (The offsets can be positive or negative.)

Edit controls: This parameter is not used and must be zero.

lParam
Pointer to a RECT structure that specifies the new dimensions of the rectangle. If this parameter is NULL, the formatting rectangle is set to its default values.

Return Values

This message does not return a value.

Remarks

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 3.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_SETRECT, RECT


EM_SETSEL

The EM_SETSEL message selects a range of characters in an edit control. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETSEL,                // message to send
  (WPARAM) wParam,          // starting position
  (LPARAM) lParam          // ending position
);

Parameters

wParam
Specifies the starting character position of the selection.
lParam
Specifies the ending character position of the selection.

Return Values

This message does not return a value.

Remarks

The start value can be greater than the end value. The lower of the two values specifies the character position of the first character in the selection. The higher value specifies the position of the first character beyond the selection.

The start value is the anchor point of the selection, and the end value is the active end. If the user uses the SHIFT key to adjust the size of the selection, the active end can move but the anchor point remains the same.

If the start is 0 and the end is –1, all the text in the edit control is selected. If the start is –1, any current selection is deselected.

Edit controls: The control displays a flashing caret at the end position regardless of the relative values of start and end.

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_GETSEL, EM_REPLACESEL, EM_SCROLLCARET, EM_EXSETSEL


EM_SETTABSTOPS

The EM_SETTABSTOPS message sets 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. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETTABSTOPS,           // message to send
  (WPARAM) wParam,          // number of tab stops
  (LPARAM) lParam          // array of tab stops
);

Parameters

wParam
Specifies the number of tab stops contained in the array. If this parameter is zero, the lParam 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 lParam parameter. If this parameter is greater than 1, lParam is a pointer to an array of tab stops.
lParam
Pointer to an array of unsigned integers specifying the tab stops, in dialog template units. If the wParam parameter is 1, this parameter is a pointer 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.

If all the tabs are not set, the return value 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 in the array 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.

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Windows 95/98/Me: The buffer pointed to by lParam must reside in writable memory, even though the message does not modify the array.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 3.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, InvalidateRect, MapDialogRect


EM_SETWORDBREAKPROC

The EM_SETWORDBREAKPROC message replaces an edit control's default wordwrap function with an application-defined wordwrap function. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETWORDBREAKPROC,      // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // wordwrap function
);

Parameters

wParam
This parameter is not used.
lParam
Specifies the address of the application-defined wordwrap 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 wordwrap 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 wordwrap function places this word at the beginning of the next line on the screen.

A wordwrap 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 wordwrap function breaks a line of text at a space character. The application-defined function may define the wordwrap to occur at a hyphen or a character other than the space character.

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EditWordBreakProc, EM_FMTLINES, EM_GETWORDBREAKPROC


EM_UNDO

The EM_UNDO message undoes the last edit control operation in the control's undo queue. You can send this message to either an edit control or a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_UNDO,                  // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // 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

Edit controls and Rich Edit 1.0: An undo operation can also be undone. For example, you can restore deleted text with the first EM_UNDO message, and remove the text again with a second EM_UNDO message as long as there is no intervening edit operation.

Rich Edit 2.0 and later: The undo feature is multilevel—so sending two EM_UNDO messages will undo the last two operations in the undo queue. To redo an operation, send the EM_REDO message.

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EM_CANUNDO


EN_ALIGN_LTR_EC

The EN_ALIGN_LTR_EC notification message is sent when the user has changed the edit control direction to left-to-right. The parent window of the edit control receives this notification message through a WM_COMMAND message.

Rich Edit: This message is not supported.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // window identifier, EN_ALIGN_LTR_EC
  LPARAM lParam    // handle to edit control (HWND)
);

Parameters

wParam
The low-order word specifies the window identifier.

The high-order word specifies the notification message.

lParam
Handle to the edit control sending the message.

Remarks

If there is a bidirectional language installed on your system, for example, Arabic or Hebrew, you can change the edit control direction using CTRL+LSHIFT (for left to right) and CTRL+RSHIFT (for right to left).

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, WM_COMMAND


EN_ALIGN_RTL_EC

The EN_ALIGN_RTL_EC notification message is sent when the user has changed the edit control direction to right-to-left. The parent window of the edit control receives this notification message through a WM_COMMAND message.

Rich Edit: This message is not supported.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // window identifier, EN_ALIGN_RTL_EC
  LPARAM lParam    // handle to edit control (HWND)
);

Parameters

wParam
The low-order word specifies the window identifier.

The high-order word specifies the notification message.

lParam
Handle to the edit control sending the message.

Remarks

If there is a bidirectional language installed on your system, for example, Arabic or Hebrew, you can change the edit control direction using CTRL+LSHIFT (for left to right) and CTRL+RSHIFT (for right to left).

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, WM_COMMAND


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 a WM_COMMAND message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // edit control identifier, EN_CHANGE
  LPARAM lParam    // handle to edit control (HWND)
);

Parameters

wParam
The low-order word specifies the edit control identifier.

The high-order word specifies the notification message.

lParam
Handle to the edit control.

Remarks

Rich Edit: To receive EN_CHANGE notifications, specify ENM_CHANGE in the mask sent with the EM_SETEVENTMASK message. For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.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 a WM_COMMAND message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // edit control identifier, EN_ERRSPACE
  LPARAM lParam    // handle to edit control (HWND)
);

Parameters

wParam
The low-order word specifies the edit control identifier.

The high-order word specifies the notification message.

lParam
Handle to the edit control.

Remarks

The parent window will always get a WM_COMMAND message for this event; it does not require a notification mask sent with the EM_SETEVENTMASK message.

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.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 a WM_COMMAND message. The parent window is notified before the screen is updated.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // edit control identifier, EN_HSCROLL
  LPARAM lParam    // handle to edit control (HWND)
);

Parameters

wParam
The low-order word specifies the edit control identifier.

The high-order word specifies the notification message.

lParam
Handle to the edit control.

Remarks

This message is sent for the following mouse events on the horizontal scroll bar: clicking either arrow button or clicking between the arrow button and the thumb. However, the message is not sent when clicking the scroll bar thumb itself. The message is also sent when a keyboard event causes a change in the view area of the edit control, for example, pressing HOME, END, LEFT ARROW, or RIGHT ARROW.

Rich Edit: To receive EN_HSCROLL notifications, specify ENM_SCROLL in the mask sent with the EM_SETEVENTMASK message. For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.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 a WM_COMMAND message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // edit control identifier, EN_KILLFOCUS
  LPARAM lParam    // handle to edit control (HWND)
);

Parameters

wParam
The low-order word specifies the edit control identifier.

The high-order word specifies the notification message.

lParam
Handle to the edit control.

Remarks

The parent window will always get a WM_COMMAND message for this event, it does not require a notification mask sent with WM_SETEVENTMASK.

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.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 a WM_COMMAND message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // edit control identifier, EN_MAXTEXT
  LPARAM lParam    // handle to edit control (HWND)
);

Parameters

wParam
The low-order word specifies the edit control identifier.

The high-order word specifies the notification message.

lParam
Handle to the edit control.

Remarks

The parent window will always get a WM_COMMAND message for this event, it does not require a notification mask sent with WM_SETEVENTMASK.

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, , WM_COMMAND


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 a WM_COMMAND message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // edit control identifier, EN_SETFOCUS
  LPARAM lParam    // handle to edit control (HWND)
);

Parameters

wParam
The low-order word specifies the edit control identifier.

The high-order word specifies the notification message.

lParam
Handle to the edit control.

Remarks

The parent window will always get a WM_COMMAND message for this event, it does not require a notification mask sent with WM_SETEVENTMASK.

Rich Edit: For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.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 redraw itself. 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 a WM_COMMAND message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // edit control identifier, EN_UPDATE
  LPARAM lParam    // handle to edit control (HWND)
);

Parameters

wParam
The low-order word specifies the edit control identifier.

The high-order word specifies the notification message.

lParam
Handle to the edit control.

Remarks

Rich Edit 1.0: To receive EN_UPDATE notifications, specify ENM_UPDATE in the mask sent with the EM_SETEVENTMASK message.

Rich Edit 2.0 and later: The ENM_UPDATE flag is ignored. The EN_UPDATE notification is always received. However, when Rich Edit 3.0 emulates Rich Edit 1.0, to receive EN_UPDATE notifications you must specify ENM_UPDATE in the mask sent with the EM_SETEVENTMASK message.

For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.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 or when the user scrolls the mouse wheel over the edit control. The parent window of the edit control receives this notification message through a WM_COMMAND message. The parent window is notified before the screen is updated.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // edit control identifier, EN_VSCROLL
  LPARAM lParam    // handle to edit control (HWND)
);

Parameters

wParam
The low-order word specifies the edit control identifier.

The high-order word specifies the notification message.

lParam
Handle to the edit control.

Remarks

This message is sent for the following mouse events on the vertical scroll bar: clicking either arrow button or clicking between the arrow button and the thumb. However, the message is not sent when clicking the scroll bar mouse itself. The message is also sent when a keyboard event causes a change in the view area of the edit control, for example, pressing HOME, END, PAGE UP, PAGE DOWN, UP ARROW, or DOWN ARROW.

The mouse wheel is a mouse that has a center wheel that scrolls. For more information, see The Mouse Wheel.

Rich Edit: To receive EN_VSCROLL notifications, specify ENM_SCROLL in the mask sent with the EM_SETEVENTMASK message. For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Rich Edit 1.0 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, EN_HSCROLL, WM_COMMAND


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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_CTLCOLOREDIT
  WPARAM wParam,   // handle to display context (HDC)
  LPARAM lParam    // handle to edit control (HWND)
);

Parameters

wParam
Handle to the device context for the edit control window.
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.

Remarks

By default, the DefWindowProc function selects the default system colors for the edit control.

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.

Rich Edit: This message is not supported. To set the background color for a rich edit control, use the EM_SETBKGNDCOLOR message.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Edit Controls Overview, Edit Control Messages, DefWindowProc, EM_SETBKGNDCOLOR, RealizePalette, SelectPalette, 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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_UNDO,                  // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

If the message succeeds, the return value is TRUE.

If the message fails, the return value is FALSE.

Remarks

Rich Edit: This message is not supported.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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. After the control has been created, these styles cannot be modified, except as noted.

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 98/ 2000: 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.

To change this style after the control has been created, use SetWindowLong.

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 wordwrap. If the window size changes, the wordwrapping 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. Note that, even with this set, it is still possible to paste non-digits into the edit control.

To change this style after the control has been created, use SetWindowLong.

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

To change this style after the control has been created, use SetWindowLong.

ES_PASSWORD Displays an asterisk (*) for each character typed into the edit control. This style is valid only for single-line edit controls.

To change the characters that is displayed, or set or clear this style, use the EM_SETPASSWORDCHAR message.

ES_READONLY Prevents the user from typing or editing text in the edit control.

To change this style after the control has been created, use the EM_SETREADONLY message.

ES_RIGHT Windows 98/ 2000: 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.

To change this style after the control has been created, use SetWindowLong.

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.

To change this style after the control has been created, use SetWindowLong.


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
  • Using List Boxes
  • List Box Reference


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 provides a scroll bar. The user scrolls through the list box items, and applies or removes selection status as necessary. Selecting a list box item changes its visual appearance, usually by changing the text and background colors to those specified by the relevant operating system metrics. When the user selects or deselects an item, the system sends a notification message to the parent window of the list box.

A dialog box procedure is responsible for initializing and monitoring its child windows, including any list boxes. The dialog box procedure communicates with the list box by sending messages to it and by processing the notification messages sent by the list box.

Windows NT/2000 or later: For an ANSI application, the system converts the text in a list box to Unicode using CP_ACP. This can cause problems. For example, accented Roman characters in a non-Unicode list box in Japanese Windows 2000 will come out garbled. To fix this, either compile the application as Unicode or use an owner-drawn 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 some functions specific to list boxes. The DlgDirList function replaces the contents of a list box with the names of drives, directories, and files that match a specified set of criteria. 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 drive, directory, or file from a list box without typing the location and name of the file.

Also, the GetListBoxInfo function returns the number of items per column in a specified list box.


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 begins with a specified string..
LB_FINDSTRINGEXACT | Returns the index of the string in the list box that is equal to a specified string.
LB_GETANCHORINDEX | Returns the index of the item that the mouse last selected.
LB_GETCARETINDEX | Returns the index of the item that has the focus rectangle.
LB_GETCOUNT | Returns the number of items in the list box.
LB_GETCURSEL | Returns the index of the currently selected item.
LB_GETHORIZONTALEXTENT | Returns the scrollable width, in pixels, of a list box.
LB_GETITEMDATA | Returns the value associated with the specified item.
LB_GETITEMHEIGHT | Returns the height, in pixels, of an item in a list box.
LB_GETITEMRECT | Retrieves the client coordinates of the specified list box item.
LB_GETLOCALE | Retrieves the locale of the list box. The high-order word contains the country/region code and the 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 specified item and the length of the string.
LB_GETTEXTLEN | Returns the length, in characters, of the string associated with a specified item.
LB_GETTOPINDEX | Returns the index of the first visible item in a list box.
LB_INITSTORAGE | Allocates memory for the specified number of items and their associated strings.
LB_INSERTSTRING | Inserts a string at a specified index in a list box.
LB_ITEMFROMPOINT | Retrieves the zero-based index of the item nearest the specified point in a list box.
LB_RESETCONTENT | Removes all items from a list box.
LB_SELECTSTRING | Selects the first string it finds that matches a specified prefix.
LB_SELITEMRANGE | Selects a specified range of items in a list box.
LB_SELITEMRANGEEX | Selects a specified range of items if the index of the first item in the range is less than the index of the last item in the range. Cancels the selection in the range if the index of the first item is greater than the last.
LB_SETANCHORINDEX | Sets the item that the mouse last selected to a specified item.
LB_SETCARETINDEX | Sets the focus rectangle to a specified list box item.
LB_SETCOLUMNWIDTH | Sets the width, in pixels, of all columns in a list box.
LB_SETCOUNT | Sets the number of items in a list box.
LB_SETCURSEL | Selects a specified list box item.
LB_SETHORIZONTALEXTENT | Sets the scrollable width, in pixels, of a list box.
LB_SETITEMDATA | Associates a value with a list box item.
LB_SETITEMHEIGHT | Sets the height, in pixels, of an item or items in a list box.
LB_SETLOCALE | Sets the locale of a list box and returns the previous locale identifier.
LB_SETSEL | Selects an item in a multiple-selection list box.
LB_SETTABSTOPS | Sets the tab stops to those specified in a specified array.
LB_SETTOPINDEX | Scrolls the list box so the specified item is at the top of the visible range.


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.

Function | Description
DlgDirList | Replaces the contents of a list box with the names of the subdirectories and files in a specified directory.
DlgDirSelectEx | Retrieves the current selection from a single-selection list box.
GetListBoxInfo | Retrieves information about the specified list box.


DlgDirList

The DlgDirList function replaces the contents of a list box with the names of the subdirectories and files in a specified directory. You can filter the list of names by specifying a set of file attributes. The list can optionally include mapped drives.

int DlgDirList(
  HWND hDlg,          // handle to dialog box with list box
  LPTSTR lpPathSpec,  // path or file name buffer
  int nIDListBox,     // list box identifier
  int nIDStaticPath,  // static control identifier
  UINT uFileType      // file attributes to display
);

Parameters

hDlg
[in] Handle to the dialog box that contains the list box.
lpPathSpec
[in/out] Pointer to a buffer containing a null-terminated string that specifies an absolute path, relative path, or filename. An absolute path can begin with a drive letter (for example, d:\) or a UNC name (for example, \\machinename\sharename).

The function splits the string into a directory and a filename. The function searches the directory for names that match the filename. If the string does not specify a directory, the function searches the current directory.

If the string includes a filename, the filename must contain at least one wildcard character (? or *). If the string does not include a filename, the function behaves as if you had specified the asterisk wildcard character (*) as the filename. All names in the specified directory that match the filename and have the attributes specified by the uFileType parameter are added to the list box.

nIDListBox
[in] Specifies the identifier of a list box in the hDlg dialog box. If this parameter is zero, DlgDirList does not try to fill a list box.
nIDStaticPath
[in] Specifies the identifier of a static control in the hDlg dialog box. DlgDirList sets the text of this control to display the current drive and directory. This parameter can be zero if you do not want to display the current drive and directory.
uFileType
[in] Specifies the attributes of the files or directories to be added to the list box. This parameter can 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 | All mapped drives are added to the list. 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. This is the default setting.
DDL_SYSTEM | Includes system files.
DDL_POSTMSGS | If set, DlgDirList uses the PostMessage function to send messages to the list box. If not set, DlgDirList uses the SendMessage function.

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 lpPathSpec specifies a directory, DlgDirListComboBox changes the current directory to the specified directory before filling the list box. The text of the static control identified by the nIDStaticPath parameter is set to the name of the new current directory.

DlgDirList sends the LB_RESETCONTENT and LB_DIR messages to the list box.

Windows NT 4.0 and later: If uFileType includes the DDL_DIRECTORY flag and lpPathSpec specifies a first-level directory, such as C:\TEMP, the list box will always include a ".." entry for the root directory. This is true even if the root directory has hidden or system attributes and the DDL_HIDDEN and DDL_SYSTEM flags are not specified. The root directory of an NTFS volume has hidden and system attributes.

Windows NT/2000 or later: 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.

For examples, see the following topics: Creating a Directory Listing in a Single-Selection List Box and Creating a Multiple-Selection List Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

List Boxes Overview, List Box Functions, DlgDirListComboBox, DlgDirSelectComboBoxEx, 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, // path buffer
  int nCount,      // number of characters in path buffer
  int nIDListBox   // list box identifier
);

Parameters

hDlg
[in] Handle to the dialog box that contains the list box.
lpString
[out] Pointer to a buffer that receives the selected path.
nCount
[in] Specifies the length, in TCHARs, of the buffer pointed to by lpString.
nIDListBox
[in] Specifies the 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.

For an example, see Creating a Directory Listing in a Single-Selection List Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

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


GetListBoxInfo

The GetListBoxInfo function retrieves information about the specified list box.

DWORD GetListBoxInfo(
  HWND hwnd      // handle to list box
);

Parameters

hwnd
[in] Handle to the list box whose information is to be retrieved.

Return Values

The return value is the number of items per column.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP6 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

List Boxes Overview, List Box Functions, GetComboBoxInfo


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/2000 or later: 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/98/Me: The system sends the WM_DELETEITEM message for any deleted list box or combo box item with nonzero item data.

typedef struct tagDELETEITEMSTRUCT {
    UINT      CtlType;
    UINT      CtlID;
    UINT      itemID;
    HWND      hwndItem;
    ULONG_PTR itemData;
} DELETEITEMSTRUCT, *PDELETEITEMSTRUCT;

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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_GETLISTBOXINFO
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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_ADDFILE,               // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // file name (LPCTSTR)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to a buffer that specifies 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 lParam is added must have been filled by the DlgDirList function.

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_ADDFILE messages take the shortest possible time. You can use estimates for the wParam and lParam parameters. If you overestimate, the extra memory is allocated; if you underestimate, the normal allocation is used for items that exceed the requested amount.

Windows NT/2000 or later: For an ANSI application, the system converts the text in a list box to Unicode using CP_ACP. This can cause problems. For example, accented Roman characters in a non-Unicode list box in Japanese Windows 2000 will come out garbled. To fix this, either compile the application as Unicode or use an owner-drawn list box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_ADDSTRING,             // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // string (LPCTSTR)
);

Parameters

wParam
This parameter is not used.
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, this parameter is stored as item data instead of the string to which it would otherwise point. 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.

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 messages take the shortest possible time. You can use estimates for the wParam and lParam parameters. If you overestimate, the extra memory is allocated; if you underestimate, the normal allocation is used for items that exceed the requested amount.

If the list box has WS_HSCROLL style and you add a string wider than the list box, send an LB_SETHORIZONTALEXTENT message to ensure the horizontal scrollbar appears.

Windows NT/2000 or later: For an ANSI application, the system converts the text in a list box to Unicode using CP_ACP. This can cause problems. For example, accented Roman characters in a non-Unicode list box in Japanese Windows 2000 will come out garbled. To fix this, either compile the application as Unicode or use an owner-drawn list box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

List Boxes Overview, List Box Messages, LB_DELETESTRING, LB_INSERTSTRING, LB_SELECTSTRING, LB_SETHORIZONTALEXTENT, WM_COMPAREITEM


LB_DELETESTRING

An application sends an LB_DELETESTRING message to delete a string in a list box.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_DELETESTRING,          // message to send
  (WPARAM) wParam,          // string index
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the zero-based index of the string to be deleted.

Windows 95/98/Me: 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.

lParam
This parameter is not used.

Return Values

The return value is a count of the strings remaining in the list. The return value is LB_ERR if the wParam 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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 a list box to add names to the list displayed by the list box. The message adds the names of directories and files that match a specified string and set of file attributes. LB_DIR can also add mapped drive letters to the list box.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_DIR,                   // message to send
  (WPARAM) wParam,          // file attributes (UINT)
  (LPARAM) lParam          // path or file name (LPCTSTR)
);

Parameters

wParam
Specifies the attributes of the files or directories to be added to the list box. This parameter can 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 | All mapped drives are added to the list. 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. This is the default setting.
DDL_SYSTEM | Includes system files.

lParam
Pointer to the null-terminated string that specifies an absolute path, relative path, or filename. An absolute path can begin with a drive letter (for example, d:\) or a UNC name (for example, \\machinename\sharename).

If the string specifies a filename or directory that has the attributes specified by the wParam parameter, the filename or directory is added to the list. If the filename or directory name contains wildcard characters (? or *), all files or directories that match the wildcard expression and have the attributes specified by the wParam parameter are added to the list.

Return Values

If the message succeeds, the return value is the zero-based index of the last name 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.

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_DIR messages take the shortest possible time. You can use estimates for the wParam and lParam parameters. If you overestimate, the extra memory is allocated; if you underestimate, the normal allocation is used for items that exceed the requested amount.

Windows NT 4.0 and later: If wParam includes the DDL_DIRECTORY flag and lParam specifies all the subdirectories of a first-level directory, such as C:\TEMP\*, the list box will always include a ".." entry for the root directory. This is true even if the root directory has hidden or system attributes and the DDL_HIDDEN and DDL_SYSTEM flags are not specified. The root directory of an NTFS volume has hidden and system attributes.

Windows NT/2000 or later: The list displays long filenames, if any.

Windows 95: The list displays short filenames (the 8.3 form). You can use the SHGetFileInfo or GetFullPathName functions to get the corresponding long filename.

Windows NT/2000 or later: For an ANSI application, the system converts the text in a list box to Unicode using CP_ACP. This can cause problems. For example, accented Roman characters in a non-Unicode list box in Japanese Windows 2000 will come out garbled. To fix this, either compile the application as Unicode or use an owner-drawn list box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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 begins with the specified string.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_FINDSTRING,            // message to send
  (WPARAM) wParam,          // item preceding start
  (LPARAM) lParam          // search string (LPCTSTR)
);

Parameters

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 searching from the top of the list box back to the item specified by the wParam parameter. If wParam is –1, the entire list box is searched from the beginning.

Windows 95/98/Me: 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.

lParam
Pointer to the null-terminated string that contains the string for which to search. 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 lParam parameter.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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 exactly matches the specified string, except that the search is not case sensitive.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_FINDSTRINGEXACT,       // message to send
  (WPARAM) wParam,          // item preceding start
  (LPARAM) lParam          // search string (LPCSTR)
);

Parameters

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 searching from the top of the list box back to the item specified by the wParam parameter. If wParam is – 1, the entire list box is searched from the beginning.

Windows 95/98/Me: 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.

lParam
Pointer to the null-terminated string for which to search. 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

This function is only successful if the specified string and a list box item have the same length (except for the null at the end of the specified string) and have exactly the same characters.

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 value against the value of the lParam parameter.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_GETANCHORINDEX,        // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

The return value is the index of the anchor item.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_GETCARETINDEX,         // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_GETCOUNT,              // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // 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).

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_GETCURSEL,             // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_GETHORIZONTALEXTENT,   // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // 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.

If the application does not set the horizontal extent of the list box (using LB_SETHORIZONTALEXTENT), the default horizontal extent is zero. Note that the list box does not update its horizontal extent dynamically.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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 value associated with the specified list box item.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_GETITEMDATA,           // message to send
  (WPARAM) wParam,          // item index
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the index of the item.

Windows 95/98/Me: 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.

lParam
This parameter is not used.

Return Values

The return value is the 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 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 the LB_SETITEMDATA message.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_GETITEMHEIGHT,         // message to send
  (WPARAM) wParam,          // item index
  (LPARAM) lParam          // not used; must be zero
);

Parameters

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/98/Me: 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.

lParam
This parameter is not used.

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 wParam parameter if the list box has the LBS_OWNERDRAWVARIABLE style. The return value is LB_ERR if an error occurs.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_GETITEMRECT,           // message to send
  (WPARAM) wParam,          // item index
  (LPARAM) lParam          // item coordinates (RECT *)
);

Parameters

wParam
Specifies the zero-based index of the item.

Windows 95/98/Me: 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.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

List Boxes Overview, List Box Messages, RECT


LB_GETLISTBOXINFO

[This is preliminary documentation and subject to change.]

An application sends an LB_GETLISTBOXINFO message to retrieve the number of items per column in a specified list box.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to list box
  LB_GETLISTBOXINFO,        // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam           // not used; must be zero
);

Parameters

wParam
This parameter is not used; it must be zero.
lParam
This parameter is not used; it must be zero.

Return Values

The return value is the number of items per column.

Remarks

This message is equivalent to GetListBoxInfo.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

List Boxes Overview, List Box Messages, GetListBoxInfo


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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_GETLOCALE,             // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

The return value specifies the current locale of the list box. The high-order word contains the country/region 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_GETSEL,                // message to send
  (WPARAM) wParam,          // item index
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the zero-based index of the item.

Windows 95/98/Me: 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.

lParam
This parameter is not used.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_GETSELCOUNT,           // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_GETSELITEMS,           // message to send
  (WPARAM) wParam,          // maximum number of items
  (LPARAM) lParam          // buffer for items
);

Parameters

wParam
Specifies the maximum number of selected items whose item numbers are to be placed in the buffer.

Windows 95/98/Me: 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.

lParam
Pointer to a buffer large enough for the number of integers specified by the wParam 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_GETTEXT,               // message to send
  (WPARAM) wParam,          // item index
  (LPARAM) lParam          // buffer for items (LPTSTR)
);

Parameters

wParam
Specifies the zero-based index of the string to retrieve.

Windows 95/98/Me: 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.

lParam
Pointer to the buffer that will receive the string; it is type LPTSTR which is subsequently cast to an LPARAM. 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 TCHARs, of the string.

Return Values

The return value is the length of the string, in TCHARs, excluding the terminating null character. If wParam 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 lParam parameter will receive the value associated with the item (the item data).

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_GETTEXTLEN,            // message to send
  (WPARAM) wParam,          // item index
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the zero-based index of the string.

Windows 95/98/Me: 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.

lParam
This parameter is not used.

Return Values

The return value is the length of the string, in TCHARs, 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 wParam 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_GETTOPINDEX,           // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_INITSTORAGE,           // message to send
  (WPARAM) wParam,          // number of items
  (LPARAM) lParam          // amount of memory
);

Parameters

wParam
Specifies the number of items to add.

Windows 95/98/Me: 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.

lParam
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/2000 or later: 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 wParam parameter. For Windows 2000, 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 wParam and lParam parameters. If you overestimate, the extra memory is allocated; if you underestimate, the normal allocation is used for items that exceed the requested amount.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_INSERTSTRING,          // message to send
  (WPARAM) wParam,          // item index
  (LPARAM) lParam          // string (LPCTSTR)
);

Parameters

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/98/Me: 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.

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

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_INSERTSTRING messages take the shortest possible time. You can use estimates for the wParam and lParam parameters. If you overestimate, the extra memory is allocated; if you underestimate, the normal allocation is used for items that exceed the requested amount.

If the list box has WS_HSCROLL style and you insert a string wider than the list box, send an LB_SETHORIZONTALEXTENT message to ensure the horizontal scrollbar appears.

Windows NT/2000 or later: For an ANSI application, the system converts the text in a list box to Unicode using CP_ACP. This can cause problems. For example, accented Roman characters in a non-Unicode list box in Japanese Windows 2000 will come out garbled. To fix this, either compile the application as Unicode or use an owner-drawn list box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

List Boxes Overview, List Box Messages, LB_ADDSTRING, LB_SELECTSTRING , LB_SETHORIZONTALEXTENT


LB_ITEMFROMPOINT

An application sends the LB_ITEMFROMPOINT message to retrieve the zero-based index of the item nearest the specified point in a list box.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_ITEMFROMPOINT,         // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // coordinates
);

Parameters

wParam
This parameter is not used.
lParam
The low-order word specifies the x-coordinate of a point, relative to the upper-left corner of the client area of the list box.

The high-order word 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

List Boxes Overview, List Box Messages, , MAKELPARAM


LB_RESETCONTENT

An application sends an LB_RESETCONTENT message to remove all items from a list box.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_RESETCONTENT,          // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_SELECTSTRING,          // message to send
  (WPARAM) wParam,          // item preceding start
  (LPARAM) lParam          // search string (LPCTSTR)
);

Parameters

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 wParam parameter. If wParam is –1, the entire list box is searched from the beginning.

Windows 95/98/Me: 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.

lParam
Pointer to the null-terminated string that contains the prefix for which to search. 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 lParam 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 specified as the lParam parameter of LB_SELECTSTRING.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_SELITEMRANGE,          // message to send
  (WPARAM) wParam,          // selection option
  (LPARAM) lParam          // first and last items
);

Parameters

wParam
Specifies how to set the selection. If this parameter is TRUE, the string is selected and highlighted; if it is zero, the highlight is removed and the string is no longer selected.
lParam
The low-order word specifies the zero-based index of the first item to select.

The high-order word 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

List Boxes Overview, List Box Messages, LB_SELITEMRANGEEX, LB_SETSEL, MAKELPARAM


LB_SELITEMRANGEEX

An application sends an LB_SELITEMRANGEEX message to select one or more consecutive items in a multiple-selection list box.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_SELITEMRANGEEX,        // message to send
  (WPARAM) wParam,          // first item
  (LPARAM) lParam          // last item
);

Parameters

wParam
Specifies the zero-based index of the first item to select.

Windows 95/98/Me: 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.

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 wParam parameter is less than the lParam parameter, the specified range of items is selected. If wParam is greater than or equal to lParam, the range is removed from the specified range of items. To select only one item, select two items and then deselect the unwanted item.

Use this message only with multiple-selection list boxes.

This message can select a range only within the first 65,536 items.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_SETANCHORINDEX,        // message to send
  (WPARAM) wParam,          // anchor index
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the index of the new anchor item.

Windows 95/98/Me: 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.

lParam
This parameter is not used.

Return Values

If the message succeeds, the return value is zero.

If the message fails, the return value is LB_ERR.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_SETCARETINDEX,         // message to send
  (WPARAM) wParam,          // item index
  (LPARAM) lParam          // scrolling option
);

Parameters

wParam
Specifies the zero-based index of the list box item that is to receive the focus rectangle.

Windows 95/98/Me: 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.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_SETCOLUMNWIDTH,        // message to send
  (WPARAM) wParam,          // column width
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the width, in pixels, of all columns.
lParam
This parameter is not used.

Return Values

This message does not return a value.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_SETCOUNT,              // message to send
  (WPARAM) wParam,          // count
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the new count of items in the list box.

Windows 95/98/Me: 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.

lParam
This parameter is not used.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_SETCURSEL,             // message to send
  (WPARAM) wParam,          // item index
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the zero-based index of the string that is selected. If this parameter is -1, the list box is set to have no selection.

Windows 95/98/Me: 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.

lParam
This parameter is not used.

Return Values

If an error occurs, the return value is LB_ERR. If the wParam 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_SETHORIZONTALEXTENT,   // message to send
  (WPARAM) wParam,          // horizontal scroll width
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the number of pixels by which the list box can be scrolled.

Windows 95/98/Me: The wParam parameter is limited to 16-bit values.

lParam
This parameter is not used.

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.

Note that a list box does not update its horizontal extent dynamically.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

List Boxes Overview, List Box Messages, LB_GETHORIZONTALEXTENT


LB_SETITEMDATA

An application sends an LB_SETITEMDATA message to set a value associated with the specified item in a list box.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_SETITEMDATA,           // message to send
  (WPARAM) wParam,          // item index
  (LPARAM) lParam          // value
);

Parameters

wParam
Specifies the zero-based index of the item.

Windows 95/98/Me: 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.

lParam
Specifies the 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 value contained in the lParam parameter of the LB_ADDSTRING or LB_INSERTSTRING message that added the item to the list box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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 wParam parameter. Otherwise, this message sets the height of all items in the list box.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_SETITEMHEIGHT,         // message to send
  (WPARAM) wParam,          // item index
  (LPARAM) lParam          // item height
);

Parameters

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/98/Me: 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.

lParam
Specifies the height, in pixels, of the item.

Return Values

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_SETLOCALE,             // message to send
  (WPARAM) wParam,          // locale identifier
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the locale identifier that the list box will use for sorting when adding text.
lParam
This parameter is not used.

Return Values

The return value is the previous locale identifier. If the wParam 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_SETSEL,                // message to send
  (WPARAM) wParam,          // selection option
  (LPARAM) lParam          // item index
);

Parameters

wParam
Specifies how to set the selection. If this parameter is TRUE, the string is selected and highlighted; if it is FALSE, the highlight is removed and the string is no longer selected.
lParam
Specifies the zero-based index of the string to set. If this parameter is –1, the selection is added to or removed from all strings, depending on the value of wParam.

Return Values

If an error occurs, the return value is LB_ERR.

Remarks

Use this message only with multiple-selection list boxes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_SETTABSTOPS,           // message to send
  (WPARAM) wParam,          // number of tab stops
  (LPARAM) lParam          // tab-stop array
);

Parameters

wParam
Specifies the number of tab stops in the list box.
lParam
Pointer to the first member of an array of integers containing the tab stops. The integers represent the number of quarters of the average character width for the font that is selected into the list box. For example, a tab stop of 4 is placed at 1.0 character units, and a tab stop of 6 is placed at 1.5 average character units. However, if the list box is part of a dialog box, the integers are 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 wParam is 0 and lParam is NULL, the default tab stop is two dialog template units. If wParam is 1, the list box will have tab stops separated by the distance specified by lParam.

If lParam points to more than a single value, a tab stop will be set for each value in lParam, up to the number specified by wParam.

The values specified by lParam 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.

Windows 95/98/Me: The buffer pointed to by lParam must reside in writable memory, even though the message does not modify the array.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  LB_SETTOPINDEX,           // message to send
  (WPARAM) wParam,          // item index
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the zero-based index of the item in the list box.

Windows 95/98/Me: 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.

lParam
This parameter is not used.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // list box identifier, LBN_DBLCLK
  LPARAM lParam    // handle to list box (HWND)
);

Parameters

wParam
The low-order word is the list box identifier.

The high-order word is the notification message.

lParam
Handle to the list box.

Remarks

This message is sent only by a list box that has the LBS_NOTIFY style.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

List Boxes Overview, List Box Messages, HIWORD, LBN_SELCHANGE, LOWORD, 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.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // list box identifier, LBN_ERRSPACE
  LPARAM lParam    // handle to list box (HWND)
);

Parameters

wParam
The low-order word is the list box identifier.

The high-order word is the notification message.

lParam
Handle to the list box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

List Boxes Overview, List Box Messages, HIWORD, LOWORD, 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.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // list box identifier, LBN_KILLFOCUS
  LPARAM lParam    // handle to list box (HWND)
);

Parameters

wParam
The low-order word is the list box identifier.

The high-order word is the notification message.

lParam
Handle to the list box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

List Boxes Overview, List Box Messages, HIWORD, LBN_SETFOCUS, LOWORD, 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.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // list box identifier, LBN_SELCANCEL
  LPARAM lParam    // handle to list box (HWND)
);

Parameters

wParam
The low-order word is the list box identifier.

The high-order word is the notification message.

lParam
Handle to the list box.

Remarks

This notification message applies only to list boxes with the LBS_NOTIFY style.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

List Boxes Overview, List Box Messages, HIWORD, LB_SETCURSEL, LBN_DBLCLK, LBN_SELCHANGE, LOWORD, 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.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // list box identifier, LBN_SELCHANGE
  LPARAM lParam    // handle to list box (HWND)
);

Parameters

wParam
The low-order word is the list box identifier.

The high-order word is the notification message.

lParam
Handle to the 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // list box identifier, LBN_SETFOCUS
  LPARAM lParam    // handle to list box (HWND)
);

Parameters

wParam
The low-order word is the list box identifier.

The high-order word is the notification message.

lParam
Handle to the list box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

List Boxes Overview, List Box Messages, HIWORD, LBN_KILLFOCUS, LOWORD, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_CHARTOITEM
  WPARAM wParam,   // key value and caret position
  LPARAM lParam    // handle to list box (HWND)
);

Parameters

wParam
The low-order word specifies the value of the key the user pressed.

The high-order word specifies the current position of the caret.

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

Remarks

The DefWindowProc function returns –1.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

List Boxes Overview, List Box Messages, DefWindowProc, HIWORD, LOWORD, 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 specified display device context handle.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_CTLCOLORLISTBOX
  WPARAM wParam,   // handle to DC (HDC)
  LPARAM lParam    // handle to list box (HWND)
);

Parameters

wParam
Handle to the device context for the list box.
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.

Remarks

By default, the DefWindowProc function selects the default system colors for the list box.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

List Boxes Overview, List Box Messages, DefWindowProc, RealizePalette, SelectPalette


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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_DELETEITEM
  WPARAM wParam,   // control identifier
  LPARAM lParam    // item information (LPDELETEITEMSTRUCT)
);

Parameters

wParam
Specifies the identifier of the control that sent the WM_DELETEITEM message.
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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_VKEYTOITEM
  WPARAM wParam,   // virtual-key code, caret position
  LPARAM lParam    // handle to list box (HWND)
);

Parameters

wParam
The low-order word specifies the virtual-key code of the key the user pressed.

The high-order word specifies the current position of the caret.

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

Remarks

The DefWindowProc function returns –1.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

List Boxes Overview, List Box Messages, DefWindowProc, HIWORD, LOWORD, 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. After the control has been created, these styles cannot be modified, except as noted.

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 specified 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. To change the redraw state of the control, use the WM_SETREDRAW message.
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

Rich edit controls provide a programming interface for formatting text. However, an application must implement any UI components necessary to make formatting operations available to the user. 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 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. Beginning with Rich Edit 2.0, there is also single line or multiline capabilities and plain or rich text. For information about edit controls, see Edit Controls.

  • About Rich Edit Controls
  • Rich Edit Control Reference


About Rich Edit Controls

The original specification for rich edit controls is Rich Edit 1.0; the current specification is Rich Edit 3.0. Each version of rich edit is a superset of the preceding one, except that only Asian builds of Rich Edit 1.0 have a vertical text option. 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. Note that the name of the file did not change from version 2.0 to version 3.0. This allows version 2.0 to be upgraded to version 3.0 without breaking existing code.

Rich Edit version | DLL
1.0 | Riched32.dll
2.0 | Riched20.dll
3.0 | Riched20.dll

Windows NT/Windows 2000

Microsoft® Windows NT® version 4.0 includes Rich Edit 1.0 and 2.0. Microsoft Windows® 2000 includes Rich Edit 3.0 with a Rich Edit 1.0 emulator.

Windows 98

Windows 98 includes Rich Edit 1.0 and 2.0.

Windows 95

Windows 95 includes only Rich Edit 1.0. However, Riched20.dll is compatible with Windows 95 and may be installed if an application that uses Rich Edit 2.0 has been installed.


What's New

The following topics describe the new features introduced in each version of Rich Edit.

  • Rich Edit Version 3.0
  • Rich Edit Version 2.0
  • Rich Edit Version 1.0


Rich Edit Version 3.0

Rich Edit 3.0 is a single, scalable, world-wide dynamic-link library (DLL) that offers high performance and compatibility with Microsoft® Word in a small package. New features for Rich Edit 3.0 include richer text, zoom, font binding, more powerful input method editor (IME) support, and rich complex script support (bidirectional, Indic, and Thai).

Rich Edit 3.0 includes the following features in addition to the features provided by Rich Edit 2.0.

Zoom
The zoom factor is given by a ratio.
Paragraph numbering (single-level)
Numeric, upper and lower alphabetic, or Roman numeral.
Simple tables
Deleting and inserting rows is possible, but not resizing nor wrapping inside cells. With advanced typography turned on (see EM_GETTYPOGRAPHYOPTIONS), Rich Edit 3.0 can align columns centered or flush right, and include decimals. Cells are simulated by tabs, so text tabs and carriage returns are replaced by blanks.
Normal and heading styles
Built-in normal style and heading styles 1 through 9 are supported by the EM_SETPARAFORMAT and Microsoft Text Object Model (TOM) interfaces.

More underline types
Dashed, dash-dot, dash-dot-dot, and dot underlining has been added.
Underline coloring
Underlined text can be tagged with one of 15 document choices for underline colors.
Hidden text
Marked by CHARFORMAT2 attribute. Handy for roundtripping (writing out to a file what was read in) of information that ordinarily should not be displayed.
More default hot keys
These hot keys function the same as those in Microsoft Word. For example, European accent dead keys (U.S. keyboards only). Number hot key (CTRL+L) cycles through numbering options available, starting with bullet.
HexToUnicode IME
Allows a user to convert between hexadecimal and Unicode by using hot keys.
Smart quotes
This feature is toggled on and off by CTRL+ALT+' for U.S. keyboards.
Soft hyphens
For plain text, use 0xAD. For RTF, use \-.
Italics cursor
In addition, the mouse cursor changes to a hand when over URLs.
Advanced typography option
Rich Edit 3.0 can use an advanced typography option for line breaking and display (see EM_GETTYPOGRAPHYOPTIONS). This elegant option was added primarily to facilitate handling complex scripts (bidirectional, Indic, and Thai). In addition, a number of improvements occur for simple scripts. Examples are:
  • Center, right, decimal tabs
  • Fully justified text
  • Underline averaging, which provides a uniform underline even when adjacent text runs have different font sizes.
Complex script support
Rich Edit 3.0 supports bidirectional (text with Arabic and/or Hebrew mixed with other scripts), Indic (Indian scripts like Devangari), and Thai text. For support of these complex scripts, the advanced typography and Uniscribe components, which run on Windows 95 and Windows 98, are used.
Font binding
Rich Edit 3.0 will automatically choose an appropriate font for characters that clearly do not belong to the current charset (a set of characters used in Windows) stamp. This is done by assigning charsets to text runs and associating fonts with those charsets. For more information, see Font Binding.
Charset-specific plain-text read/write options
This allows reading a file using one charset, and writing with a different charset.
UTF-8 RTF
This is recommended for cutting, copying, and pasting operations. This file format is more compact than ordinary RTF, faster, and compatible with Unicode.
Office 9 IME support (IME98)
This more powerful IME capability has been separated into an independent module. Features include:
Reconversion
In the earlier versions, the user needed to delete the final string first and then type in a new string to get to the correct candidate. This new feature enables the user to convert the final string back to composition mode, thereby allowing easy selection of a different candidate string.
Document feed
This feature provides IME98 with the text for the current paragraph, which helps IME98 perform more accurate conversion during typing.
Mouse operation
This feature provides better control over the candidate and UI windows during typing.
Caret position
This feature provides the current caret and line information, which IME98 uses to position UI windows (for example, a candidate list).
AIMM support
Users can invoke the Active Input Method Manager (AIMM) object, which enables users to enter Asian characters on U.S. systems (in Windows NT 4.0 and Windows 95).
HexToUnicode support
Users can convert between hexadecimal notation and Unicode by using hot keys.
More RTF roundtripping
RTF text that is read in from a file will be written back out intact.
Improved 1.0 compatibility mode
Rich Edit 3.0 can emulate Rich Edit 1.0 behavior. For example, it is possible to change between MBCS and Unicode character-position (cp) mappings. This feature emulates Rich Edit 1.0 in Windows 2000.
Increased freeze control
The display can be frozen over multiple API calls and then unfrozen to display the updates.
Increased undo control
Undo can be suspended and resumed (an IME requirement).
Increase/decrease font size
Increases or decreases font size to one of six standard values (12, 28, 36, 48, 72, and 80 points).


Rich Edit Version 2.0

Rich Edit version 2.0 incorporated several additional features, such as support for Unicode and Asian languages, multilevel Undo, COM interfaces, and numerous UI enhancements.

Rich Edit 2.0 includes the following features in addition to the features provided by Rich Edit 1.0.

Unicode
Unicode eases the effort in handling international text. However effort is needed to maintain compatibility with existing non-Unicode documents—that is, the ability to convert to/from non-Unicode plain and rich text. Also, substantial effort is needed to run correctly on Windows 95.
General international support
General line breaking algorithm (extension of Kinsoku rules), simple font linking, keyboard font switching.
Asian support
Level 2 (dialog box) and 3 (inline) is supported in IMEs.
Find Up/Find Down support
Searching forward and backward is supported.
Bidirectional support
This is included in Rich Edit 2.1
Multilevel undo
An extensible Undo architecture allows client to participate in application-wide Undo model.
Magellan mouse support
This is the mouse with a roller for scrolling.
Dual-font support
The keyboard can automatically switch fonts when the active font is inappropriate for current keyboard, for example, Kanji characters in Times New Roman.
Smart font apply
Font change request does not apply Western fonts to Asian characters.
Improved display
An off-screen bitmap is used when multiple fonts occur on the same line. This allows, for example, the last letter of the word cool not to be chopped off.
Transparency support
Also in windowless mode.
System selection colors
Used for selecting text.
Automatic URL recognition
Can check for a number of URL formats (for example, http:)
Microsoft Word edit UI compatibility
Selection, cursor-keypad semantics.
Microsoft Word standard EOP
The end-of-paragraph mark (CR) can also handle CRLF (carriage return, line-feed).
Plain-text as well as rich-text functionality
Single-character format and single-paragraph format.
Single-line and multiline controls
Truncate at first end-of-paragraph and no wordwrap.
Accelerator keys
Accelerator keys are supported.
Password window style
Password edit controls are supplied through EM_GETPASSWORDCHAR and EM_SETPASSWORDCHAR.
Scalable architecture
To reduce instance size.
Windowless operation and interfaces
This is provided through the ITextHost and ITextServices interfaces.
COM dual interfaces
Microsoft Text Object Model (TOM) interfaces.
CHARFORMAT2
Added font weight, background color, locale identifier, underline type, superscript and subscript (in addition to offset), disabled effect. For RTF roundtripping only, added amount to space between letters, twip size above which to kern character pair, animated-text type, various effects: font shadow/outline, all caps, small caps, hidden, embossed, imprint, and revised.
PARAFORMAT2
Added space before and after and Microsoft Word line spacing. For RTF roundtripping only, added shading weight/style, numbering start/style/tab, border space/width/sides, tab alignment/leaders, various Microsoft Word paragraph effects: RTL paragraph, keep, keep-next, page-break-before, no-line-number, no-widow-control, do-not-hyphenate, side-by-side.
More RTF roundtripping
All of the Microsoft Word FormatFont and FormatParagraph properties.
Code stability and stabilization
Examples: parameter and object validation, function invariants, reentrancy guards, object stabilization.
Strong testing infrastructure
Including extensive regressions tests.
Improved performance
Smaller working set, faster load and redisplay times, etc.
C++ code base
The code is written in C++, which provides a solid foundation on which to build Rich Edit 3.0.

With a few exceptions, Rich Edit 2.0 uses the same functions, structures, and messages as Rich Edit 1.0. Note, however, the following differences:

  • 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 2.0, if you create a Unicode rich edit control (one that expects Unicode text messages), you must 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 uses Unicode text messages. Note that the rich edit COM interfaces use Unicode text unless they encounter a code page argument.
  • Rich Edit 1.0 used CRLF character combinations for paragraph markers. Rich Edit 2.0 used only a carriage return character ('\r'). Rich Edit 3.0 uses only a carriage return character but can emulate Rich Edit 1.0 in this regard.
  • Rich Edit 2.0 introduced the following new messages.
    Message | Description
    EM_AUTOURLDETECT | Enables or disables automatic URL detection.
    EM_CANREDO | Determines whether there are any actions in the redo queue.
    EM_GETIMECOMPMODE | Retrieves the current input method editor (IME) mode.
    EM_GETLANGOPTIONS | Retrieves options for IME and Asian language support.
    EM_GETREDONAME | Retrieves the type name of the next action in the redo queue.
    EM_GETTEXTMODE | Retrieves the text mode or undo level.
    EM_GETUNDONAME | Retrieves the type name of the next action in the undo queue.
    EM_REDO | Redoes the next action in the redo queue.
    EM_SETLANGOPTIONS | Sets options for IME and Asian language support.
    EM_SETTEXTMODE | Sets the text mode or undo level.
    EM_SETUNDOLIMIT | Sets the maximum number of actions in the undo queue.
    EM_STOPGROUPTYPING | Stops grouping consecutive typing actions into the current undo action.

  • Rich Edit 2.0 introduced the following new structures.
    Structure | Description
    CHARFORMAT2 | Contains information about character formatting.
    PARAFORMAT2 | Contains information about paragraph formatting.

  • Rich Edit versions 2.0 and 3.0 do not support the following messages that were previously 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


Rich Edit Version 1.0

Rich Edit 1.0 includes the following features.

Text entry and selection
Mostly standard (system-edit control) selection and entry of text. Selection bar support (the selection bar is an unmarked area to the left of each paragraph that when clicked, selects the line). Word-wrap and auto-word-select options. Single-, double-, and triple-click selection.
ANSI (SBCS and MBCS) editing
However, there is no Unicode editing.
Basic set of character/paragraph formatting properties
See CHARFORMAT and PARAFORMAT.
Character formatting properties
Font name and size, bold, italic, solid underline, strike-out, protected, link, offset, and text color.
Paragraph formatting properties
Start indent, right indent, subsequent line offset, bullet, alignment (left, center, right), and tabs.
Find forward
Includes case-insensitive and match-whole-word options.
Message-based interface
Almost a superset of the system edit-control message set plus two interfaces, IRichEditOle and IRichEditCallback.
Embedded objects
Requires client collaboration based on IRichEditOle and IRichEditCallback interfaces.
Right-button menu support
Uses IRichEditOleCallback interface.
Drag and drop editing
Drag and drop editing is supported.
Notifications
WM_COMMAND messages sent to client plus a number of others. This is a superset of common-control notifications.
Single-level undo/redo
Behaves similarly to the system edit control. Selecting Undo reverses the last action, and that action then becomes the new Redo action.
Simple vertical text
(Asian builds only).
IME support
(Asian builds only).
WYSIWYG editing using printer metrics
This feature is needed for Microsoft® WordPad, in particular.
Cut/Copy/Paste/StreamIn/StreamOut
With plain text (CF_TEXT) or RTF with and without objects.
C code base
The code is written in C, which provides a solid and versatile foundation.
Different builds for different scripts
Rich Edit 1.0 addresses localization issues with different builds.


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 2.0 or later (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 to retrieve formatting information. Paragraph formatting attributes include alignment, tabs, indents, numbering, and simple tables. For characters, you can specify font name, 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 or PARAFORMAT2 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 or CHARFORMAT2 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 character formatting of the insertion point, 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 character formatting of the insertion point is applied to newly inserted text only if the current selection is empty (if the current selection is an insertion point). 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 always a character attribute. In Rich Edit 1.0, background color is only a property of the rich edit control. To set the default background color, use the EM_SETBKGNDCOLOR message. Note, Rich Edit does not support the WM_CTLCOLOREDIT 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 it, determine when it 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.

As an alternative to using the EM_EXGETSEL and EM_EXSETSEL messages, you can 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 characters of text, unless you extend this limit by using the EM_LIMITTEXT or EM_EXLIMITTEXT message. For selections that extend beyond the first 64KB of text, the EM_GETSEL message returns – 1. In such a case you can still use the values returned in wParam and lParam to find the start and end characters of the selection.


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.

Rich Edit 3.0 also supports the HexToUnicode IME, which allows a user to convert between hexadecimal and Unicode by using hot keys. For more information, see HexToUnicode IME.


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 wordwrap operations and when processing CTRL+LEFT ARROW key and CTRL+RIGHT ARROW 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. Usually, in an edit control, a word break occurs only after delimiters. However, different rules apply to most Asian languages.

Word-break procedures for rich edit controls also group characters into character classes, each identified by a value in the range 0x00 through 0x0F. 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.doc" (before and after the period).

A character's class can be combined with zero or more word-break flags to form an 8-bit value. When performing wordwrap operations, a rich edit control uses word-break flags to determine where it can break lines. Rich Edit uses the following word-break flags.

Flags | Description
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 the default word-break procedure for a rich edit control, with your own procedure by using the EM_SETWORDBREAKPROC message. For more information about word-break procedures, see the description of the EditWordBreakProc function.

Note This replacement is not recommended for Rich Edit control 2.0 and later, due to the complexity of multilingual word breaking.

For Rich Edit 1.0, 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. Note that Rich Edit 2.0 and later do not support EditWordBreakProcEx, EM_GETWORDBREAKPROCEX, and EM_SETWORDBREAKPROCEX.

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)
  • 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 in the data), 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 out the data), 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 the 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 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 content 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. For a list of event mask flags, see Rich Edit Control Event Mask Flags.

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

For lists of the edit control and rich edit control notification messages, see Rich Edit Notification Messages and Edit Control Notification Messages.


Font Binding

Rich Edit 3.0 will assign a charset to plain-text characters depending on their context. Some examples are:

  • Hangul symbols get HANGUL_CHARSET
  • Non-neutral ANSI characters get ANSI_CHARSET in any event
  • Chinese characters get SHIFTJIS_CHARSET if kana characters are found nearby or GB2312_CHARSET if no kana are found nearby.
  • Greek characters get GREEK_CHARSET

Note The rich edit control uses Unicode internally, so this use of charset differs from the original one used in font specifications. But CHARFORMAT has a well-defined place for the charset. It also helps with some anomalies in Microsoft® Windows® 95, where Unicode can't always be used.

Neutral characters like blanks and digits are assigned a charset depending on their context. For example, a blank surrounded by characters of the same charset gets that charset. Neutrals and digits used for bidirectional text are assigned charsets in a way based on the Unicode bidirectional algorithm.

Once charsets are assigned, Rich Edit scans the text around the insertion point forward and backward to find the nearest fonts that have been used for the charsets. If no font is found for a charset, rich edit uses the font chosen by the client for that charset. If the client hasn't specified a font for the charset, rich edit uses the default font for that charset. If the client wants some other font, the client can always change it, but this approach will work most of the time. The current default font choices are based on the following table. Note that the default fonts are set per-process, and there are separate lists for UI usage and for non-UI usage.

Language | UI font name | UI font size | non-UI font name | non-UI font size
Western, CE, ME, Vietnamese | Tahoma | 8 | Arial | 10
Japanese | MS UI Gothic | 9 | MS P Gothic | 10
Korean | Gulim | 9 | Gulim | 9
Simplified Chinese | Simsun | 9 | SimSun | 10
Traditional Chinese | PMingLiU | 9 | PMingLiU | 9
Thai | MS Sans Serif | 8 | Tahoma | 14
Symbols | Wingdings | 8 | Wingdings | 10
Devanagari | Mangal | 8 | Mangal | 10
Tamil | Latha | 8 | Latha | 10
Georgian, Armenian | Arial Unicode | 8 | Arial Unicode | 10

Therefore, in the default font-binding table (entries have charset, font name, size), Rich Edit allows ANSI_CHARSET to match several charsets, while the appropriate charset matches other fonts on a one-to-one basis. More precisely, rich edit uses the ANSI_CHARSET choice whenever no other alternative is found. You will be able to specify a finer granularity than this, for example: assign a specific ARABIC_CHARSET for Arabic runs, a specific Greek font for Greek runs, for example. This finer granularity will also be used if a font with the desired charset stamp is found somewhere in the document before the area being font-bound.

Note that Rich Edit does not currently handle a missing glyph in a font that claims to support a charset but is incomplete. At display time in a complex script, Rich Edit does end up knowing that such a glyph is missing, but it does not cause the backing store to use a new font. Normally, the underlying font linking of the OS will accomplish this.


Unsupported Edit Control Functionality

Rich edit controls support most but not all functionality for 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_GETIMESTATUS | Not supported.
EM_GETMARGINS | Not supported.
EM_SETHANDLE | Rich edit controls do not store text as a simple array of characters.
EM_SETIMESTATUS | Not supported.
EM_SETMARGINS | Supported in Rich Edit 3.0.
EM_SETRECTNP | Not supported.
EM_SETTABSTOPS | The EM_SETPARAFORMAT message is used instead. Supported in Rich Edit 3.0.
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_UPPERCASE, and ES_OEMCONVERT.


Rich Edit Control Reference

This section groups messages, notification messages, and structures associated with rich edit controls. Some of these application programming interface (API) elements are also used with edit controls.

For alphabetic listings, see the following topics:

  • Rich Edit Callback Functions
  • Rich Edit Interfaces
  • Rich Edit Structures
  • Rich Edit Messages
  • Rich Edit Notification Messages

Formatting

BIDIOPTIONS
CHARFORMAT
CHARFORMAT2
EM_GETAUTOURLDETECT
EM_GETBIDIOPTIONS
EM_GETCHARFORMAT
EM_GETPARAFORMAT
EM_GETRECT
EM_GETTYPOGRAPHYOPTIONS
EM_SETBIDIOPTIONS
EM_SETBKGNDCOLOR
EM_SETCHARFORMAT
EM_SETEVENTMASK
EM_SETFONTSIZE
EM_SETLANGOPTIONS
EM_SETPALETTE
EM_SETPARAFORMAT
EM_SETRECT
EM_SETTYPOGRAPHYOPTIONS
PARAFORMAT
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_FINDTEXTEX
EM_FINDTEXTEXW
EM_FINDTEXTW
EM_GETLIMITTEXT
EM_GETSELTEXT
EM_GETTEXTEX
EM_GETTEXTLENGTHEX
EM_GETTEXTMODE
EM_GETTEXTRANGE
EM_REPLACESEL
EM_SETLIMITTEXT
EM_SETTEXTEX
EM_SETTEXTMODE
FINDTEXT
FINDTEXTEX
GETTEXTEX
GETTEXTLENGTHEX
SETTEXTEX
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_GETSCROLLPOS
EM_GETTHUMB
EM_LINEFROMCHAR
EM_LINEINDEX
EM_LINELENGTH
EM_LINESCROLL
EM_SCROLL
EM_SCROLLCARET
EM_SETSCROLLPOS
EM_SHOWSCROLLBAR

Editing Operations

EM_CANPASTE
EM_CANREDO
EM_CANUNDO
EM_EMPTYUNDOBUFFER
EM_GETEDITSTYLE
EM_GETREDONAME
EM_GETUNDONAME
EM_PASTESPECIAL
EM_RECONVERSION
EM_REDO
EM_SETUNDOLIMIT
EM_STOPGROUPTYPING
EM_UNDO
REPASTESPECIAL

Streams

EDITSTREAM
EM_STREAMIN
EM_STREAMOUT

Printing

EM_DISPLAYBAND
EM_FORMATRANGE
EM_SETTARGETDEVICE
FORMATRANGE

Bottomless Rich Edit Controls

EM_REQUESTRESIZE
EN_REQUESTRESIZE
REQRESIZE

Interfaces

EM_GETOLEINTERFACE
EM_SETOLECALLBACK
EN_OLEOPFAILED
ENOLEOPFAILED
IRichEditOle
IRichEditOleCallback
REOBJECT

Miscellaneous

EM_GETEVENTMASK
EM_GETIMECOLOR
EM_GETIMECOMPMODE
EM_GETIMEOPTIONS
EM_GETLANGOPTIONS
EM_GETMODIFY
EM_GETOPTIONS
EM_GETPUNCTUATION
EM_GETWORDWRAPMODE
EM_GETZOOM
EM_SETEVENTMASK
EM_SETIMECOLOR
EM_SETIMEOPTIONS
EM_SETMODIFY
EM_SETOPTIONS
EM_SETPUNCTUATION
EM_SETREADONLY
EM_SETWORDWRAPMODE
EM_SETZOOM
EN_CHANGE
EN_CORRECTTEXT
EN_DROPFILES
EN_ERRSPACE
EN_HSCROLL
EN_IMECHANGE
EN_KILLFOCUS
EN_LINK
EN_MAXTEXT
EN_MSGFILTER
EN_PROTECTED
EN_SAVECLIPBOARD
EN_SETFOCUS
EN_STOPNOUNDO
EN_UPDATE
EN_VSCROLL
COMPCOLOR
ENCORRECTTEXT
ENDROPFILES
ENLINK
ENPROTECTED
ENSAVECLIPBOARD
MSGFILTER
PUNCTUATION


Rich Edit Callback Functions

The following callback functions are unique to rich edit controls.

Function | Description
EditStreamCallback | An application defined–callback function used with the EM_STREAMIN and EM_STREAMOUT messages.
EditWordBreakProcEx | An application defined–callback function used with the EM_SETWORDBREAKPROCEX message.


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_PTR dwCookie, // application-defined value
  LPBYTE pbBuff,      // data buffer
  LONG cb,            // number of bytes to read or write
  LONG *pcb           // number of bytes transferred
);

Parameters

dwCookie
[in] 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
[in] 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
[in] Number of bytes to read or write.
pcb
[in] 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.
  • 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 an invalid character in the read buffer.
  • 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 an end-of-paragraph character (CR, LF, VT, LS, or PS).

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

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,  // text buffer
  LONG cchText,   // number of characters in buffer
  BYTE bCharSet,  // character set
  INT code        // word break action
);

Parameters

pchText
[in] 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
[in] Number of characters in the buffer in the direction specified by code.
bCharSet
[in] Character set of the text.
code
[in] Word break action. Can be one of the values described for the code parameter in the EM_FINDWORDBREAK message.

Return Values

The function returns a value based on the code parameter.

code parameter | Return value
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 if the character is not.
All other values | Returns the character index of the word break.

Remarks

An application must install the callback function by specifying the address of the callback function in an EM_SETWORDBREAKPROCEX message.

For Rich Edit 2.0 and later,Rich Edit no longer supports EditWordBreakProcEx. Users can send EM_SETWORDBREAKPROC to set EditWordBreakProc, which is now enhanced to support the passing of Unicode text.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Callback Functions, EditWordBreakProc, EM_FINDWORDBREAK, EM_SETWORDBREAKPROCEX


Rich Edit Interfaces

The rich edit control supports the client functionality defined by COM. The control provides full support for most COM client features. It does not support linking to its contents. The client is responsible for dialogs and error messages, managing storage for COM 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 interfaces are used with rich text edit controls.

Interface | Description
IRichEditOle | An interface used by the client of a rich text edit control to carry out OLE-related operations.
IRichEditOleCallback | An interface used by a rich text edit control to retrieve OLE-related information from its client.


IRichEditOle

The IRichEditOle interface specifies an interface used by the client of a rich text edit control to carry out OLE-related operations. The IRichEditOle interface also supports the ITextDocument interface. For more information on this, see Interface from Window Messages. The IRichEditOle interface has the following methods.

Vtable Order

Method | Description
QueryInterface | Returns pointers to supported interfaces.
AddRef | Increments reference count.
Release | Decrements reference count.

IRichEditOle methods | Description
ActivateAs | Unloads objects of the old class, telling OLE to treat those objects as objects of the new class and reloading the objects.
ContextSensitiveHelp | Tells a rich edit control to transition into or out of context-sensitive help mode.
ConvertObject | Converts an object to a new type.
GetClientSite | Retrieves an IOleClientSite interface to use when creating a new object.
GetClipboardData | Retrieves a clipboard object for a range in an 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.
GetObjectCount | Returns the number of objects contained in a rich edit control.
HandsOffStorage | Tells a rich edit control to release its reference to the storage interface associated with the specified object.
ImportDataObject | Imports a clipboard object into a rich edit control, replacing the current selection.
InPlaceDeactivate | Tells a rich edit control to deactivate the currently active in-place object, if any.
InsertObject | Inserts an object into a rich edit control.
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.
SetDvaspect | Sets the aspect that a rich edit control uses to draw an object.
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.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.


IRichEditOle::ActivateAs

The IRichEditOle::ActivateAs method handles 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

This method returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success or an SCODE.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Interfaces, IRichEditOle


IRichEditOle::ContextSensitiveHelp

The IRichEditOle::ContextSensitiveHelp method 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 occurring.

HRESULT ContextSensitiveHelp(
  BOOL fEnterMode
);

Parameters

fEnterMode
Indicator of whether the control is entering context-sensitive help mode (TRUE) or leaving it (FALSE).

Return Values

This method returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success or an SCODE.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Interfaces, IRichEditOle


IRichEditOle::ConvertObject

The IRichEditOle::ConvertObject method converts an object to a new type. This call reloads 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 converted.
lpstrUserTypeNew
User-visible type name of the class to which the object is converted.

Return Values

This method returns success status. Use GetScode to retrieve an SCODE. The return value can be S_OK on success, E_INVALIDARG if the index is invalid, or an SCODE.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Interfaces, IRichEditOle


IRichEditOle::GetClientSite

The IRichEditOle::GetClientSite method 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

lplpolesite
Pointer to the pointer variable that receives the address of the IOleClientSite interface.

Return Values

This method returns success status. Use GetScode to retrieve an SCODE. The return value can be S_OK on success or E_OUTOFMEMORY if memory could not be allocated for the client site.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Interfaces, IRichEditOle


IRichEditOle::GetClipboardData

The IRichEditOle::GetClipboardData method 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 for which to create the clipboard object.
reco
The clipboard operation flag, which can be one of the following values.
Value | Meaning
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 a variable that receives a pointer to the IDataObject interface of the clipboard object representing the range specified in the lpchrg parameter.

Return Values

This message returns success status. Use GetScode to retrieve an SCODE. The return value can be S_OK on success. If the method fails, it can be one of the following values.

Value | Meaning
E_INVALIDARG | There was an invalid argument.
E_OUTOFMEMORY | There was not enough memory to do the operation.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Interfaces, CHARRANGE, IRichEditOle


IRichEditOle::GetLinkCount

The IRichEditOle::GetLinkCount method returns the number of objects in a rich edit control that are links.

LONG GetLinkCount(void);

Parameters

This function has no parameters.

Return Values

This method returns the number of links.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Interfaces, IRichEditOle


IRichEditOle::GetObject

The IRichEditOle::GetObject method 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 that specify which interfaces to return in the structure. The dwFlags parameter can be a combination of the following values.
Value | Meaning
REO_GETOBJ_POLEOBJ | Get object interface.
REO_GETOBJ_PSTG | Get storage interface.
REO_GETOBJ_POLESITE | Get site interface.
REO_GETOBJ_NO_INTERFACES | Get no interfaces.
REO_GETOBJ_ALL_INTERFACES | Get all interfaces.

Return Values

This method returns success status. Use GetScode to retrieve an SCODE. The return value can be S_OK on success, E_INVALIDARG if no buffer for the REOBJECT structure was given or if the iob or character position is invalid.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Interfaces, IRichEditOle, REOBJECT


IRichEditOle::GetObjectCount

The IRichEditOle::GetObjectCount method returns the number of objects currently contained in a rich edit control.

LONG GetObjectCount(void);

Parameters

This function has no parameters.

Return Values

This method returns the number of objects.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Interfaces, IRichEditOle


IRichEditOle::HandsOffStorage

The IRichEditOle::HandsOffStorage method 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 storage of the selected object is to be released.

Return Values

This method returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success or E_INVALIDARG if the index is invalid.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Interfaces, IPersistStorage::HandsOffStorage, IRichEditOle


IRichEditOle::ImportDataObject

The IRichEditOle::ImportDataObject method 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 an IDataObject interface for the clipboard object to import.
cf
Clipboard format to use. A value of zero will use the best available format.
hMetaPict
Handle to a metafile containing the icon view of an object. The handle is used only if the DVASPECT_ICON display aspect is required by a Paste Special operation.

Return Values

This method returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success. If the method fails, it can be one of the following values.

Value | Meaning
E_INVALIDARG | There was an invalid argument.
E_OUTOFMEMORY | There was not enough memory to do the operation.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Interfaces, IRichEditOle


IRichEditOle::InPlaceDeactivate

The IRichEditOle::InPlaceDeactivate method tells a rich edit control to deactivate the currently active in-place object, if any.

HRESULT InPlaceDeactivate(void);

Parameters

This function has no parameters.

Return Values

This method returns success status. Use GetScode to retrieve an SCODE. The return value can be S_OK on success. If there is no active in-place object, an error is not returned.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Interfaces, IRichEditOle


IRichEditOle::InsertObject

The IRichEditOle::InsertObject method 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 they are not needed.

Return Values

This method returns success status. Use GetScode to retrieve an SCODE. The return value 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.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Interfaces, IRichEditOle, REOBJECT


IRichEditOle::SaveCompleted

The IRichEditOle::SaveCompleted method tells a rich edit control that the most recent save operation has been completed and that it should hold onto 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.
lpstg
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

This method returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success or E_INVALIDARG if the index is invalid.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Interfaces, IRichEditOle


IRichEditOle::SetDvaspect

The IRichEditOle::SetDvaspect method 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

This method returns success status. Use GetScode to retrieve an SCODE. The return value can be S_OK on success or E_INVALIDARG if the index is invalid.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Interfaces, IRichEditOle


IRichEditOle::SetHostNames

The IRichEditOle::SetHostNames method 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

lpstrContainerApp
Null-terminated name of the container application.
lpstrContainerObj
Null-terminated name of the container document or object.

Return Values

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

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Interfaces, IRichEditOle


IRichEditOle::SetLinkAvailable

The IRichEditOle::SetLinkAvailable method 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 used in the set operation. The value can be TRUE or FALSE.

Return Values

This method returns success status. Use GetScode to retrieve an SCODE. The return value can be S_OK on success or E_INVALIDARG if the index is invalid.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Interfaces, IRichEditOle


IRichEditOleCallback

The IRichEditOleCallback interface specifies an interface used by a rich text edit control to retrieve OLE-related information from its client. A rich edit control 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.

Vtable Order

IUnknown methods | Description
QueryInterface | Returns pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.

IRichEditOleCallback methods | Description
ContextSensitiveHelp | Tells the application that it should transition into or out of context-sensitive help mode.
DeleteObject | Notification that an object is about to be deleted from a rich edit control.
GetClipboardData | Allows the client to supply its own clipboard object.
GetContextMenu | Queries the application for a context menu to use on a right-click event.
GetDragDropEffect | Allows the client to specify the effects of a drop operation.
GetInPlaceContext | Provides the application- and document-level interfaces and information required to support in-place activation.
GetNewStorage | Provides storage for a new object pasted from the clipboard or read in from an RTF stream.
QueryAcceptData | Called on a paste or drag to determine if the data that is pasted and dragged should be accepted.
QueryInsertObject | Queries the application as to whether an object should be inserted.
ShowContainerUI | Tells the application whether to display its container UI.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.


IRichEditOleCallback::ContextSensitiveHelp

The IRichEditOleCallback::ContextSensitiveHelp method tells the application that it should transition into or out of context-sensitive help mode. This method should implement the functionality described for IOleWindow::ContextSensitiveHelp

HRESULT ContextSensitiveHelp(
  BOOL fEnterMode
);

Parameters

fEnterMode
If TRUE, the application should enter context-sensitive help mode. If FALSE, the application should leave context-sensitive help mode.

Return Values

This method returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success. If the method fails, it can be one of the following values.

Value | Meaning
E_INVALIDARG | There was an invalid argument.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Interfaces, IRichEditOleCallback


IRichEditOleCallback::DeleteObject

The IRichEditOleCallback::DeleteObject method sends 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 IUnknown interface of the object that is being deleted.

Return Values

This method does not return a value.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Interfaces, IRichEditOleCallback


IRichEditOleCallback::GetClipboardData

The 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
The clipboard operation flag can be one of these values.
Value | Meaning
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

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

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Interfaces, CHARRANGE, IDataObject, IRichEditOleCallback


IRichEditOleCallback::GetContextMenu

The IRichEditOleCallback::GetContextMenu method queries the application for a context menu to use on a rightclick event.

HRESULT GetContextMenu(
  WORD seltype,
  LPOLEOBJECT lpoleobj,
  CHARRANGE FAR *lpchrg,
  HMENU FAR *lphmenu
);

Parameters

seltype
Selection type. The value, which specifies the contents of the new selection, can be one or more of the following values.
Value | Meaning
SEL_EMPTY | The selection is empty.
SEL_TEXT | Text.
SEL_OBJECT | At least one COM object.
SEL_MULTICHAR | More than one character of text.
SEL_MULTIOBJECT | More than one COM object.
GCM_RIGHTMOUSEDROP | Indicates that a context menu for a right-mouse drag drop should be generated. The lpoleobj parameter is a pointer to the IDataObject interface for the object being dropped.

lpoleobj
Pointer to an interface. If the seltype parameter includes the SEL_OBJECT flag, lpoleobj is a pointer to the IOleObject interface for the first selected COM object. If seltype includes the GCM_RIGHTMOUSEDROP flag, lpoleobj is a pointer to an IDataObject interface. Otherwise, lpoleobj is NULL.

If you hold on to the interface pointer, you must call AddRef to increment the object's reference count.

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

This method returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success. If the method fails, it can be one of the following values.

Value | Meaning
E_INVALIDARG | There was an invalid argument.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Interfaces, CHARRANGE, IRichEditOleCallback


IRichEditOleCallback::GetDragDropEffect

The IRichEditOleCallback::GetDragDropEffect method 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 used by a rich edit control. When fDrag is TRUE, on return, its content is set to the effect allowable by the rich edit control. When fDrag is FALSE, on return, the variable is set to the effect to use.

Return Values

This method does not return a value.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Interfaces, IDropTarget::DragEnter, IDropTarget::DragOver, IDropTarget::Drop, IRichEditOleCallback


IRichEditOleCallback::GetInPlaceContext

The IRichEditOleCallback::GetInPlaceContext method 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 is 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 is no longer needed.
lpFrameInfo
Pointer to the OLEINPLACEFRAMEINFO structure that receives the accelerator information.

Return Values

This method returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success. If the method fails, it can be one of the following values.

Value | Meaning
E_INVALIDARG | There was an invalid argument.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Interfaces, IOleInPlaceFrame, IRichEditOleCallback, OLEINPLACEFRAMEINFO


IRichEditOleCallback::GetNewStorage

The IRichEditOleCallback::GetNewStorage method provides storage for a new object pasted from the clipboard or read in from an RTF stream.

HRESULT GetNewStorage(
  LPSTORAGE FAR *lplpstg
);

Parameters

lplpstg
Pointer variable that receives the address of the IStorage interface created for the new object.

Return Values

This method returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success If the method fails, it can be one of the following values.

Value | Meaning
E_INVALIDARG | There was an invalid argument.
E_OUTOFMEMORY | There was not enough memory to do the operation.

Remarks

This method must be implemented to allow cut, copy, paste, drag, and drop operations of COM objects.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Interfaces, IRichEditOleCallback, IStorage


IRichEditOleCallback::QueryAcceptData

The IRichEditOleCallback::QueryAcceptData method is called on a paste operation or a drag event to determine if the data that is pasted or dragged should be accepted.

HRESULT QueryAcceptData(
  LPDATAOBJECT lpdataobj,
  CLIPFORMAT FAR *lpcfFormat,
  DWORD reco,
  BOOL fReally,
  HGLOBAL hMetaPict
);

Parameters

lpdataobj
Pointer to an IDataObject interface for 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
A clipboard operation flag, which can be one of these values.
Value | Meaning
RECO_DROP | Drop operation (drag and drop).
RECO_PASTE | Paste from the clipboard.

fReally
Indicates whether the drag-drop is actually happening or if it is just a query. A nonzero value indicates the paste or drop is actually happening. A zero value indicates the operation 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 a paste special operation.

Return Values

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

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Interfaces, IRichEditOleCallback


IRichEditOleCallback::QueryInsertObject

The IRichEditOleCallback::QueryInsertObject method queries the application as to whether an object should be inserted. The 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

This method returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success. If the SCODE of the result is not S_OK, the object is not inserted. If the method fails, it can be one of the following values.

Value | Meaning
E_INVALIDARG | There was an invalid argument.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Interfaces, IRichEditOleCallback


IRichEditOleCallback::ShowContainerUI

The IRichEditOleCallback::ShowContainerUI method tells the application whether to display its container UI. The rich edit control looks ahead for double-clicks and defers the call if appropriate. Applications may defer hiding adornments until an IOleInPlaceFrame::SetBorderSpace call is received.

HRESULT ShowContainerUI(
  BOOL fShow
);

Parameters

fShow
Show container UI flag. The value is TRUE if the container UI is displayed, and FALSE if it is not.

Return Values

This method returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success. If the method fails, it can be one of the following values.

Value | Meaning
E_INVALIDARG | There was an invalid argument.

Remarks

The IRichEditOleCallback::ShowContainerUI method is called by the OnUIActivate and OnUIDeActivate methods of the IOleInPlaceSite interface.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Interfaces, IOleInPlaceFrame, IRichEditOleCallback


Rich Edit Structures

The following structures are used with rich edit controls:

BIDIOPTIONS
CHARFORMAT
CHARFORMAT2
CHARRANGE
COMPCOLOR
EDITSTREAM
ENCORRECTTEXT
ENDROPFILES
ENLINK
ENOLEOPFAILED
ENPROTECTED
ENSAVECLIPBOARD
FINDTEXT
FINDTEXTEX
FORMATRANGE
GETTEXTEX
GETTEXTLENGTHEX
MSGFILTER
OBJECTPOSITIONS
PARAFORMAT
PARAFORMAT2
PUNCTUATION
REOBJECT
REPASTESPECIAL
REQRESIZE
SELCHANGE
SETTEXTEX
TEXTRANGE


BIDIOPTIONS

The BIDIOPTIONS structure contains bidirectional information about a rich edit control. This structure is used by the EM_GETBIDIOPTIONS and EM_SETBIDIOPTIONS messages to get and set the bidirectional information for a control.

typedef struct _bidioptions {
  UINT    cbSize;
  WORD    wMask;
  WORD    wEffects;
} BIDIOPTIONS;

Members

cbSize
Specifies the size, in bytes, of the structure. Before passing this structure to a rich edit control, set cbSize to the size of the BIDIOPTIONS structure. The rich edit control checks the size of cbSize before sending an EM_GETBIDIOPTIONS message.
wMask
A set of mask bits that determine which of the wEffects flags will be set to 1 or 0 by the rich edit control. This approach eliminates the need to read the effects flags before changing them.

BIDIOPTIONS Masks
Value | Meaning
BOM_DEFPARADIR | Default paragraph direction—implies alignment (obsolete).
BOM_PLAINTEXT | Use plain text layout (obsolete).
BOM_NEUTRALOVERRIDE | Override neutral layout.
BOM_CONTEXTREADING | Context reading order.
BOM_CONTEXTALIGNMENT | Context alignment.

Obsolete bits are valid only for the bidirectional version of Rich Edit 1.0.

wEffects
A set of flags that indicate the desired or current state of the effects flags.
Value | Meaning
BOE_RTLDIR | Default paragraph direction—implies alignment (obsolete).
BOE_PLAINTEXT | Uses plain text layout (obsolete).
BOE_NEUTRALOVERRIDE | Overrides neutral layout.
BOE_CONTEXTREADING | Context reading order.
BOE_CONTEXTALIGNMENT | Context alignment.

Obsolete bits are valid only for the bidirectional version of Rich Edit 1.0.

Requirements

Version: Requires Rich Edit 3.0 or later (or BiDi versions).
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EM_GETBIDIOPTIONS, EM_SETBIDIOPTIONS


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 and later allows you to use either structure with the EM_GETCHARFORMAT and EM_SETCHARFORMAT messages.

typedef struct _charformat {
  UINT     cbSize;
  DWORD    dwMask;
  DWORD    dwEffects;
  LONG     yHeight;
  LONG     yOffset;
  COLORREF crTextColor;
  BYTE     bCharSet;
  BYTE     bPitchAndFamily;
  TCHAR    szFaceName[LF_FACESIZE];
} CHARFORMAT;

Members

cbSize
Size in bytes of the specified structure. This member 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, one, or more than one 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_DISABLED | RichEdit 2.0 and later: Characters are displayed with a shadow that is offset by 3/4 point or one pixel, whichever is larger.
CFE_ITALIC | Characters are italic.
CFE_STRIKEOUT | Characters are struck.
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 (1/1440 of an inch or 1/20 of a printer's point).
yOffset
Character offset, in twips, from the baseline. If the value of 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. To generate a COLORREF, use the RGB macro.
bCharSet
Character set value. The bCharSet member can be one of the values specified for the lfCharSet member of the LOGFONT structure. Rich Edit 3.0 may override this value if it is invalid for the target characters.
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 name.

Remarks

This structure is used with the EM_GETCHARFORMAT and EM_SETCHARFORMAT messages.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Rich Edit Controls Overview, Rich Edit Structures, CHARFORMAT2, COLORREF, EM_GETCHARFORMAT, EM_SETCHARFORMAT, EN_PROTECTED, GetSysColor, LOGFONT, RGB


CHARFORMAT2

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;
  DWORD       dwMask;
  DWORD       dwEffects;
  LONG        yHeight;
  LONG        yOffset;
  COLORREF    crTextColor;
  BYTE        bCharSet;
  BYTE        bPitchAndFamily;
  TCHAR       szFaceName[LF_FACESIZE];
  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 the 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 | The CFE_SUBSCRIPT and CFE_SUPERSCRIPT values are valid.
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. The value does not affect the way the control displays the text. This value applies only to versions earlier than Rich Edit 3.0.
CFE_AUTOBACKCOLOR | The background color is the return value of GetSysColor (COLOR_WINDOW). If this flag is set, crBackColor member is ignored.
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_DISABLED | Characters are displayed with a shadow that is offset by 3/4 point or one pixel, whichever is larger.
CFE_EMBOSS | Characters are embossed. The value does not affect how the control displays the text.
CFE_HIDDEN | For Rich Edit 3.0 and later, characters are not displayed.
CFE_IMPRINT | Characters are displayed as imprinted characters. The value 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. The value 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_REVISED | Characters are marked as revised.
CFE_SHADOW | Characters are displayed as shadowed characters. The value does not affect how the control displays the text.
CFE_SMALLCAPS | Characters are in small capital letters. The value 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 (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
Character offset from the baseline, in twips,. If the value of this member is positive, the character is a superscript; if the value is negative, the character is a subscript. To use this member, set the CFM_OFFSET flag in the dwMask member.
crTextColor
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. To generate a COLORREF, use the RGB macro.
bCharSet
Character set value. It 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 name. To use this member, set the CFM_FACE flag in the dwMask member.
wWeight
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
Horizontal space between letters, in twips. 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
Background color. To use this member, set the CFM_BACKCOLOR flag in the dwMask member. This member is ignored if the CFE_AUTOBACKCOLOR character effect is specified. To generate a COLORREF, use the RGB macro.
lcid
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; the value must be zero.
sStyle
Character 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. For more information see the Text Object Model documentation.
wKerning
Value of the font size, above which to kern the character (yHeight). 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 | The structure maps CHARFORMAT's bit underline to CHARFORMAT2, (that is, it performs a CHARFORMAT type of underline on this text).
CFU_UNDERLINE | Solid underlined text.
CFU_UNDERLINEDOTTED Dotted underlined text.

For versions earlier than Rich Edit 3.0, text is displayed 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
Text animation type. 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
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; the value must be zero.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Richedit.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Rich Edit Controls Overview, Rich Edit Structures, CHARFORMAT, COLORREF, EM_GETCHARFORMAT, EM_SETCHARFORMAT, EN_PROTECTED, GetSysColor, LOGFONT, MAKELCID, RGB


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
Character position index immediately preceding the first character in the range.
cpMax
Character position immediately following the last character in the range.

Requirements

Version: Requires Rich Edit 1.0 or later.
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. To generate a COLORREF, use the RGB macro.
crBackground
Color of background. To generate a COLORREF, use the RGB macro.
dwEffects
Character effect values as described for the dwEffects member in the CHARFORMAT structure.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, CHARFORMAT, COLORREF, RGB


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

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EditStreamCallback, EM_STREAMIN, EM_STREAMOUT


ENCORRECTTEXT

The ENCORRECTTEXT structure contains information about the selected text to be corrected.

typedef struct _encorrecttext {
    NMHDR nmhdr;
    CHARRANGE chrg;
    WORD seltyp;
} ENCORRECTTEXT;

Members

nmhdr
An NMHDR structure. The code member of this structure identifies the notification message being sent.
chrg
A CHARRANGE structure that specifies the range of selected characters.
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 | The new selection contains text.
SEL_OBJECT | The new selection contains at least one COM object.
SEL_MULTICHAR | The new selection contains more than one character of text.
SEL_MULTIOBJECT | The new selection contains more than one COM object.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EN_CORRECTTEXT


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

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, DragFinish, DragQueryFile, DragQueryPoint, EN_DROPFILES, WM_DROPFILES


ENLINK

The ENLINK structure contains information about an EN_LINK notification message from a rich edit control.

typedef struct _enlink {
    NMHDR nmhdr;
    UINT msg;
    WPARAM wParam;
    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.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, CHARRANGE, EN_LINK, NMHDR


ENOLEOPFAILED

The ENOLEOPFAILED structure contains information about a failed operation.

typedef struct {
    NMHDR nmhdr;
    LONG iob;
    LONG lOper;
    HRESULT hr;
} ENOLEOPFAILED;

Members

nmhdr
Notification header.
iob
Object index.
lOper
Operation that failed. This can be OLEOP_DOVERB to indicate that IOleObject::DoVerb failed.
hr
Error code returned by the object on the operation.

Requirements

Version: Requires Rich Edit 1.0 or later.
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;
    UINT msg;
    WPARAM wParam;
    LPARAM lParam;
    CHARRANGE chrg;
} ENPROTECTED;

Members

nmhdr
Notification header.
msg
Message that triggered the notification.
wParam
The wParam parameter of the message.
lParam
The lParam parameter of the message.
chrg
Current selection.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EN_PROTECTED


ENSAVECLIPBOARD

The ENSAVECLIPBOARD structure 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.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EN_SAVECLIPBOARD


FINDTEXT

The FINDTEXT structure contains information about a search operation in a rich edit control. This structure is used with the EM_FINDTEXT message.

typedef struct _findtext {
    CHARRANGE chrg;
    LPCTSTR lpstrText;
} FINDTEXT;

Members

chrg
A CHARRANGE structure that specifies the range of characters to search.
lpstrText
Pointer to the null-terminated string used in the find operation.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Rich Edit Controls Overview, Rich Edit Structures, CHARRANGE, EM_FINDTEXT, EM_FINDTEXTW


FINDTEXTEX

The FINDTEXTEX structure 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;
    LPCTSTR lpstrText;
    CHARRANGE chrgText;
} FINDTEXTEX;

Members

chrg
A CHARRANGE structure that specifies the range of characters to search.
lpstrText
Pointer to the null-terminated string to find.
chrgText
A CHARRANGE structure that specifies the range of characters in which text is found.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EM_FINDTEXTEX, EM_FINDTEXTEXW


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 measured in twips.
rcPage
Entire area of rendering device. Units are measured in twips.
chrg
Range of text to format.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EM_FORMATRANGE


GETTEXTEX

The GETTEXTEX structure contains information about an operation to get text from a rich edit control. This structure is passed in the wParam in the EM_GETTEXTEX message.

typedef struct _gettextex {
    DWORD    cb;
    DWORD    flags;
    UINT     codepage;
    LPCSTR   lpDefaultChar;
    LPBOOL   lpUsedDefChar;
} GETTEXTEX;

Members

cb
Count of bytes in the fetched string. The size of the output buffer is lParam in the EM_GETTEXTEX message.
flags
Value specifying the CR translation. This member can be one of the following values.
Value | Meaning
GT_DEFAULT | No CR translation.
GT_USECRLF | Indicates that when copying text, each CR should be translated into a CRLF.

codepage
Code page used in the translation. It is CP_ACP for ANSI Code Page and 1200 for Unicode.
lpDefaultChar
Points to the character used if a wide character cannot be represented in the specified code page. It is used only if the code page is not 1200 (Unicode). If this member is NULL, a system default value is used.
lpUsedDefChar
Points to a flag that indicates whether a default character was used. It is used only if the code page is not 1200 (Unicode). The flag is set to TRUE if one or more wide characters in the source string cannot be represented in the specified code page. Otherwise, the flag is set to FALSE. This member may be NULL.

Remarks

The EM_GETTEXTEX message is faster when both lpDefaultChar and lpUsedDefChar are NULL.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EM_GETTEXTEX


GETTEXTLENGTHEX

The GETTEXTLENGTHEX structure contains information about how the text length of a rich edit control should be calculated. This structure is passed in the wParam in the EM_GETTEXTLENGTHEX message.

typedef struct _gettextlengthex {
    DWORD    flags;
    UINT    codepage;
} GETTEXTLENGTHEX;

Members

flags
Value specifying the method to be used in determining the text length. This member can be one or more of the following values (some values are mutually exclusive).
Value | Meaning
GTL_DEFAULT | Returns the number of characters. This is the default.
GTL_USECRLF | Computes the answer by using CR/LFs at the end of paragraphs.
GTL_PRECISE | Computes a precise answer. This approach could necessitate a conversion and thereby take longer. This flag cannot be used with the GTL_CLOSE flag. E_INVALIDARG will be returned if both are used.
GTL_CLOSE | Computes an approximate (close) answer. It is obtained quickly and can be used to set the buffer size. This flag cannot be used with the GTL_PRECISE flag. E_INVALIDARG will be returned if both are used.
GTL_NUMCHARS | Returns the number of characters. This flag cannot be used with the GTL_NUMBYTES flag. E_INVALIDARG will be returned if both are used.
GTL_NUMBYTES | Returns the number of bytes. This flag cannot be used with the GTL_NUMCHARS flag. E_INVALIDARG will be returned if both are used.

codepage
Code page used in the translation. It is CP_ACP for ANSI Code Page and 1200 for Unicode.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EM_GETTEXTLENGTHEX


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;
    WPARAM wParam;
    LPARAM lParam;
} MSGFILTER;

Members

nmhdr
A NMHDR structure. The code member of the NMHDR structure is the EN_MSGFILTER notification code that identifies the message being sent.
msg
Keyboard or mouse message identifier.
wParam
The wParam parameter of the message.
lParam
The lParam parameter of the message.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EN_MSGFILTER


OBJECTPOSITIONS

The OBJECTPOSITIONS structure contains object position information.

typedef struct _objectpositions
{
    NMHDR nmhdr;
    LONG cObjectCount;
    LONG * pcpPositions;
} OBJECTPOSITIONS;

Members

nmhdr
A NMHDR structure. The code member of this structure identifies the notification message being sent.
cObjectCount
Number of object positions.
pcpPositions
Pointer to the object positions.

Remarks

This is used in the EN_OBJECTPOSITIONS notification.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EN_OBJECTPOSITIONS, NMHDR


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.

In 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;
    DWORD dwMask;
    WORD  wNumbering;
    WORD  wReserved;       // RichEdit 2.0: this is wEffects
    LONG  dxStartIndent;
    LONG  dxRightIndent;
    LONG  dxOffset;
    WORD  wAlignment;
    SHORT cTabCount;
    LONG  rgxTabs[MAX_TAB_STOPS];
} PARAFORMAT;

Members

cbSize
Structure size, in bytes. The member must be filled before passing to the rich edit control.
dwMask
Members containing valid information or attributes to set. This parameter can be none or a combination of the following 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_RTLPARA | Rich Edit 2.0: The wEffects 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.
wReserved or wEffects
Rich Edit 1.0: This member is named wReserved. Reserved; the value must be zero.

Rich Edit 2.0: This member is named wEffects. A bit flag that specifies a paragraph effect. It is included only for compatibility with TOM interfaces; the rich edit control stores the value but does not use it to display the text. This parameter can be one of the following values.
Value | Meaning
0 | Displays text using left-to-right reading order. This is the default.
PFE_RLTPARA | Displays text using right-to-left reading order.

dxStartIndent
Indentation of the first line in the paragraph, in twips. 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, of the right indentation relative to the right margin, in twips.
dxOffset
Indentation of the second and subsequent lines of a paragraph relative to the starting indentation, in twips. The first line is indented if this member is negative or outdented if this member is positive.
wAlignment
Value specifying the paragraph alignment. This member can be one of the following values.
Value | Meaning
PFA_CENTER | Paragraphs are centered.
PFA_LEFT | Paragraphs are aligned with the left margin.
PFA_RIGHT | Paragraphs are aligned with the right margin.

cTabCount
Number of tab stops.
rgxTabs
Array of absolute tab stop positions.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EM_GETPARAFORMAT, EM_SETPARAFORMAT, PARAFORMAT2


PARAFORMAT2

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;
    DWORD dwMask;
    WORD  wNumbering;
    WORD  wEffects;
    LONG  dxStartIndent;
    LONG  dxRightIndent;
    LONG  dxOffset;
    WORD  wAlignment;
    SHORT cTabCount;
    LONG  rgxTabs[MAX_TAB_STOPS];
    LONG  dySpaceBefore;
    LONG  dySpaceAfter;
    LONG  dyLineSpacing;
    SHORT sStyle;
    BYTE  bLineSpacingRule;
    BYTE  bOutlineLevel;
    WORD  wShadingWeight;
    WORD  wShadingStyle;
    WORD  wNumberingStart;
    WORD  wNumberingStyle;
    WORD  wNumberingTab;
    WORD  wBorderSpace;
    WORD  wBorderWidth;
    WORD  wBorders;
} PARAFORMAT2;
#define  wEffects  wReserved

Members

cbSize
Structure size, in bytes. 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
The members 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
Options used 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 versions earlier than version 3.0 do not display paragraph numbers. However, for compatibility with Microsoft Text Object Model (TOM) interfaces, wNumbering can specify one of the following values.
Value | Meaning
2 | Uses Arabic numbers (1, 2, 3, ...).
3 | Uses lowercase letters (a, b, c, ...).
4 | Uses uppercase letters (A, B, C, ...).
5 | Uses lowercase Roman numerals (i, ii, iii, ...).
6 | Uses uppercase Roman numerals (I, II, III, ...).
7 | Uses a sequence of characters beginning with the Unicode character specified by the wNumberingStart member.

The rich edit control stores the value but does not use it to display the text.

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 | Disables automatic hyphenation.
PFE_KEEP | No page break within the paragraph.
PFE_KEEPNEXT | No page break between this paragraph and the next.
PFE_NOLINENUMBER | Disables line numbering (in Rich Edit 3.0 only).
PFE_NOWIDOWCONTROL | Disables widow and orphan control for the selected paragraph.
PFE_PAGEBREAKBEFORE | Inserts a page break before the selected paragraph.
PFE_RTLPARA | Displays text using right-to-left reading order (in Rich Edit 2.1 and later).
PFE_SIDEBYSIDE | Displays paragraphs side by side.
PFE_TABLE | The paragraph is a table row.

In Rich Edit 1.0, wReserved or wEffects is reserved; the value must be zero.

dxStartIndent
Indentation of the paragraph's first line, in twips. 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
Indentation of the right side of the paragraph, relative to the right margin, in twips. To use this member, set the PFM_RIGHTINDENT flag in the dwMask member.
dxOffset
Indentation of the second and subsequent lines, relative to the indentation of the first line, in twips. The first line is indented if this member is negative or outdented if this member is positive. To use this member, set the PFM_OFFSET flag in the dwMask member.
wAlignment
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 earlier than version 3.0 display the text aligned with the left margin.
PFA_FULL_INTERWORD | Paragraphs are justified by expanding the blanks alone.

cTabCount
Number of tab stops defined in the rgxTabs array.
rgxTabs
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 eight high-order bits to store additional information about each tab stop.

Bits 24-27 can specify one of the following values to indicate the tab alignment. These bits do not affect the rich edit control display for versions earlier than 3.0.
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. These bits do not affect the rich edit control display.
Value | Meaning
0 | No leader
1 | Dotted leader
2 | Dashed leader
3 | Underlined leader
4 | Thick line leader
5 | Double line leader

dySpaceBefore
Size of the spacing above the paragraph, in twips. To use this member, set the PFM_SPACEBEFORE flag in the dwMask member. The value must be greater than or equal to zero.
dySpaceAfter
Specifies the size of the spacing below the paragraph, in twips. To use this member, set the PFM_SPACEAFTER flag in the dwMask member. The value must be greater than or equal to zero.
dyLineSpacing
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
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
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 spacingfrom one line to the next, in twips. 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 from one line to the next, in twips. 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.

bOutlineLevel
Reserved.
wShadingWeight
Percentage foreground color used 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
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
Starting number or Unicode value used 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
Numbering style used 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 Rich Edit versions earlier than 3.0 do 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 | Follows the number with a right parenthesis.
0x100 | Encloses the number in parentheses.
0x200 | Follows the number with a period..
0x300 | Displays only the number.
0x8000 | Forces Roman numerals.

wNumberingTab
Minimum space between a paragraph number and the paragraph text, in twips. Use this member in conjunction with the wNumbering member. The wNumberingTab member is included for compatibility with TOM interfaces; previous to Rich Edit 3.0, 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
The space between the border and the paragraph text, in twips. The wBorderSpace member is 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
Border width, in twips. To use this member, set the PFM_BORDER flag in the dwMask member.
wBorders
Border location, style, and color. 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

Requirements

Version: Requires Rich Edit 2.0 or later.
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;
    LPSTR  szPunctuation;
} PUNCTUATION;

Members

iSize
Size of buffer pointed to by the szPunctuation member,in bytes.
szPunctuation
Pointer to the buffer containing the punctuation characters.

Remarks

This structure is used only in Asian-language versions of the operating system.

Requirements

Version: Requires Rich Edit 1.0 Asian language only.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EM_GETPUNCTUATION, EM_SETPUNCTUATION


REOBJECT

The REOBJECT structure contains information about an object.

typedef struct _reobject {
    DWORD  cbStruct;
    LONG   cp;
    CLSID  clsid;
    LPOLEOBJECT poleobj;
    LPSTORAGE pstg;
    LPOLECLIENTSITE  polesite;
    SIZEL  sizel;
    DWORD  dvaspect;
    DWORD  dwFlags;
    DWORD  dwUser;
} REOBJECT;

Members

cbStruct
Structure size, in bytes.
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
A SIZEL structure specifying the size of the object. A 0, 0 on insertion indicates that an object is free to determine its size until the modify flag is turned off.
dvaspect
Display aspect used. See DVASPECT for an explanation of possible values.
dwFlags
Object status flag. It 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 new. This value gives the object an opportunity to save nothing and be deleted from the control automatically.
REO_DONTUSEPALETTE | Object is rendered before the creation and realization of a half-tone palette. 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 inplace 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.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richole.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, IOleClientSite, IOleObject, IRichEditOle::GetClientSite, IStorage


REPASTESPECIAL

The REPASTESPECIAL structure 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;
    DWORD_PTR  dwParam;
} REPASTESPECIAL;

Members

dwAspect
Display aspect. It can be one of the following values.
Value | Meaning
DVASPECT_CONTENT | Aspect is based on the content of the object.
DVASPECT_ICON | 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.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EM_PASTESPECIAL


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.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EN_REQUESTRESIZE


SELCHANGE

The SELCHANGE structure 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 COM object.
SEL_MULTICHAR | More than one character of text.
SEL_MULTIOBJECT | More than one COM object.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EN_SELCHANGE


SETTEXTEX

The SETTEXTEX structure specifies which code page (if any) to use in setting text, whether the text replaces all the text in the control or just the selection, and whether the undo state is to be preserved.

typedef struct _settextex {
    DWORD flags;
    UINT  codepage;
} SETTEXTEX;

Members

flags
Option flags. It can be any reasonable combination of the following flags.
Value | Meaning
ST_DEFAULT | Deletes the undo stack, discards rich-text formatting, replaces all text.
ST_KEEPUNDO | Keeps the undo stack.
ST_SELECTION | Replaces selection and keeps rich-text formatting.

codepage
The code page used to translate the text to Unicode. If codepage is 1200 (Unicode code page), no translation is done. If codepage is CP_ACP, the system code page is used.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Structures, EM_SETTEXTEX


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 terminating null character.

typedef struct _textrange {
    CHARRANGE chrg;
    LPSTR lpstrText;
} TEXTRANGE;

Members

chrg
A CHARRANGE structure that indicates the range of characters to retrieve.
lpstrText
Pointer to buffer that receives the text.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Rich Edit Controls Overview, Rich Edit Structures, CHARRANGE, 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_FINDTEXTEXW
EM_FINDTEXTW
EM_FINDWORDBREAK
EM_FORMATRANGE
EM_GETAUTOURLDETECT
EM_GETBIDIOPTIONS
EM_GETCHARFORMAT
EM_GETEDITSTYLE
EM_GETEVENTMASK
EM_GETIMECOLOR
EM_GETIMECOMPMODE
EM_GETIMEOPTIONS
EM_GETLANGOPTIONS
EM_GETOLEINTERFACE
EM_GETOPTIONS
EM_GETPARAFORMAT
EM_GETPUNCTUATION
EM_GETREDONAME
EM_GETSCROLLPOS
EM_GETSELTEXT
EM_GETTEXTEX
EM_GETTEXTLENGTHEX
EM_GETTEXTMODE
EM_GETTEXTRANGE
EM_GETTYPOGRAPHYOPTIONS
EM_GETUNDONAME
EM_GETWORDBREAKPROCEX
EM_GETWORDWRAPMODE
EM_GETZOOM
EM_HIDESELECTION
EM_PASTESPECIAL
EM_RECONVERSION
EM_REDO
EM_REQUESTRESIZE
EM_SELECTIONTYPE
EM_SETBIDIOPTIONS
EM_SETBKGNDCOLOR
EM_SETCHARFORMAT
EM_SETEDITSTYLE
EM_SETEVENTMASK
EM_SETFONTSIZE
EM_SETIMECOLOR
EM_SETIMEOPTIONS
EM_SETLANGOPTIONS
EM_SETOLECALLBACK
EM_SETOPTIONS
EM_SETPALETTE
EM_SETPARAFORMAT
EM_SETPUNCTUATION
EM_SETSCROLLPOS
EM_SETTARGETDEVICE
EM_SETTEXTEX
EM_SETTEXTMODE
EM_SETTYPOGRAPHYOPTIONS
EM_SETUNDOLIMIT
EM_SETWORDBREAKPROCEX
EM_SETWORDWRAPMODE
EM_SETZOOM
EM_SHOWSCROLLBAR
EM_STOPGROUPTYPING
EM_STREAMIN
EM_STREAMOUT


EM_AUTOURLDETECT

An EM_AUTOURLDETECT message enables or disables automatic detection of URLs by a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_AUTOURLDETECT,         // message to send
  (WPARAM) wParam,          // URL detection state
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specify TRUE to enable automatic URL detection or FALSE to disable it.
lParam
This parameter is not used.

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 URLs that begin with the following prefixes:

  • http:
  • file:
  • mailto:
  • ftp:
  • https:
  • gopher:
  • nntp:
  • prospero:
  • telnet:
  • news:
  • wais:

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

Requirements

Version: Requires Rich Edit 2.0 or later.
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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_CANPASTE,              // message to send
  (WPARAM) wParam,          // clipboard format
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the clipboard format to try. To try any format currently on the clipboard, set this parameter to zero.
lParam
This parameter is not used.

Return Values

If the clipboard format can be pasted, the return value is a nonzero value.

If the clipboard format cannot be pasted, the return value is zero.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, , SendMessage


EM_CANREDO

The EM_CANREDO message determines whether there are any actions in the control redo queue.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_CANREDO,               // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

If there are actions in the control redo queue, the return value is a nonzero value.

If the redo queue is empty, the return value is zero.

Remarks

To redo the most recent undo operation, send the EM_REDO message.

Requirements

Version: Requires Rich Edit 2.0 or later.
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 the contents of a rich edit control, as previously formatted for a device using the EM_FORMATRANGE message.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_DISPLAYBAND,           // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // display area (LPRECT)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to a RECT structure specifying the display area of the device.

Return Values

If the operation succeeds, the return value is TRUE.

If the operation fails, the return value is FALSE.

Remarks

Text and COM objects are clipped by the rectangle. The application does not need to set the clipping region.

Requirements

Version: Requires Rich Edit 1.0 or later.
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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_EXGETSEL,              // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // selection range (CHARRANGE *)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to a CHARRANGE structure that receives the selection range.

Return Values

This message does not return a value.

Requirements

Version: Requires Rich Edit 1.0 or later.
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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_EXLIMITTEXT,           // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // text limit
);

Parameters

wParam
This parameter is not used.
lParam
Specifies the maximum amount of text that can be entered. If this parameter is zero, the default maximum is used, which is 64K characters. A COM object counts as a single character.

Return Values

This message does not return a 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.

Before EM_EXLIMITTEXT is called, the default limit to the amount of text a user can enter is 32,767 characters.

Requirements

Version: Requires Rich Edit 1.0 or later.
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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_EXLINEFROMCHAR,        // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // character index
);

Parameters

wParam
This parameter is not used.
lParam
Zero-based index of the character.

Return Values

This message returns the zero-based index of the line.

Requirements

Version: Requires Rich Edit 1.0 or later.
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 COM objects in a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_EXSETSEL,              // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // selection range (CHARRANGE *)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to a CHARRANGE structure that specifies the selection range.

Return Values

The return value is the selection that is actually set.

Requirements

Version: Requires Rich Edit 1.0 or later.
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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_FINDTEXT,              // message to send
  (WPARAM) wParam,          // search options
  (LPARAM) lParam          // text information (FINDTEXT *)
);

Parameters

wParam
Specify the parameters of the search operation. This parameter can be one or more of the following values.
Value | Description
FR_DOWN Rich Edit 2.0 and later: If set, the search is from the end of the current selection to the end of the document. If not set, the search is from the end of the current selection to the beginning of the document.

Rich Edit 1.0: The FR_DOWN flag is ignored. The search is always from the end of the current selection to the end of the document.

FR_MATCHALEFHAMZA | Rich Edit 3.0 and later: If set, the search differentiates between Arabic alefs with different accents. If not set, all alefs are matched by the alef character alone.
FR_MATCHCASE | If set, the search operation is case-sensitive. If not set, the search operation is case-insensitive.
FR_MATCHDIAC | Rich Edit 3.0 and later: If set, the search operation considers Arabic and Hebrew diacritical marks. If not set, diacritical marks are ignored.
FR_MATCHKASHIDA | Rich Edit 3.0 and later: If set, the search operation considers Arabic kashidas. If not set, kashidas are ignored.
FR_WHOLEWORD | If set, the operation searches only for whole words that match the search string. If not set, the operation also searches for word fragments that match the search string.

lParam
Pointer to a FINDTEXT structure containing information about the find operation.

Return Values

If there are more matches, the return value is the zero-based character position of the next match.

If there are no more matches, the return value is –1.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.
Unicode: Declared as Unicode and ANSI messages.

See Also

Rich Edit Controls Overview, Rich Edit Messages, FINDTEXT


EM_FINDTEXTEX

The EM_FINDTEXTEX message finds text within a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,            // handle to destination window
  EM_FINDTEXTEX,          // message to send
  (WPARAM) wParam,        // search options
  (LPARAM) lParam        // text information (FINDTEXTEX *)
);

Parameters

wParam
Specifies the parameters of the search operation. This parameter can be one or more of the following values.
Value | Description
FR_DOWN Rich Edit 2.0 and later: If set, the search is from the end of the current selection to the end of the document. If not set, the search is from the end of the current selection to the beginning of the document.

Rich Edit 1.0: The FR_DOWN flag is ignored. The search is always from the end of the current selection to the end of the document.

FR_MATCHALEFHAMZA | Rich Edit 3.0 and later: If set, the search differentiates between Arabic and Hebrew alefs with different accents. If not set, all alefs are matched by the alef character alone.
FR_MATCHCASE | If set, the search operation is case-sensitive. If not set, the search operation is case-insensitive.
FR_MATCHDIAC | Rich Edit 3.0 and later: If set, the search operation considers Arabic and Hebrew diacritical marks. If not set, diacritical marks are ignored.
FR_MATCHKASHIDA | Rich Edit 3.0 and later: If set, the search operation considers Arabic and Hebrew kashidas. If not set, kashidas are ignored.
FR_WHOLEWORD | If set, the operation searches only for whole words that match the search string. If not set, the operation also searches for word fragments that match the search string.

lParam
Pointer to a FINDTEXTEX structure containing information about the find operation.

Return Values

If there are more matches, the return value is the zero-based character position of the next match.

If there are no more matches, the return value is –1.

Remarks

If the search operation finds a match, the chrgText member of the FINDTEXTEX structure returns the range of characters that contain the matching text.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.
Unicode: Declared as Unicode and ANSI messages.

See Also

Rich Edit Controls Overview, Rich Edit Messages, FINDTEXTEX


EM_FINDTEXTEXW

The EM_FINDTEXTEXW message is the Unicode version of the EM_FINDTEXTEX message It is used to locate text within the edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,            // handle to destination window
  EM_FINDTEXTEXW,         // message to send
  (WPARAM) wParam,        // search options
  (LPARAM) lParam        // find information (FINDTEXTEX *)
);

Parameters

wParam
Specifies the parameters of the search operation. This parameter can be one or more of the following values.
Value | Meaning
FR_DOWN | If set, the operation searches from the end of the current selection to the end of the document. If not set, the operation searches from the end of the current selection to the beginning of the document.
FR_WHOLEWORD | If set, the operation searches only for whole words that match the search string. If not set, the operation also searches for word fragments that match the search string.
FR_MATCHCASE | If set, the search operation is case-sensitive. If not set, the search operation is case-insensitive.
FR_MATCHALEFHAMZA | If set, the search differentiates between alefs with different accents. If not set, Arabic and Hebrew alefs with different accents are all matched by the alef character.
FR_MATCHDIAC | If set, the search operation considers diacritical marks. If not set, Arabic and Hebrew diacritical marks are ignored.
FR_MATCHKASHIDA | If set, the search operation considers kashidas. If not set, Arabic and Hebrew kashidas are ignored.

lParam
Pointer to a FINDTEXTEXW structure containing information about the find operation.

Return Values

If there are more matches, the return value is the zero-based character position of the next match.

If there are no more matches, the return value is –1.

Remarks

EM_FINDTEXTEXW uses the FINDTEXTEXW structure, while EM_FINDTEXTW uses the FINDTEXTW structure. The difference is that FINDTEXTEXW reports back the range of text that was found.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, FINDTEXTEXW


EM_FINDTEXTW

The EM_FINDTEXTW message is the Unicode version of the EM_FINDTEXT message. It is used to locate text within the edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_FINDTEXTW,             // message to send
  (WPARAM) wParam,          // search options
  (LPARAM) lParam          // text information (FINDTEXT *)
);

Parameters

wParam
Specifies the parameters of the search operation. This parameter can be one or more of the following values.
Value | Meaning
FR_DOWN | If set, the operation searches from the end of the current selection to the end of the document. If not set, the operation searches from the end of the current selection to the beginning of the document.
FR_WHOLEWORD | If set, the operation searches only for whole words that match the search string. If not set, the operation also searches for word fragments that match the search string.
FR_MATCHCASE | If set, the search operation is case-sensitive. If not set, the search operation is case-insensitive.
FR_MATCHALEFHAMZA | By default, Arabic and Hebrew alefs with different accents are all matched by the alef character. Set this flag if you want the search to differentiate between alefs with different accents.
FR_MATCHDIAC | By default, Arabic and Hebrew diacritical marks are ignored. Set this flag if you want the search operation to consider diacritical marks.
FR_MATCHKASHIDA | By default, Arabic and Hebrew kashidas are ignored. Set this flag if you want the search operation to consider kashidas.

lParam
Pointer to a FINDTEXTW structure containing information about the find operation.

Return Values

If there are more matches, the return value is the zero-based character position of the next match.

If there are no more matches, the return value is –1.

Remarks

EM_FINDTEXTW uses the FINDTEXTW structure, while EM_FINDTEXTEXW uses the FINDTEXTEXW structure. The difference is that FINDTEXTEXW reports back the range of text that was found.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, FINDTEXTW


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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_FINDWORDBREAK,         // message to send
  (WPARAM) wParam,          // find operation
  (LPARAM) lParam          // starting index
);

Parameters

wParam
Specifies the find operation. This parameter can be one of the following 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. This value is the 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 ARROW key processing. This value is the similar to WB_MOVEWORDPREV. See Remarks for more information.
WB_MOVEWORDRIGHT | Finds the next character that begins a word after the specified position. This value is used during CTRL+right key processing. This value is similar to WB_MOVEWORDNEXT. See Remarks for more information.
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. This value is the same as WB_NEXTBREAK.

lParam
Zero-based character starting position.

Return Values

The message returns a value based on the wParam parameter.

wParam | Return Value
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; otherwise it returns FALSE.
All other values | Returns the character index of the word break.

Remarks

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

Requirements

Version: Requires Rich Edit 1.0 or later.
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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_FORMATRANGE,           // message to send
  (WPARAM) wParam,          // render option
  (LPARAM) lParam          // device data (FORMATRANGE *)
);

Parameters

wParam
Specifies whether to render the text. If this parameter is a nonzero value, the text is rendered. Otherwise, the text is just measured.
lParam
Pointer to a FORMATRANGE structure containing information about the output device, or NULL to free information cached by the control.

Return Values

This message returns the index of the last character that fits in the region, plus one.

Remarks

This message is typically used with the EM_DISPLAYBAND message to format the content of rich edit control 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 lParam. In addition, after using this message for one device, you must free cached information before using it again for a different device.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_DISPLAYBAND, FORMATRANGE


EM_GETAUTOURLDETECT

The EM_GETAUTOURLDETECT message indicates whether the auto URL detection is turned on in the rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETAUTOURLDETECT,      // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

If auto-URL detection is active, the return value is 1.

If auto-URL detection is inactive, the return value is 0.

Remarks

When auto URL detection is on, Rich Edit is constantly checking typed text for a valid URL. Rich Edit recognizes URLs that start with these prefixes:

  • http:
  • file:
  • mailto:
  • ftp:
  • https:
  • gopher:
  • nntp:
  • prospero:
  • telnet:
  • news:
  • wais:
  • outlook:

Rich Edit also recognizes standard path names that start with \\. When Rich Edit locates a URL, it changes the URL text color, underlines the text, and notifies the client using EN_LINK.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EN_LINK


EM_GETBIDIOPTIONS

The EM_GETBIDIOPTIONS message indicates the current state of the bidirectional options in the rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETBIDIOPTIONS,        // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // bidi options (BIDIOPTIONS *)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to a BIDIOPTIONS structure that receives the current state of the bidirectional options in the rich edit control.

Return Values

This message does not return a value.

Remarks

This message sets the values of the wMask and wEffects members to the value of the current state of the bidirectional options in the rich edit control.

Requirements

Version: Requires Rich Edit 3.0 or later (or BiDi versions).
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, BIDIOPTIONS, EM_SETBIDIOPTIONS


EM_GETCHARFORMAT

The EM_GETCHARFORMAT message determines the current character formatting in a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETCHARFORMAT,         // message to send
  (WPARAM) wParam,          // formatting option
  (LPARAM) lParam          // format data (CHARFORMAT *)
);

Parameters

wParam
Specifies the character formatting that applies to the control. It can be one of the following values.
Value | Meaning
SCF_DEFAULT | Gets the default character formatting.
SCF_SELECTION | Gets the current selection's character formatting.

lParam
Pointer to a CHARFORMAT structure. 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

This message returns the value of the dwMask member of the CHARFORMAT structure.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, CHARFORMAT, CHARFORMAT2


EM_GETEDITSTYLE

The EM_GETEDITSTYLE message retrieves the current edit style flags.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETEDITSTYLE,          // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

The return value can be one or more of the following values.

Value | Meaning
SES_EMULATESYSEDIT | When this bit is on, rich edit attempts to emulate the system edit control.
SES_BEEPONMAXTEXT | Rich Edit will call the system beeper if the user attempts to input more than the maximum characters.
SES_EXTENDBACKCOLOR | Extends the background color all the way to the edges of the client rectangle.
SES_USEAIMM | Uses the AIMM input method component that ships with Microsoft Internet Explorer™ 4.0 or later.
SES_UPPERCASE | Converts all input characters to upper case.
SES_LOWERCASE | Converts all input characters to lower case.
SES_NOINPUTSEQUENCECHK | When this bit is on, rich edit does not verify the sequence of typed text. Some languages (such as Thai and Vietnamese) require verifying the input sequence order before submitting it to the backing store.

Requirements

Version: Requires Rich Edit 3.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_SETEDITSTYLE


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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETEVENTMASK,          // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

This message returns the event mask for the rich edit control.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_SETEVENTMASK, Rich Edit Control Event Mask Flags


EM_GETIMECOLOR

The EM_GETIMECOLOR message retrieves the Input Method Editor (IME) composition color. This message is available only in Asian-language versions of the operating system.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,            // handle to destination window
  EM_GETIMECOLOR,         // message to send
  (WPARAM) wParam,        // not used; must be zero
  (LPARAM) lParam        // composition color (COMPCOLOR *)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to a four-element array of COMPCOLOR structures that receives the composition color.

Return Values

If the operation succeeds, the return value is a nonzero value.

If the operation fails, the return value is zero.

Requirements

Version: Requires Rich Edit 1.0 Asian language only.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, COMPCOLOR


EM_GETIMECOMPMODE

An application sends an EM_GETIMECOMPMODE message to get the current IME mode for a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETIMECOMPMODE,        // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

The return value is one of the following values.

Enumerator Value | Meaning
ICM_NOTOPEN | IME is not open.
ICM_LEVEL3 | True inline mode.
ICM_LEVEL2 | Level 2.
ICM_LEVEL2_5 | Level 2.5
ICM_LEVEL2_SUI | Special UI.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages


EM_GETIMEOPTIONS

The EM_GETIMEOPTIONS message retrieves the current Input Method Editor (IME) options. This message is available only in Asian-language versions of the operating system.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETIMEOPTIONS,         // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

This message returns one or more of the IME option flag values described in the EM_SETIMEOPTIONS message.

Requirements

Version: Requires Rich Edit 1.0 Asian language only.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_SETIMEOPTIONS


EM_GETLANGOPTIONS

An application sends an EM_GETLANGOPTIONS message to get a rich edit control's option settings for input method editors (IME) and Asian language support.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETLANGOPTIONS,        // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

The return value is one or more of the following values, which indicate the current language option settings.

Flag | Meaning
IMF_AUTOFONT | If this flag is set, the control automatically changes fonts when the user explicitly changes to a different keyboard layout.
IMF_AUTOFONTSIZEADJUST | Font-bound font sizes are scaled from insertion point size according to a script. For example, Asian fonts are slightly larger than Western. This is the default.
IMF_AUTOKEYBOARD | If this flag is set, the control automatically changes the keyboard layout when the user explicitly changes to a different font, or when the user explicitly changes the insertion point to a new location in the text.
IMF_DUALFONT | Sets the control to dual-font mode. Used for Asian language text. The control uses an English font for ASCII text and an Asian font for Asian text.
IMF_IMEALWAYSSENDNOTIFY | Controls how Rich Edit notifies the client during IME composition: 0: No EN_CHANGE or EN_SELCHANGE notifications during undetermined state. Send notification when final string comes in. (default) 1: Send EN_CHANGE and EN_SELCHANGE events during undetermined state.
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.
IMF_UIFONTS | Use UI default fonts. This option is turned off by default.

Remarks

The IMF_AUTOFONT flag is set by default. The IMF_AUTOKEYBOARD and IMF_IMECANCELCOMPLETE flags are cleared by default.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_SETLANGOPTIONS, EM_SETLIMITTEXT


EM_GETOLEINTERFACE

The EM_GETOLEINTERFACE message retrieves an IRichEditOle object that a client can use to access a rich edit control's COM functionality.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,            // handle to destination window
  EM_GETOLEINTERFACE,     // message to send
  (WPARAM) wParam,        // not used; must be zero
  (LPARAM) lParam        // IRichEditOle object (LPVOID *)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to a pointer that receives the IRichEditOle object. The control calls the AddRef method for the object before returning, so the calling application must call the Release method when it is done with the object.

Return Values

If the operation succeeds, the return value is a nonzero value.

If the operation fails, the return value is zero.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, IRichEditOle


EM_GETOPTIONS

The EM_GETOPTIONS message retrieves rich edit control options.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETOPTIONS,            // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

This message returns a combination of the current option flag values described in the EM_SETOPTIONS message.

Requirements

Version: Requires Rich Edit 1.0 or later.
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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETPARAFORMAT,         // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // para format (PARAFORMAT *)
);

Parameters

wParam
This parameter is not used.
lParam
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

This message returns the value of the dwMask member of the PARAFORMAT structure.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, PARAFORMAT, PARAFORMAT2


EM_GETPUNCTUATION

The EM_GETPUNCTUATION message gets the current punctuation characters for the rich edit control. This message is available only in Asian-language versions of the operating system.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETPUNCTUATION,        // message to send
  (WPARAM) wParam,          // punctuation type
  (LPARAM) lParam          // characters (PUNCTUATION *)
);

Parameters

wParam
The punctuation type can be one of the following values.
Value | Meaning
PC_LEADING | Leading punctuation characters
PC_FOLLOWING | Following punctuation characters
PC_DELIMITER | Delimiter
PC_OVERFLOW | Not supported

lParam
Pointer to a PUNCTUATION structure that receives the punctuation characters.

Return Values

If the operation succeeds, the return value is a nonzero value.

If the operation fails, the return value is zero.

Requirements

Version: Requires Rich Edit 1.0 Asian language only.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_SETPUNCTUATION, PUNCTUATION


EM_GETREDONAME

An application sends 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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETREDONAME,           // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

If the redo queue for the control 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.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_GETUNDONAME, EM_REDO, EM_UNDO, UNDONAMEID


EM_GETSCROLLPOS

An application sends an EM_GETSCROLLPOS message to obtain the current scroll position of the edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETSCROLLPOS,          // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // scroll position (POINT *)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to a POINT structure. After calling EM_GETSCROLLPOS, this parameters contains a point in the virtual text space of the document, expressed in pixels. This point will be the point that is currently located in the upper-left corner of the edit control window.

Return Values

This message always returns 1.

Requirements

Version: Requires Rich Edit 3.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_SETSCROLLPOS


EM_GETSELTEXT

The EM_GETSELTEXT message retrieves the currently selected text in a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETSELTEXT,            // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // selected text (LPSTR)
);

Parameters

wParam
This parameter is not used.
lParam
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

This message returns the number of characters copied, not including the terminating null character.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages


EM_GETTEXTEX

The EM_GETTEXTEX message allows you to get all of the text from the rich edit control in any particular code base you want.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,            // handle to destination window
  EM_GETTEXTEX,           // message to send
  (WPARAM) wParam,        // text information (GETTEXTEX *)
  (LPARAM) lParam        // output buffer (LPCTSTR)
);

Parameters

wParam
Pointer to a GETTEXTEX structure, which indicates how to translate the text before putting it into the output buffer.
lParam
Pointer to a null-terminated string that receives the text. The size of this buffer should be placed in the cb member of the GETTEXTEX structure.

Return Values

The return value is the number of TCHARs copied into the output buffer.

Remarks

If the size of the output buffer is less than the size of the text in the control, the edit control will copy text from its beginning and place it in the buffer until the buffer is full. A null terminator will still be placed at the end of the buffer.

If ANSI text is requested, EM_GETTEXTEX uses the WideCharToMultiByte function to translate the Unicode characters to ANSI. It allows you to go from Unicode to ANSI using a particular code page. The GETTEXTEX structure contains members (lpDefaultChar and lpUsedDefChar) that are used in the translation from Unicode to ANSI.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_SETTEXTEX, GETTEXTEX, WideCharToMultiByte, WM_SETTEXT


EM_GETTEXTLENGTHEX

The EM_GETTEXTLENGTHEX message calculates text length in various ways. It is usually called before creating a buffer to receive the text from the control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,            // handle to destination window
  EM_GETTEXTLENGTHEX,     // message to send
  (WPARAM) wParam,        // text length (GETTEXTLENGTHEX *)
  (LPARAM) lParam        // not used; must be zero
);

Parameters

wParam
Pointer to a GETTEXTLENGTHEX structure that receives the text length information.
lParam
This parameter is not used.

Return Values

The message returns the number of TCHARs in the edit control, depending on the setting of the flags in the GETTEXTLENGTHEX structure. If incompatible flags were set in the flags member, the message returns E_INVALIDARG .

Remarks

This message is a fast and easy way to determine the number of characters in the Unicode version of the rich edit control. However, for a non-Unicode target code page you will potentially be converting to a combination of single-byte and double-byte characters.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, GETTEXTLENGTHEX


EM_GETTEXTMODE

An application sends an EM_GETTEXTMODE message to get the current text mode and undo level of a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETTEXTMODE,           // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

The return value is one or more values from the TEXTMODE enumeration type. The values indicate the current text mode and undo level of the control.

Requirements

Version: Requires Rich Edit 2.0 or later.
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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETTEXTRANGE,          // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // range (TEXTRANGE *)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to a TEXTRANGE structure that specifies the range of characters to retrieve and a buffer to copy the characters to.

Return Values

The message returns the number of characters copied, not including the terminating null character.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, TEXTRANGE


EM_GETTYPOGRAPHYOPTIONS

The EM_GETTYPOGRAPHYOPTIONS message returns the current state of the typography options of a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETTYPOGRAPHYOPTIONS,  // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

The return value can be one of the following values.

Value | Meaning
TO_ADVANCEDTYPOGRAPHY | Advanced typography (special line breaking and line formatting) is turned on.
TO_SIMPLELINEBREAK | Normal line breaking and formatting is used.

Remarks

You can turn on advanced line breaking by sending the EM_SETTYPOGRAPHYOPTIONS message. Advanced and normal line breaking may also be turned on automatically by the rich edit control if it is needed for certain languages.

Requirements

Version: Requires Rich Edit 3.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, Rich Edit Version 3.0, EM_SETTYPOGRAPHYOPTIONS


EM_GETUNDONAME

Rich Edit 2.0 and later: An application sends 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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETUNDONAME,           // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

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.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_GETREDONAME, EM_REDO, EM_UNDO, UNDONAMEID


EM_GETWORDBREAKPROCEX

The EM_GETWORDBREAKPROCEX message retrieves the address of the currently registered extended word-break procedure.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETWORDBREAKPROCEX,    // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

The message returns the address of the current procedure.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages


EM_GETWORDWRAPMODE

The EM_GETWORDWRAPMODE message gets the current word wrap and word-break options for the rich edit control. This message is available only in Asian-language versions of the operating system.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETWORDWRAPMODE,       // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

The message returns the current word wrap and word-break options.

Remarks

This message must not be sent by the application-defined, word-break procedure.

Requirements

Version: Requires Rich Edit 1.0 Asian language only.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages


EM_GETZOOM

The EM_GETZOOM message gets the current zoom ratio, which is always between 1/64 and 64.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_GETZOOM,               // message to send
  (WPARAM) wParam,          // numerator (WORD)
  (LPARAM) lParam          // denominator (WORD)
);

Parameters

wParam
Receives the numerator of the zoom ratio.
lParam
Receives the denominator of the zoom ratio.

Return Values

The message returns TRUE if message is processed, which it will be if both wParam and lParam are not NULL.

Requirements

Version: Requires Rich Edit 3.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_SETZOOM


EM_HIDESELECTION

The EM_HIDESELECTION message hides or shows the selection in a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_HIDESELECTION,         // message to send
  (WPARAM) wParam,          // visible option
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Value specifying whether to hide or show the selection. If this parameter is zero, the selection is shown. Otherwise, the selection is hidden.
lParam
This parameter is not used.

Return Values

This message does not return a value.

Requirements

Version: Requires Rich Edit 1.0 or later.
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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,          // handle to destination window
  EM_PASTESPECIAL,      // message to send
  (WPARAM) wParam,      // clipboard format
  (LPARAM) lParam      // display aspect (REPASTESPECIAL *)
);

Parameters

wParam
Specifies the clipboard format.
lParam
Pointer to a REPASTESPECIAL structure or NULL. If an object is being pasted, the REPASTESPECIAL structure is filled in with the desired display aspect. If lParam is NULL or the dwAspect member is zero, the display aspect used will be the contents of the object descriptor.

Return Values

This message does not return a value.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, REPASTESPECIAL


EM_RECONVERSION

The EM_RECONVERSION message invokes the IME reconversion dialog box.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_RECONVERSION,          // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

This message always returns zero.

Requirements

Version: Requires Rich Edit 3.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_GETLANGOPTIONS


EM_REDO

Send an EM_REDO message to a rich edit control to redo the next action in the control's redo queue.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_REDO,                  // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

If the Redo operation succeeds, the return value is a nonzero value.

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.

Requirements

Version: Requires Rich Edit 2.0 or later.
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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_REQUESTRESIZE,         // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

This message does not return a value.

Remarks

This message is useful during WM_SIZE processing for the parent of a bottomless rich edit control.

Requirements

Version: Requires Rich Edit 1.0 or later.
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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SELECTIONTYPE,         // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

If the selection is empty, the return value is SEL_EMPTY.

If the selection is not empty, the return value is a set of flags containing one or more of the following values.

Value | Contents of the selection
SEL_TEXT | Text.
SEL_OBJECT | At least one COM object.
SEL_MULTICHAR | More than one character of text.
SEL_MULTIOBJECT | More than one COM object.

Remarks

This message is useful during WM_SIZE processing for the parent of a bottomless rich edit control.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, WM_SIZE


EM_SETBIDIOPTIONS

The EM_SETBIDIOPTIONS message sets the current state of the bidirectional options in the rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETBIDIOPTIONS,        // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // bidi options (BIDIOPTIONS *)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to a BIDIOPTIONS structure that indicates how to set the state of the bidirectional options in the rich edit control.

Return Values

This message does not return a value.

Remarks

The rich edit control must be in plain text mode or EM_SETBIDIOPTIONS will not do anything.

In plain text controls, EM_SETBIDIOPTIONS automatically determines the paragraph direction and/or alignment based on the context rules. These rules state that the direction and/or alignment is derived from the first strong character in the control. A strong character is one from which text direction can be determined (see Unicode Standard version 2.0). The paragraph direction and/or alignment is applied to the default format.

EM_SETBIDIOPTIONS only switches the default paragraph format to RTL (right to left) if it finds an RTL character,

Requirements

Version: Requires Rich Edit 3.0 or later (or BiDi versions).
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, BIDIOPTIONS, EM_GETBIDIOPTIONS


EM_SETBKGNDCOLOR

The EM_SETBKGNDCOLOR message sets the background color for a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETBKGNDCOLOR,         // message to send
  (WPARAM) wParam,          // system color option
  (LPARAM) lParam          // color (COLORREF)
);

Parameters

wParam
Specifies whether to use the system color. If this parameter is a nonzero value, the background is set to the window background system color. Otherwise, the background is set to the specified color.
lParam
A COLORREF structure specifying the color if wParam is zero. To generate a COLORREF, use the RGB macro.

Return Values

This message returns the original background color.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, COLORREF, RGB


EM_SETCHARFORMAT

The EM_SETCHARFORMAT message sets character formatting in a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETCHARFORMAT,         // message to send
  (WPARAM) wParam,          // formatting options
  (LPARAM) lParam          // char format (CHARFORMAT *)
);

Parameters

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

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

The szFaceName and bCharSet may be overruled when invalid for characters, for example: Arial on kanji characters.

Return Values

If the operation succeeds, the return value is a nonzero value.

If the operation fails, the return value is zero.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, CHARFORMAT, CHARFORMAT2


EM_SETEDITSTYLE

The EM_SETEDITSTYLE message sets the current edit style flags.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETEDITSTYLE,          // message to send
  (WPARAM) wParam,          // options
  (LPARAM) lParam          // mask
);

Parameters

wParam
Specifies one of the following values.
Value | Meaning
SES_EMULATESYSEDIT | When this bit is on, rich edit attempts to emulate the system edit control.
SES_BEEPONMAXTEXT | Rich Edit will call the system beeper if the user attempts to enter more than the maximum characters.
SES_EXTENDBACKCOLOR | Extends the background color all the way to the edges of the client rectangle.
SES_USEAIMM | Uses the AIMM input method component that ships with Microsoft® Internet Explorer 4.0 or later.
SES_UPPERCASE | Converts all input characters to uppercase.
SES_LOWERCASE | Converts all input characters to lowercase.
SES_NOINPUTSEQUENCECHK | When this bit is on, rich edit does not verify the sequence of typed text. Some languages (such as Thai and Vietnamese) require verifying the input sequence order before submitting it to the backing store.
SES_XLTCRCRLFTOCR | Turns on translation of CRCRLFs to CRs. When this bit is on and a file is read in, all instances of CRCRLF will be converted to hard CRs internally. This will affect the text wrapping. Note that if such a file is saved as plain text, the CRs will be replaced by CRLFs. This is the .txt standard for plain text.

lParam
A mask consisting of one or more of the wParam values. Only the values specified in this mask will be set or cleared. This allows a single flag to be set or cleared without reading the current flag states.

Return Values

The return value is the state of the edit style flags after rich edit has attempted to implement your edit style changes. The edit style flags are a set of flags that indicate the current edit style, made up of the values in the preceding table .

Requirements

Version: Requires Rich Edit 3.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_GETEDITSTYLE


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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETEVENTMASK,          // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // event mask
);

Parameters

wParam
This parameter is not used.
lParam
New event mask for the rich edit control. For a list of event masks, see Rich Edit Control Event Mask Flags.

Return Values

This message returns the previous event mask.

Remarks

The default event mask (before any is set) is ENM_NONE.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_GETEVENTMASK, Rich Edit Control Event Mask Flags


EM_SETFONTSIZE

The EM_SETFONTSIZE message sets the font size for the selected text.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETFONTSIZE,           // message to send
  (WPARAM) wParam,          // font size delta
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Change in point size of the selected text. The result will be rounded according to values shown in the following table. This parameter should be in the range of –1637 to 1638. The resulting font size will be within the range of 1 to 1638.
lParam
This parameter is not used.

Return Values

If no error occurred, the return value is TRUE.

If an error occurred, the return value is FALSE.

Remarks

You can easily get the font size by sending the EM_GETCHARFORMAT message.

Rich Edit first adds wParam to the current font size and then uses the resulting size and the following table to determine the rounding value.

Band | Rounding value
<=12 | 1
28 | 2
36 | 0
48 | 0
72 | 0
80 | 0
> 80 | 10

If the resulting font size is not evenly divisible by the rounding value, the font size is then rounded to a number evenly divisible by the rounding value. So if the font size is less than or equal to 12, the rounding value will be 1. Similarly, if the font size is less than or equal to 28, the rounding value is 2. For values greater than 28, font sizes are rounded to the next band. So, the font size jumps to 36, 48, 72, 80. After 80, all rounding is done in increments of ten points.

The font size is rounded up or down depending on the sign of wParam. If wParam is positive, the rounding is always up. Otherwise, rounding is always down. So, if the current font size is 10 and wParam is 3, the resulting font size would be 14 (10 + 3 = 13, which is not divisible by 2, so the size rounds up to 14). Conversely, if the current font size is 14 and wParam is –3, the resulting font size would be 10 (14 – 3 = 11, which is not divisible by 2, so the size rounds down to 10).

The change is applied to each part of the selection. So, if some of the text is 10pt and some 20pt, after a call with wParam set to 1, the font sizes become 11pt and 22pt, respectively.

Additional examples are shown in the following table.

Original font size | wParam | Resulting font size
7 | 1 | 8
7 | 3 | 10
10 | 3 | 14
14 | -3 | 10
28 | 1 | 36
28 | 3 | 36
80 | 1 | 90
80 | -1 | 72

Requirements

Version: Requires Rich Edit 3.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, Rich Edit Version 3.0, EM_GETCHARFORMAT, CHARFORMAT2


EM_SETIMECOLOR

The EM_SETIMECOLOR message sets the Input Method Editor (IME) composition color. This message is available only in Asian-language versions of the operating system.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,            // handle to destination window
  EM_SETIMECOLOR,         // message to send
  (WPARAM) wParam,        // not used; must be zero
  (LPARAM) lParam        // composition color (COMPCOLOR *)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to a COMPCOLOR structure that contains the composition color to be set.

Return Values

If the operation succeeds, the return value is a nonzero value.

If the operation fails, the return value is zero.

Requirements

Version: Requires Rich Edit 1.0 Asian language only.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_GETIMECOLOR, COMPCOLOR


EM_SETIMEOPTIONS

The EM_SETIMEOPTIONS message sets the Input Method Editor (IME) options. This message is available only in Asian-language versions of the operating system.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETIMEOPTIONS,         // message to send
  (WPARAM) wParam,          // operation
  (LPARAM) lParam          // options
);

Parameters

wParam
Specifies one of the following values.
Value | Description
ECOOP_SET | Sets the options to those specified by lParam.
ECOOP_OR | Combines the specified options with the current options.
ECOOP_AND | Retains only those current options that are also specified by lParam.
ECOOP_XOR | Logically exclusive OR the current options with those specified by lParam.

lParam
Specifies one of more of the following values.
Value | Description
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 composition strings on each rich edit control.

Return Values

If the operation succeeds, the return value is a nonzero value.

If the operation fails, the return value is zero.

Requirements

Version: Requires Rich Edit 1.0 Asian language only.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_GETIMEOPTIONS


EM_SETLANGOPTIONS

An application sends an EM_SETLANGOPTIONS message to set options for input method editors (IME) and Asian language support in a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETLANGOPTIONS,        // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // language options
);

Parameters

wParam
This parameter is not used.
lParam
Specifies the language options. This parameter can be one or more of the following values.
Value | Meaning
IMF_AUTOFONT | If this flag is set, the control automatically changes fonts when the user explicitly changes to a different keyboard layout. It is useful to turn off IMF_AUTOFONT for universal Unicode fonts. This option is turned on by default (1).
IMF_AUTOFONTSIZEADJUST | Font-bound font sizes are scaled from insertion point size according to script. For example, Asian fonts are slightly larger than Western ones. This option is turned on by default (1).
IMF_AUTOKEYBOARD | If this flag is set, the control automatically changes the keyboard layout when the user explicitly changes to a different font, or when the user explicitly changes the insertion point to a new location in the text. Will be turned on automatically for bidirectional controls. For all other controls, it is turned off by default.
IMF_DUALFONT | Sets the control to dual-font mode. Used for Asian language support. The control uses an English font for ASCII text and a Asian font for Asian text.
IMF_IMEALWAYSSENDNOTIFY Controls how Rich Edit notifies the client during IME composition:

0: No EN_CHANGED or EN_SELCHANGE notifications during undetermined state. Send notification when final string comes in. (default)

1: Send EN_CHANGED and EN_SELCHANGE events during undetermined state.
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.
IMF_UIFONTS | Use user-interface default fonts. This option is turned off by default.

Return Values

This message returns a value of 1.

Remarks

The EM_SETLANGOPTIONS message controls the following:

  • Automatic font binding.
  • Automatic keyboard switching.
  • Automatic font size adjustment.
  • Use of user-interface default fonts instead of document default fonts.
  • Notifications to client during IME composition.
  • How IME aborts composition mode.

The IMF_AUTOFONT flag is set by default. The IMF_AUTOKEYBOARD and IMF_IMECANCELCOMPLETE flags are clear by default.

Requirements

Version: Requires Rich Edit 2.0 or later.
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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,            // handle to destination window
  EM_SETOLECALLBACK,      // message to send
  (WPARAM) wParam,        // not used; must be zero
  (LPARAM) lParam        // object (IRichEditOleCallback *)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to an IRichEditOleCallback object. The control calls the AddRef function for the object before returning.

Return Values

If the operation succeeds, the return value is a nonzero value.

If the operation fails, the return value is zero.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages


EM_SETOPTIONS

The EM_SETOPTIONS message sets the options for a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETOPTIONS,            // message to send
  (WPARAM) wParam,          // operation
  (LPARAM) lParam          // options
);

Parameters

wParam
Specifies the operation, which can be one of these values.
Value | Meaning
ECOOP_SET | Sets the options to those specified by lParam.
ECOOP_OR | Combines the specified options with the current options.
ECOOP_AND | Retains only those current options that are also specified by lParam.
ECOOP_XOR | Logically exclusive OR the current options with those specified by lParam.

lParam
Specifies one or more of the following values.
Value | Meaning
ECO_AUTOWORDSELECTION | Automatic selection of word on double-click.
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_SELECTIONBAR | Same as ES_SELECTIONBAR style.
ECO_VERTICAL | Same as ES_VERTICAL style. Available in Asian-language versions only.

Return Values

This message returns the current option of edit control.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, Rich Edit Control Styles


EM_SETPALETTE

An application sends an EM_SETPALETTE message to change the palette that rich edit uses for its display window.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETPALETTE,            // message to send
  (WPARAM) wParam,          // handle to palette (HPALETTE)
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Handle to the new palette used by the rich edit control.
lParam
This parameter is not used.

Return Values

This message does not return a value.

Remarks

Rich Edit assumes the palette you're passing is valid.

Requirements

Version: Requires Rich Edit 2.0 or later.
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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETPARAFORMAT,         // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // formatting (PARAFORMAT *)
);

Parameters

wParam
This parameter is not used.
lParam
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

If the operation succeeds, the return value is a nonzero value.

If the operation fails, the return value is zero.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, PARAFORMAT, PARAFORMAT2


EM_SETPUNCTUATION

The EM_SETPUNCTUATION message sets the punctuation characters for a rich edit control. This message is available only in Asian-language versions of the operating system.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETPUNCTUATION,        // message to send
  (WPARAM) wParam,          // punctuation type
  (LPARAM) lParam          // characters (PUNCTUATION *)
);

Parameters

wParam
Specifies the punctuation type, which can be one of the following values.
Value | Meaning
PC_LEADING | Leading punctuation characters.
PC_FOLLOWING | Following punctuation characters.
PC_DELIMITER | Delimiter.
PC_OVERFLOW | Not supported.

lParam
Pointer to a PUNCTUATION structure that contains the punctuation characters.

Return Values

If the operation succeeds, the return value is a nonzero value.

If the operation fails, the return value is zero.

Requirements

Version: Requires Rich Edit 1.0 Asian language only.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_GETPUNCTUATION, PUNCTUATION


EM_SETSCROLLPOS

An application sends an EM_SETSCROLLPOS message to tell the rich edit control to scroll to a particular point.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETSCROLLPOS,          // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // point (POINT *)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to a POINT structure which specifies a point in the virtual text space of the document, expressed in pixels. The document will be scrolled until this point is located in the upper-left corner of the edit control window. If you want to change the view such that the upper left corner of the view is two lines down and one character in from the left edge. You would pass a point of (7, 22).

Rich Edit checks the X and Y coordinates and adjusts them if necessary, so that a complete line is displayed at the top. It also ensures that the text is never completely scrolled off the view rectangle.

Return Values

This message always returns 1.

Requirements

Version: Requires Rich Edit 3.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_GETSCROLLPOS


EM_SETTARGETDEVICE

The EM_SETTARGETDEVICE message sets the target device and line width used for WYSIWYG formatting in a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETTARGETDEVICE,       // message to send
  (WPARAM) wParam,          // handle to DC (HDC)
  (LPARAM) lParam          // line width
);

Parameters

wParam
Handle to a device context for the target device.
lParam
Line width to use for formatting.

Return Values

If the operation succeeds, the return value is a nonzero value.

If the operation fails, the return value is zero.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages


EM_SETTEXTEX

The EM_SETTEXTEX message combines the functionality of WM_SETTEXT and EM_REPLACESEL and adds the ability to set text using a code page and to use either RTF rich text or plain text.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETTEXTEX,             // message to send
  (WPARAM) wParam,          // options (SETTEXT *)
  (LPARAM) lParam          // text (TCHAR *)
);

Parameters

wParam
Pointer to a SETTEXTEX structure that specifies flags and an optional code page to use in translating to Unicode.
lParam
Pointer to the null-terminated text to insert. This text is an ANSI string, unless the code page is 1200 (Unicode), in which case it's a Unicode string. If lParam starts with a valid RTF ASCII sequence, for example, {\rtf or {urtf, the text is read in using the RTF reader. This allows one to set rich text.

Return Values

If the operation is setting all of the text and succeeds, the return value is 1.

If the operation is setting the selection and succeeds, the return value is the number of bytes or characters copied.

If the operation fails, the return value is zero.

Requirements

Version: Requires Rich Edit 3.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_GETTEXTEX, SETTEXTEX


EM_SETTEXTMODE

An application sends 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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETTEXTMODE,           // message to send
  (WPARAM) wParam,          // new text mode
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
One or more 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.

Specify one of the following values to set the code page parameter. If you don't specify an code page value, the code page remains at its current setting.
Value | Meaning
TM_SINGLECODEPAGE | The control only allows the English keyboard and a keyboard corresponding to the default charset. For example, you could have Greek and English.
TM_MULTICODEPAGE | The control allows multiple code pages.

lParam
This parameter is not used.

Return Values

If the message succeeds, the return value is zero.

If the message fails, the return value is a nonzero value.

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 ("").

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_GETTEXTMODE, EM_SETUNDOLIMIT, TEXTMODE, WM_SETTEXT


EM_SETTYPOGRAPHYOPTIONS

The EM_SETTYPOGRAPHYOPTIONS message sets the current state of the typography options of a rich edit control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETTYPOGRAPHYOPTIONS,  // message to send
  (WPARAM) wParam,          // option
  (LPARAM) lParam          // mask
);

Parameters

wParam
Specifies one of the following values.
Value | Meaning
TO_ADVANCEDTYPOGRAPHY | Advanced line breaking and line formatting is turned on.
TO_SIMPLELINEBREAK | Normal line breaking and formatting is used.

lParam
A mask consisting of one or more of the flags in wParam. Only the flags are set in this mask will be set or cleared. This allows a single flag to be set or cleared without reading the current flag states.

Return Values

If an illegal wParam is passed, EM_SETTYPOGRAPHYOPTIONS returns FALSE.

If wParam is valid, the return value is TRUE.

Remarks

Advanced and normal line breaking may also be turned on automatically by the rich edit control if it is needed for certain languages.

Requirements

Version: Requires Rich Edit 3.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_GETTYPOGRAPHYOPTIONS


EM_SETUNDOLIMIT

An application sends an EM_SETUNDOLIMIT message to a rich edit control to set the maximum number of actions that can stored in the undo queue.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETUNDOLIMIT,          // message to send
  (WPARAM) wParam,          // maximum undo actions
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the maximum number of actions that can be stored in the undo queue.
lParam
This parameter is not used.

Return Values

The return value is the new maximum number of undo actions for the rich edit control. This value may be less than wParam 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.

Requirements

Version: Requires Rich Edit 2.0 or later.
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

The EM_SETWORDBREAKPROCEX message sets the extended word-break procedure.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETWORDBREAKPROCEX,    // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // word break procedure
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to an EditWordBreakProcEx function or NULL to use the default procedure.

Return Values

This message returns the address of the previous extended word-break procedure.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EditWordBreakProcEx, EM_GETWORDBREAKPROCEX


EM_SETWORDWRAPMODE

The EM_SETWORDWRAPMODE message 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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETWORDWRAPMODE,       // message to send
  (WPARAM) wParam,          // options
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies one or more of the following values.
Value | Meaning
WBF_WORDWRAP | Enables Asian-specific word wrap operations, such as kinsoku in Japanese.
WBF_WORDBREAK Enables English word-breaking operations in Japanese and Chinese.

Enables Hangeul word-breaking operation.
WBF_OVERFLOW | Recognizes overflow punctuation. (Not currently supported.)
WBF_LEVEL1 | Sets the Level 1 punctuation table as the default.
WBF_LEVEL2 | Sets the Level 2 punctuation table as the default.
WBF_CUSTOM | Sets the application-defined punctuation table.

lParam
This parameter is not used.

Return Values

This message returns the current word-wrapping and word-breaking options.

Remarks

This message must not be sent by the application defined–word breaking procedure.

Requirements

Version: Requires Rich Edit 1.0 Asian language only.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages


EM_SETZOOM

The EM_SETZOOM message sets the zoom ratio anywhere between 1/64 and 64.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SETZOOM,               // message to send
  (WPARAM) wParam,          // numerator
  (LPARAM) lParam          // denominator
);

Parameters

wParam
Numerator of the zoom ratio.
lParam
Denominator of the zoom ratio.

These parameters can have the following values.
Value | Meaning
Both 0 | Turns off zooming by using the EM_SETZOOM message (zooming may still occur using ITextHost::TxGetExtent).
1/64 < (wParam / lParam) < 64 | Zooms display by the zoom ratio numerator/denominator

Return Values

If the new zoom setting is accepted, the return value is TRUE.

If the new zoom setting is not accepted, the return value is FALSE.

Requirements

Version: Requires Rich Edit 3.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_GETZOOM


EM_SHOWSCROLLBAR

The EM_SHOWSCROLLBAR message shows or hides one of the scroll bars in the Text Host window.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_SHOWSCROLLBAR,         // message to send
  (WPARAM) wParam,          // scroll bar identifier
  (LPARAM) lParam          // scroll bar visibility
);

Parameters

wParam
Identifies which scroll bar to display: horizontal or vertical. This parameter must be SB_VERT or SB_HORZ.
lParam
Specifies whether to show the scroll bar or hide it. Specify TRUE to show the scroll bar and FALSE to hide it.

Return Values

This message does not return a value.

Remarks

This method is only valid when the control is in-place active. Calls made while the control is inactive may fail.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Messages, EM_GETSCROLLPOS, EM_SETSCROLLPOS


EM_STOPGROUPTYPING

An application sends 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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_STOPGROUPTYPING,       // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

The return value is zero. This 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, such as a paste operation that does not involve typing.

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.

Requirements

Version: Requires Rich Edit 2.0 or later.
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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_STREAMIN,              // message to send
  (WPARAM) wParam,          // format options
  (LPARAM) lParam          // data (EDITSTREAM *)
);

Parameters

wParam
Specifies the data format and replacement options. This value must be one of the following values.
Value | Meaning
SF_RTF | Rich Text Format (RTF)
SF_TEXT | Text

In addition, you can specify the following flags.
Value | Meaning
SFF_PLAINRTF | If specified, only keywords common to all languages are streamed in. Language-specific RTF keywords in the stream are ignored. If not specified, all keywords are streamed in. You can combine this flag with the SF_RTF flag.
SFF_SELECTION | If specified, the data stream replaces the contents of the current selection. If 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.
SF_UNICODE | Rich Edit 2.0 and later: Indicates Unicode text. You can combine this flag with the SF_TEXT flag.

lParam
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

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

Requirements

Version: Requires Rich Edit 1.0 or later.
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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  EM_STREAMOUT,             // message to send
  (WPARAM) wParam,          // format options
  (LPARAM) lParam          // data (EDITSTREAM *)
);

Parameters

wParam
Specifies the data format and replacement options. This value must be one of the following values.
Value | Meaning
SF_RTF | Rich Text Format (RTF).
SF_RTFNOOBJS | RTF with spaces in place of COM object.
SF_TEXT | Text with spaces in place of COM objects.
SF_TEXTIZED | Text with a text representation of COM objects.

The SF_RTFNOOBJS option is useful if an application stores COM objects itself, as RTF representation of COM objects is not very compact. The control word, \objattph, followed by a space denotes the object position.

In addition, you can specify the following flags.
Value | Meaning
SFF_PLAINRTF | If specified, the rich edit control streams out only the keywords common to all languages, ignoring language-specific keywords. If not specified, the rich edit control streams out all keywords. You can combine this flag with the SF_RTF or SF_RTFNOOBJS flag.
SFF_SELECTION | If specified, the rich edit control streams out only the contents of the current selection. If not specified, the control streams out the entire contents. You can combine this flag with any of data format values.
SF_UNICODE | Rich Edit 2.0 and later: Indicates Unicode text. You can combine this flag with the SF_TEXT flag.
SF_USECODEPAGE | Rich Edit 3.0 and later: Generates UTF-8 RTF as well as text using other code pages. The code page is set in the high word of wParam. For example, for UTF-8 RTF, set wParam to (CP_UTF8 << 16) | SF_USECODEPAGE | SF_RTF.

lParam
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

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

Requirements

Version: Requires Rich Edit 1.0 or later.
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_DRAGDROPDONE
EN_DROPFILES
EN_IMECHANGE
EN_LINK
EN_MSGFILTER
EN_OBJECTPOSITIONS
EN_PROTECTED
EN_REQUESTRESIZE
EN_SELCHANGE

The following notification messages are always enabled and do not depend on the EM_SETEVENTMASK message.

EN_ALIGNLTR
EN_ALIGNRTL
EN_OLEOPFAILED
EN_SAVECLIPBOARD
EN_STOPNOUNDO

For a list of edit control notification messages, see Edit Control Notification Messages.


EN_ALIGNLTR

The EN_ALIGNLTR notification message notifies a rich edit control's parent window that the paragraph direction has changed to left-to-right. A rich edit control sends this notification message in the form of a WM_COMMAND message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,        // handle to window
  UINT uMsg,        // WM_COMMAND
  WPARAM wParam,     // control identifier, EN_ALIGNLTR
  LPARAM lParam     // handle to rich edit control (HWND)
);

Parameters

wParam
The low-order word specifies the rich edit control identifier.

The high-order word specifies the notification message.

lParam
Handle to the rich edit control.

Return Values

This message returns no value.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Notification Messages, EN_ALIGNRTL, HIWORD, LOWORD, WM_COMMAND


EN_ALIGNRTL

The EN_ALIGNRTL notification message notifies a rich edit control's parent window that the paragraph direction changed to right-to-left. A rich edit control sends this notification message in the form of a WM_COMMAND message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // control identifier, EN_ALIGNRTL
  LPARAM lParam    // handle to rich edit control (HWND)
);

Parameters

wParam
The low-order word specifies rich edit control identifier.

The high-order word specifies the notification message.

lParam
Handle to the rich edit control.

Return Values

This message returns no value.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Notification Messages, EN_ALIGNLTR, HIWORD, LOWORD, WM_COMMAND


EN_CORRECTTEXT

The EN_CORRECTTEXT message notifies a rich edit control parent window that a SYV_CORRECT gesture occurred, giving the parent window a chance to cancel correcting the text. A rich edit control sends this notification message in the form of a WM_NOTIFY message.

This message is provided only for compatibility with 16-bit versions of Windows, and is supported only on East Asian versions of Rich Edit 1.0.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NOTIFY
  WPARAM wParam,   // control identifier, EN_CORRECTTEXT
  LPARAM lParam    // selection (ENCORRECTTEXT *)
);

Parameters

wParam
The low-order word specifies rich edit control identifier.

The high-order word specifies the notification message.

lParam
Pointer to an ENCORRECTTEXT structure specifying the selection to be corrected.

Return Values

This message returns zero to ignore the action.

This message returns a nonzero value to process the action.

Remarks

This message is sent only if pen capabilities are available.

To receive EN_CORRECTTEXT notifications, specify ENM_CORRECTTEXT in the mask sent with the EM_SETEVENTMASK message.

Note The EN_CORRECTTEXT notification message is only supported in rich edit version 1.0. It is not supported in later versions of rich edit. For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Version: Requires Rich Edit 1.0 only.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Notification Messages, ENCORRECTTEXT, HIWORD, LOWORD, WM_NOTIFY


EN_DRAGDROPDONE

The EN_DRAGDROPDONE notification message notifies a rich edit control's parent window that the drag-and-drop operation has completed. A rich edit control sends this notification message in the form of a WM_NOTIFY message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NOTIFY
  WPARAM wParam,    // control identifier, EN_DRAGDROPDONE
  LPARAM lParam    // header (NMHDR *)
);

Parameters

wParam
The low-order word specifies the rich edit control identifier.

The high-order word specifies the notification message.

lParam
Pointer to an NMHDR structure.

Return Values

This message returns no value.

Remarks

To receive an EN_DRAGDROPDONE notification, specify the ENM_DRAGDROPDONE flag in the mask sent with the EM_SETEVENTMASK message.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Notification Messages, EM_SETEVENTMASK, HIWORD, LOWORD, NMHDR, WM_NOTIFY


EN_DROPFILES

The EN_DROPFILES message notifies a rich edit control 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.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NOTIFY
  WPARAM wParam,   // control identifier, EN_DROPFILES
  LPARAM lParam    // file information (ENDROPFILES *)
);

Parameters

wParam
The low-order word specifies rich edit control identifier.

The high-order word specifies the notification message.

lParam
Pointer to an ENDROPFILES structure that receives dropped files information.

Return Values

This message returns a nonzero value to allow the drop operation.

This message returns zero to ignore the drop operation.

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 ENM_DROPFILES in the mask sent with the EM_SETEVENTMASK message.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Notification Messages, DragAcceptFiles, ENDROPFILES, HIWORD, LOWORD, WM_DROPFILES, WM_NOTIFY


EN_IMECHANGE

The EN_IMECHANGE message 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. A rich edit control sends this notification message in the form of a WM_COMMAND message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // control identifier, EN_IMECHANGE
  LPARAM lParam    // handle to rich edit control (HWND)
);

Parameters

wParam
The low-order word specifies rich edit control identifier.

The high-order word specifies the notification message.

lParam
Handle to the rich edit control..

Return Values

This message returns zero.

Remarks

To receive EN_IMECHANGE notifications, specify ENM_IMECHANGE in the mask sent with the EM_SETEVENTMASK message.

Note The EN_IMECHANGE notification message is only supported in the Asian version of Rich Edit 1.0. It is not supported in later versions. For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.

Requirements

Version: Requires Rich Edit 1.0 Asian language only.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Notification Messages, HIWORD, LOWORD, WM_COMMAND


EN_LINK

A rich edit control sends EN_LINK messages when it receives various messages, for example, when the user clicks the mouse or when the mouse pointer is over text that has the CFE_LINK effect.

The parent window of the control receives this notification message through a WM_NOTIFY message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NOTIFY
  WPARAM wParam,   // control identifier, EN_LINK
  LPARAM lParam    // link information (ENLINK *)
);

Parameters

wParam
The low-order word specifies rich edit control identifier.

The high-order word specifies the notification message.

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

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.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Notification Messages, CHARRANGE, EM_AUTOURLDETECT, EM_GETAUTOURLDETECT, ENLINK, HIWORD, LOWORD, NMHDR


EN_MSGFILTER

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

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NOTIFY
  WPARAM wParam,   // control identifier, EN_MSGFILTER
  LPARAM lParam    // message information (MSGFILTER *)
);

Parameters

wParam
The low-order word specifies rich edit control identifier.

The high-order word specifies the notification message.

lParam
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

If the control should process the event, the message returns a zero value.

If the control should ignore the event, the message returns a nonzero value.

Remarks

To receive EN_MSGFILTER notifications for events, specify one or more of the following flags in the mask sent with the EM_SETEVENTMASK message.

Flag | Meaning
ENM_KEYEVENTS | To receive notifications for keyboard events.
ENM_MOUSEEVENTS | To receive notifications for mouse events.
ENM_SCROLLEVENTS | To receive notifications for a mouse wheel event.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Notification Messages, HIWORD, LOWORD, MSGFILTER, WM_NOTIFY


EN_OBJECTPOSITIONS

The EN_OBJECTPOSITIONS notification message notifies a rich edit control's parent window when the control reads in objects. A rich edit control sends this notification message in the form of a WM_NOTIFY message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NOTIFY
  WPARAM wParam,   // control identifier, EN_OBJECTPOSITIONS
  LPARAM lParam    // (OBJECTPOSITIONS *)
);

Parameters

wParam
The low-order word specifies the rich edit control identifier.

The high-order word specifies the notification message.

lParam
Pointer to an OBJECTPOSITIONS structure.

Return Values

This message returns zero to continue the Read operation.

This message returns a nonzero value to stop the Read operation.

Remarks

To receive an EN_OBJECTPOSITIONS notification, specify the ENM_OBJECTPOSITIONS flag in the mask sent with the EM_SETEVENTMASK message.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Notification Messages, EM_SETEVENTMASK, HIWORD, LOWORD, OBJECTPOSITIONS, WM_NOTIFY


EN_OLEOPFAILED

The EN_OLEOPFAILED message notifies a rich edit control's parent window that a user action on a COM object has failed. A rich edit control sends this notification message in the form of a WM_NOTIFY message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NOTIFY
  WPARAM wParam,   // control identifier, EN_OLEOPFAILED
  LPARAM lParam    // failure information (ENOLEOPFAILED *)
);

Parameters

wParam
The low-order word specifies rich edit control identifier.

The high-order word specifies the notification message.

lParam
Pointer to an ENOLEOPFAILED structure that contains information about the failure.

Return Values

This message returns zero.

Remarks

The parent window will always get a WM_NOTIFY message for this event, it does not require a notification mask sent with WM_SETEVENTMASK.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Notification Messages, , ENOLEOPFAILED, HIWORD, LOWORD


EN_PROTECTED

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

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NOTIFY
  WPARAM wParam,   // control identifier, EN_PROTECTED
  LPARAM lParam    // message information (ENPROTECTED *)
);

Parameters

wParam
The low-order word specifies rich edit control identifier.

The high-order word specifies the notification message.

lParam
Pointer to an ENPROTECTED structure containing information about the message that triggered the notification.

Return Values

This message returns zero to allow the operation.

This message returns a nonzero value to prevent the operation.

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 ENM_PROTECTED in the mask sent with the EM_SETEVENTMASK message.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Notification Messages, ENPROTECTED, HIWORD, LOWORD, WM_NOTIFY


EN_REQUESTRESIZE

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

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NOTIFY
  WPARAM wParam,   // control identifier, EN_REQUESTRESIZE
  LPARAM lParam    // requested size (REQRESIZE *)
);

Parameters

wParam
The low-order word specifies rich edit control identifier.

The high-order word specifies the notification message.

lParam
Pointer to a REQRESIZE structure that receives the requested size.

Return Values

This message returns no 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 ENM_REQUESTRESIZE in the mask sent with the EM_SETEVENTMASK message.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Notification Messages, HIWORD, LOWORD, REQRESIZE, WM_NOTIFY


EN_SAVECLIPBOARD

The EN_SAVECLIPBOARD message notifies the rich edit control's parent window that the control is closing and the clipboard contains information. A rich edit control sends this notification message in the form of a WM_NOTIFY message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NOTIFY
  WPARAM wParam,   // control identifier, EN_SAVECLIPBOARD
  LPARAM lParam    // clipboard info (ENSAVECLIPBOARD *)
);

Parameters

wParam
The low-order word specifies rich edit control identifier.

The high-order word specifies the notification message.

lParam
Pointer to an ENSAVECLIPBOARD structure that contains information about clipboard information.

Return Values

This message returns zero if the clipboard should be made available to other applications.

This message returns a nonzero value if the clipboard should not be saved.

Remarks

The parent window will always get a WM_NOTIFY message for this event, it does not require a notification mask sent with WM_SETEVENTMASK.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Notification Messages, ENSAVECLIPBOARD, HIWORD, LOWORD


EN_SELCHANGE

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

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NOTIFY
  WPARAM wParam,   // control identifier, EN_SELCHANGE
  LPARAM lParam    // selection information (SELCHANGE *)
);

Parameters

wParam
The low-order word specifies rich edit control identifier.

The high-order word specifies the notification message.

lParam
Pointer to a SELCHANGE structure that receives information about the selection.

Return Values

This message returns no value.

Remarks

To receive EN_SELCHANGE notifications, specify ENM_SELCHANGE in the mask sent with the EM_SETEVENTMASK message.

Note, when there is no selection (that is, the caret is displayed) we have, in fact, the empty selection. Thus, when the caret position changes (for example, clicking a mouse, typing, or pressing an arrow key), an EN_SELCHANGE message is sent.

Requirements

Version: Requires Rich Edit 1.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Notification Messages, HIWORD, LOWORD, SELCHANGE, WM_NOTIFY


EN_STOPNOUNDO

The EN_STOPNOUNDO message 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.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NOTIFY
  WPARAM wParam,   // control identifier, EN_STOPNOUNDO
  LPARAM lParam    // header (NMHDR *)
);

Parameters

wParam
The low-order word specifies rich edit control identifier.

The high-order word specifies the notification message.

lParam
Pointer to an NMHDR structure.

Return Values

This message returns zero to continue the Undo operation.

This message returns a nonzero value to stop the Undo operation.

Remarks

The parent window will always get a WM_NOTIFY message for this event, it does not require a notification mask sent with WM_SETEVENTMASK.

Requirements

Version: Requires Rich Edit 1.0 Asian language only.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Notification Messages, HIWORD, LOWORD, NMHDR, WM_NOTIFY


Rich Edit Enumeration Types

The following enumeration types are used with rich edit controls.

TEXTMODE
UNDONAMEID


TEXTMODE

The TEXTMODE enumeration type indicates 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;

Enumeration Values

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
The control only allows the English keyboard and a keyboard corresponding to the default charset. For example, you could have Greek and English.
TM_MULTICODEPAGE
The control allows multiple code pages.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Enumeration Types, EM_SETTEXTMODE, EM_GETTEXTMODE


UNDONAMEID

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;

Enumeration Values

UID_UNKNOWN
The type of undo action is unknown.
UID_TYPING
Typing operation.
UID_DELETE
Delete operation.
UID_DRAGDROP
Drag and drop operation.
UID_CUT
Cut operation.
UID_PASTE
Paste operation.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Richedit.h.

See Also

Rich Edit Controls Overview, Rich Edit Enumeration Types, EM_GETREDONAME, EM_GETUNDONAME


Rich Edit Constants

The following section describes constants used with rich edit controls.

  • Rich Edit Control Styles
  • Rich Edit Control Event Mask Flags


Rich Edit Control Styles

The following window styles are unique to rich edit controls.

Style | Description
ES_DISABLENOSCROLL | Disables scroll bars instead of hiding them when they are not needed.
ES_EX_NOCALLOLEINIT | Prevents the control from calling the OleInitialize function when created. This window style is useful only in dialog templates because CreateWindowEx does not accept this style.
ES_NOIME | Disables the input method editor (IME) operation. This style is available for Asian language support only.
ES_SELFIME | Directs the rich edit control to allow the application to handle all IME operations. This style is available for Asian language support 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. This style is available for Asian-language support only.

Rich edit controls also support the following edit control styles.

Edit control style | Description
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 | Centers text in a single-line or multiline edit control.
ES_LEFT | Left aligns text.
ES_MULTILINE | Designates a multiline edit control. The default is single-line edit control.
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_PASSWORD | Displays an asterisk (*) for each character typed into the edit control. This style is valid only for single-line edit controls.
ES_READONLY | Prevents the user from typing or editing text in the edit control.
ES_RIGHT | Right aligns text in a single-line or multiline 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.

Rich edit controls do not support the following edit control styles.

ES_LOWERCASE
ES_OEMCONVERT
ES_UPPERCASE


Rich Edit Control Event Mask Flags

The event mask specifies which notification messages a rich edit control sends to its parent window. The event mask can be none or a combination of these values.

Value | Meaning
ENM_CHANGE | Sends EN_CHANGE notifications.
ENM_CORRECTTEXT | Sends EN_CORRECTTEXT notifications.
ENM_DRAGDROPDONE | Sends EN_DRAGDROPDONE notifications.
ENM_DROPFILES | Sends EN_DROPFILES notifications.
ENM_IMECHANGE | Rich Edit 1.0 only: Sends EN_IMECHANGE notifications when the IME conversion status has changed. Only for Asian-language versions of the operating system.
ENM_KEYEVENTS | Sends EN_MSGFILTER notifications for keyboard events.
ENM_LINK | Rich Edit 2.0 and later: Sends EN_LINK notifications when the mouse pointer is over text that has the CFE_LINK and one of several mouse actions is performed.
ENM_MOUSEEVENTS | Sends EN_MSGFILTER notifications for mouse events.
ENM_OBJECTPOSITIONS | Sends EN_OBJECTPOSITIONS notifications.
ENM_PROTECTED | Sends EN_PROTECTED notifications.
ENM_REQUESTRESIZE | Sends EN_REQUESTRESIZE notifications.
ENM_SCROLL | Sends EN_HSCROLL and EN_VSCROLL notifications.
ENM_SCROLLEVENTS | Sends EN_MSGFILTER notifications for mouse wheel events.
ENM_SELCHANGE | Sends EN_SELCHANGE notifications.
ENM_UPDATE | Sends EN_UPDATE notifications. Rich Edit 2.0 and later: this flag is ignored and the EN_UPDATE notifications are always sent. However, if Rich Edit 3.0 emulates Rich Edit 1.0, you must use this flag to send 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 EM_GETEVENTMASK and EM_SETEVENTMASK messages.


Text Object Model

The Text Object Model (TOM) defines a substantial set of text manipulation interfaces. Text solutions such as Microsoft® Word and rich edit controls support the TOM feature set. TOM was greatly influenced by WordBasic (the programming language used for Word) and it is easy to use from Microsoft® Visual Basic® for Applications (VBA). This compatibility has several advantages:

  • Code can migrate fairly easily from one solution to another.
  • One language can be used to share text information between different text engines.
  • It reduces the need for documentation and code compared to the separate low-level COM and VBA interfaces.

However, it can be less efficient for C/C++ purposes than the use of more general lower level COM interfaces.

TOM is a straightforward set of interfaces to implement for its primary text solutions, Microsoft Word and rich edit controls. However, for applications that place minor emphasis on text, it is better to provide TOM interfaces by transferring the text to an edit control that supports TOM. Since rich edit controls ship with Microsoft operating systems, they are the standard means of obtaining TOM functionality:

The material in this topic is divided into the following sections:

  • About Text Object Model
  • Using The Text Object Model
  • Text Object Model Reference


About Text Object Model

The top-level TOM object is defined by the ITextDocument interface, which has methods for creating and retrieving objects lower in the object hierarchy. For simple, plain text processing, you can obtain an ITextRange object from an ITextDocument object.

If you need to add rich-text formatting, you can obtain ITextFont and ITextPara objects from an ITextRange object:

  • ITextFont provides the programming equivalent of the Microsoft® Word Font dialog box.
  • ITextPara provides the equivalent of the Microsoft Word Paragraph dialog box.

In addition to these three lower-level objects, TOM has a selection object ITextSelection, which is just an ITextRange object with selection highlighting and additional UI-oriented methods. The range and selection objects include screen-oriented methods that enable programs to examine text on the screen or text that could be scrolled onto the screen. These capabilities aid in making text accessible to the visually impaired, for example.

These objects can be illustrated by the following directory tree:

ITextDocument             Top-level editing object
    ITextStoryRanges      Enumerator for stories in document
    ITextRange            Primary text interface: range of text
        ITextFont         Character-attribute interface
        ITextPara         Paragraph-attribute interface
    ITextSelection        Screen highlighted text range that
                          inherits all ITextRange methods

A story is a contiguous range of text. An ITextDocument object describes one or more stories. In Microsoft Word, a story contains one of the various parts of a document, such as the main text of a document, headers and footers, footnotes, or annotations. In rich edit controls, there is only one story per document, although a client can use multiple documents to represent multiple stories.

An ITextRange object is defined by its start and end character position (cp) offsets and a story object. As such, it does not exist independently of its parent story object, although its text can be copied to the Clipboard or to other targets. A text range object is different from spreadsheet and other range objects, which are defined by other kinds of offsets, like row/column or graphics position (x,y). A text range object can:

  • Modify itself in various ways.
  • Return a duplicate of itself.
  • Copy its start and end character positions and its story pointer to the current selection.

Note that an explicit story object is not needed, since an ITextRange object can always be created to represent any given story. In particular, the ITextDocument object can create an ITextStoryRanges object to enumerate the stories in the document in terms of ranges with start and end cp values that describe complete stories (such as, 0 and tomForward).


TOM RTF

In TOM 1.0, rich-text exchange can be accomplished by sets of explicit method calls or by transfers of rich text in the RTF format. This section gives tables of RTF control words for paragraph properties and for character properties.

TOM RTF Paragraph Control Words

Control word | Meaning
\ fi n | First-line indent (the default is zero).
\ keep | Keep paragraph intact.
\ keepn | Keep with the next paragraph.
\ li n | Left indent (the default is zero).
\ noline | No line numbering.
\ nowidctlpar | Turn off widow/orphan control.
\ pagebb | Break page before paragraph.
\ par | New paragraph.
\ pard | Resets to default paragraph properties.
\ ql | Left aligned (the default).
\ qr | Right aligned.
\ qj | Justified.
\ qc | Centered.
\ ri n | Right indent (the default is zero).
\ s n | Style n.
\ sa n | Space after (the default is zero).
\ sb n | Space before (the default is zero).
\ sl n | If missing or if n =1000, line spacing is determined by the tallest character in the line (single-line spacing); if n > zero, at least this size is used; if n is < zero, exactly |n| is used. The line spacing is multiple-line spacing if \slmult 1 follows.
\ slmult m | Follows \sl. m = zero: At Least or Exactly line spacing as described by \ sl n. m = 1: line spacing = n/240 times single-line spacing.
\ tb n | Bar tab position, in twips, from the left margin.
\ tldot | Tab leader dots.
\ tleq | Tab leader equal sign.
\ tlhyph | Tab leader hyphens.
\ tlth | Tab leader thick line.
\ tlul | Tab leader underline.
\ tqc | Centered tab.
\ tqdec | Decimal tab.
\ tqr | Flush-right tab.
\ tx n | Tab position, in twips, from the left margin.

TOM RTF Character Format Control Words

Control word | Meaning
\ animation n | Sets animation type to n.
\ b | Bold.
\ caps | All capitals.
\ cf n | Foreground color (the default is tomAutocolor).
\ cs n | Character style n.
\ dn n | Subscript position in half-points (the default is 6).
\ embo | Embossed.
\ f n | Font number, n refers to an entry in the font table.
\ fs n | Font size in half-points (the default is 24).
\ highlight n | Background color (the default is tomAutocolor).
\ i | Italic.
\ impr | Imprint.
\ lang n | Applies a language to a character. n is a number corresponding to a language. The \ plain control word resets the language property to the language defined by \ deflang n in the document properties.
\ nosupersub | Turns off superscript or subscript.
\ outl | Outline.
\ plain | Resets character formatting properties to a default value defined by the application. The associated character-formatting properties (described in the section Associated Character Properties in the RTF specification) are also reset.
\ scaps | Small capitals.
\ shad | Shadow.
\ strike | Strikethrough.
\ sub | Applies subscript to text and reduces point size according to font information.
\ super | Applies superscript to text and reduces point size according to font information.
\ ul | Continuous underline. \ ul0 turns off all underlining.
\ uld | Dotted underline.
\ uldb | Double underline.
\ ulnone | Stops all underlining.
\ ulw | Word underline.
\ up n | Superscript position in half-points (the default is 6).
\ v | Hidden text.


Finding Rich Text

TOM methods can be used fairly easily to find rich text as defined by a range of text. The Microsoft Word 97 Find command can find plain text with uniform formatting, such as Arial 11-point, but it cannot find text with a combination of formatting, such as α2. Finding such rich text exactly is often needed in word processing, although it has never been fulfilled in a WYSIWYG word processor. There is clearly a larger domain of rich-text matching that allows for some character formatting properties to be ignored (or to include paragraph formatting and/or object content), but such generalizations are beyond the scope of this section.

One purpose for this functionality is to use a rich-text Find dialog box to define the rich text you want to locate in a Microsoft Word document. The dialog box would be implemented using a rich edit control and TOM methods would be used to carry out the search through the Word document. You could either copy the desired rich text from a Microsoft Word document into the Find dialog box or enter and format it directly in the Find dialog box.

The following program uses TOM methods to find text containing combinations of exact character formatting. The algorithm searches for the plain text in the match range, which is named pr1. If the plain text is found, it is pointed to by a trial range, which is named pr2. Then, two insertion-point ranges (prip1 and prip2) are used to walk through the trial range comparing its character formatting to that of pr1. If they match exactly, the input range (given by ppr) is updated to point at the trial range's text and the function returns the count of characters in the matched range. Two ITextFont objects, pf1 and pf2, are used in the character-formatting comparison. They are attached to the insertion-point ranges prip1 and prip2, respectively.

LONG FindRichText (
    ITextRange **ppr,             // Ptr to range to search
    ITextRange *pr1)              // Range with rich text to find
{
    BSTR         bstr;            // pr1 plain-text to search for
    LONG        cch;              // Text string count
    LONG        cch1, cch2;       // tomCharFormat run char counts
    LONG        cchMatch = 0;     // Nothing matched yet
    LONG        cp;               // Handy char position
    LONG        cpFirst1;         // pr1 cpFirst
    LONG        cpFirst2;         // pr2 cpFirst
    ITextFont  *    pf1, *pf      // Fonts corresponding to IPs prip1 and prip2
    ITextRange *pr2;              // Range duplicate to search with
    ITextRange *prip1, *prip      // Insertion points to walk pr1, pr2

    if (!ppr || !*ppr || !pr1)
        return E_INVALIDARG;

    // Initialize range and font objects used in search
    if ((*ppr)->GetDuplicate(&pr2)    != NOERROR ||
        pr1->GetDuplicate(&prip1)     != NOERROR ||
        pr2->GetDuplicate(&prip2)     != NOERROR ||
        prip1->GetFont(&pf1)          != NOERROR ||
        prip2->GetFont(&pf2)          != NOERROR ||
        pr1->GetText(&bstr)           != NOERROR )
    {
        return E_OUTOFMEMORY;
    }

    pr1->GetStart(&cpFirst1);

    // Keep searching till rich text is matched or no more plain-text hits
    while(!cchMatch && pr2->FindText(bstr, tomForward, 0, &cch) == NOERROR)
    {
        pr2->GetStart(&cpFirst2);                 // pr2 is a new trial range
        prip1->SetRange(cpFirst1, cpFirst1);      // Set up IPs to scan match
        prip2->SetRange(cpFirst2, cpFirst2);      //  and trial ranges

        while(cch > 0 &&
            pf1->IsEqual(pf2, NULL) == NOERROR)   // Walk match & trial ranges
        {                                         //  together comparing font
            prip1->GetStart(&cch1);               //  properties
            prip1->Move(tomCharFormat, 1, NULL);
            prip1->GetStart(&cp);
            cch1 = cp - cch1;                     // cch of next match font run

            prip2->GetStart(&cch2);
            prip2->Move(tomCharFormat, 1, NULL);
            prip2->GetStart(&cp);
            cch2 = cp - cch2;                      // cch of next trial font run

            if(cch1 < cch)                         // There is more to compare
            {
                if(cch1 != cch2)                   // Different run lengths:
                    break;                         //  no formatting match
                cch = cch - cch1;                  // Matched format run
            }
            else if(cch2 < cch)                    // Trial range format run too
                break;                             //  short

            else                                   // Both match and trial runs
            {                                      //  reach at least to match
                pr2->GetEnd(&cp);                  //  text end: rich-text match
                (*ppr)->SetRange(cpFirst2, cp)     // Set input range to hit
                cchMatch = cp - cpFirst2;          //  coordinates and return
                break;                             //  length of matched string
            }
        }
    }
    pr2->Release();
    prip1->Release();
    prip2->Release();
    pf1->Release();
    pf2->Release();
    SysFreeString(bstr);

    return cchMatch;
}


TOM Accessibility

TOM provides accessibility support through the ITextSelection and ITextRange interfaces. This section describes methods that are useful for accessibility as well as how a program can determine the x, y screen position of an object.

Since UI-based accessibility programs typically work with the screen and the mouse, a common concern is to find the corresponding ITextDocument interface for the current mouse location (in screen coordinates). The following sections present two ways to determine the proper interface:

  • Through the running-object table
  • Through the EM_GETOLEINTERFACE message, which works for windowed rich edit instances, provided the client is in the same process space (no marshaling is needed)

For more information, see the Microsoft® Active Accessibility® specification. After you obtain an object from a screen position, you can use QueryInterface for an ITextDocument interface and call the ITextDocument::RangeFromPoint method to get an empty range object at the cp corresponding to the screen position.


Interface from Running Object Table

A running object table (ROT) tells what object instances are active. By querying this table, you can accelerate the process of connecting a client to an object when the object is already running. Before programs can access TOM interfaces through the running object table, a TOM instance with a window needs to register in the ROT using a moniker. You construct the moniker from a string containing the hexadecimal value of its HWND. The following code sample shows how to do this.

// This TOM implementation code is executed when a new windowed
// instance starts up.
// Variables with leading underscores are members of this class.

OLECHAR szBuf[10];            // Place to put moniker
MONIKER *pmk;
wsprintf(szBuf, "%x", _hwnd);
CreateFileMoniker(szBuf, &pmk);
OleStdRegisterAsRunning(this, pmk, &_dwROTcookie);
....................

// Accessibility Client:
//    Find hwnd for window pointed to by mouse cursor.

GetCursorPos(&pt);
hwnd = WindowFromPoint(pt);

// Look in ROT (running object table) for an object attached to hwnd

wsprintf(szBuf, "%x", hwnd);
CreateFileMoniker(szBuf, &pmk);
CreateBindContext(0, &pbc);
pmk->BindToObject(pbc, NULL, IID_ITextDocument, &pDoc);
pbc->Release();

if( pDoc )
{
    pDoc->RangeFromPoint(pt.x, pt.y, &pRange);
    // ...now do whatever with the range pRange
}


Interface from Window Messages

The EM_GETOLEINTERFACE message provides another way to obtain an IUnknown interface for an object at a given screen position. As described in the Interface from Running Object Table topic, you get an HWND for the screen position and then send this message to that HWND. The EM_GETOLEINTERFACE message is rich edit-specific and returns a pointer to an IRichEditOle interface in the variable addressed by lParam.

Tip If a pointer is returned (be sure to set the object to which lParam points to null before sending the message), you can call its QueryInterface method to obtain an ITextDocument interface. The following code sample illustrates this approach.

    HWND    hwnd;
    ITextDocument *pDoc;
    ITextRange *pRange;
    POINT    pt;
    IUnknown *pUnk = NULL;

    GetCursorPos(&pt);
    hwnd = WindowFromPoint(pt);
    SendMessage(hwnd, EM_GETOLEINTERFACE, 0, (LPARAM)&pUnk);
    if(pUnk &&
        pUnk->QueryInterface(IID_ITextDocument, &pDoc) == NOERROR)
    {
        pDoc->RangeFromPoint(pt.x, pt.y, &pRange);
        //  ... continue with rest of program
    }


Accessibility-Oriented Methods

Some TOM methods are particularly useful for navigating around the screen, while other TOM methods enhance what you can do when you arrive at places of interest. The following table describes the most useful methods.

Method | How it promotes accessibility
ITextDocument::GetSelection | This method gets the active selection that can be used for a variety of view-oriented purposes, such as highlighting text and scrolling.
ITextDocument::RangeFromPoint | When used on an active selection, this method is guaranteed to get a range associated with a particular view.
ITextRange::Expand | Enlarges a text range so that any partial units it contains are completely contained. For example, Expand(tomWindow) expands the range to include the visible portion of the range's story.
ITextRange::GetDuplicate | When used on an active selection, this method is guaranteed to get a range associated with a particular view. See the description of ITextDocument::RangeFromPoint.
ITextRange::GetPoint | Gets the screen coordinates for the start or end character position in the text range.
ITextRange::ScrollIntoView | Scrolls a text range into view.
ITextRange::SetPoint | Selects text at or up through a specified point.


Character Match Sets

The variant parameter of the various Move* methods in ITextRange, for example, MoveWhile and MoveUntil, can take an explicit string or a character-match set 32-bit index. The indexes are defined by either Unicode ranges or GetStringTypeEx character sets. The Unicode range starting at n and of length l (< 32768) is given by the index n + (l << 16) + 0x80000000. For example, basic Greek letters are defined by CR_Greek = 0x805f0370 and printable ASCII characters are defined by CR_ASCIIPrint = 0x805e0020. In addition, the MoveWhile and MoveUntil methods let you rapidly bypass a span of characters in any GetStringTypeEx character set or a span of characters not in any one of these character sets, respectively. In spite of their power, these methods are very efficient, requiring only 150 lines of C++ to implement.

The GetStringTypeEx sets are specified by the values for Ctype1, Ctype2, and Ctype3 and are defined as follows.

Cset | Meaning
Ctype1 | Combination of CT_CTYPE1 types.
Ctype2 + tomCType2 | Any CT_CTYPE2 type.
Ctype3 + tomCType3 | Combination of CT_CTYPE3 types.

Specifically, Ctype1 can be any combination of the following .

Ctype1 name | Value | Meaning
C1_UPPER | 0x0001 | Uppercase.
C1_LOWER | 0x0002 | Lowercase.
C1_DIGIT | 0x0004 | Decimal digits.
C1_SPACE | 0x0008 | Space characters.
C1_PUNCT | 0x0010 | Punctuation.
C1_CNTRL | 0x0020 | Control characters.
C1_BLANK | 0x0040 | Blank characters.
C1_XDIGIT | 0x0080 | Hexadecimal digits.
C1_ALPHA | 0x0100 | Any linguistic character (alphabetic, syllabary, or ideographic).

The Ctype2 types support proper layout of Unicode text. The direction attributes are assigned so that the bidirectional layout algorithm standardized by Unicode produces accurate results. These types are mutually exclusive. For more information about the use of these attributes, see The Unicode Standard: Worldwide Character Encoding, Volumes 1 and 2, Addison-Wesley Publishing Company: 1991, 1992.

CType2 name | Value | Meaning
Strong: |  |
C2_LEFTTORIGHT | 0x1 | Left to right.
C2_RIGHTTOLEFT | 0x2 | Right to left.
Weak: |  |
C2_EUROPENUMBER | 0x3 | European number, European digit.
C2_EUROPESEPARATOR | 0x4 | European numeric separator.
C2_EUROPETERMINATOR | 0x5 | European numeric terminator.
C2_ARABICNUMBER | 0x6 | Arabic number.
C2_COMMONSEPARATOR | 0x7 | Common numeric separator.
Neutral: |  |
C2_BLOCKSEPARATOR | 0x8 | Block separator.
C2_SEGMENTSEPARATOR | 0x9 | Segment separator.
C2_WHITESPACE | 0xA | White space.
C2_OTHERNEUTRAL | 0xB | Other neutrals.
Not applicable: |  |
C2_NOTAPPLICABLE | 0x0 | No implicit direction.

The Ctype3 types are intended to be placeholders for extensions to the POSIX types required for general text processing or for the standard C library functions. These types are supported in the current version of the Microsoft® Windows NT®/Windows® 2000 operating system.

CType3 name | Value | Meaning
C3_NONSPACING | 0x1 | Nonspacing mark.
C3_DIACRITIC | 0x2 | Diacritic nonspacing mark.
C3_VOWELMARK | 0x4 | Vowel nonspacing mark.
C3_SYMBOL | 0x8 | Symbol.
C3_KATAKANA | 0x10 | Katakana character.
C3_HIRAGANA | 0x20 | Hiragana character.
C3_HALFWIDTH | 0x40 | Half-width character.
C3_FULLWIDTH | 0x80 | Full-width character.
C3_IDEOGRAPH | 0x100 | Ideographic character.
C3_KASHIDA | 0x200 | Arabic Kashida character.
C3_ALPHA | 0x8000 | All linguistic characters (alphabetic,
 |  | syllabary, and ideographic).
C3_NOTAPPLICABLE | 0x0 | Not applicable.

An Edit Development Kit (EDK) could include pVar index #defines for the following ranges described in the Unicode Standard.

Character set | Unicode Range | Character set | Unicode Range
ASCII | 0x0—0x7f | ANSI | 0x0—0xff
ASCIIPrint | 0x20—0x7e | Latin1 | 0x20—0xff
Latin1Supp | 0xa0—0xff | LatinXA | 0x100—0x17f
LatinXB | 0x180—0x24f | IPAX | 0x250—0x2af
SpaceMod | 0x2b0—0x2ff | Combining | 0x300—0x36f
Greek | 0x370—0x3ff | BasicGreek | 0x370—0x3cf
GreekSymbols | 0x3d0—0x3ff | Cyrillic | 0x400—0x4ff
Armenian | 0x530—0x58f | Hebrew | 0x590—0x5ff
BasicHebrew | 0x5d0—0x5ea | HebrewXA | 0x590—0x5cf
HebrewXB | 0x5eb—0x5ff | Arabic | 0x600—0x6ff
BasicArabic | 0x600—0x652 | ArabicX | 0x653—0x6ff
Devangari | 0x900—0x97f | Bengali | 0x980—0x9ff
Gurmukhi | 0xa00—0xa7f | Gujarati | 0xa80—0xaff
Oriya | 0xb00—0xb7f | Tamil | 0xb80—0xbff
Teluga | 0xc00—0xc7f | Kannada | 0xc80—0xcff
Malayalam | 0xd00—0xd7f | Thai | 0xe00—0xe7f
Lao | 0xe80—0xeff | GeorgianX | 0x10a0—0xa0cf
BascGeorgian | 0x10d0—0x10ff | Jamo | 0x1100—0x11ff
LatinXAdd | 0x1e00—0x1eff | GreekX | 0x1f00—0x1fff
GenPunct | 0x2000—0x206f | Superscript | 0x2070—0x207f
Subscript | 0x2080—0x208f | SuperSubscript | 0x2070—0x209f
Currency | 0x20a0—0x20cf | CombMarkSym | 0x20d0—0x20ff
LetterLike | 0x2100—0x214f | NumberForms | 0x2150—0x218f
Arrows | 0x2190—0x21ff | MathOps | 0x2200—0x22ff
MiscTech | 0x2300—0x23ff | CtrlPictures | 0x2400—0x243f
OptCharRecog | 0x2440—0x245f | EnclAlphaNum | 0x2460—x24ff
BoxDrawing | 0x2500—0x257f | BlockElement | 0x2580—0x259f
GeometShapes | 0x25a0—0x25ff | MiscSymbols | 0x2600—0x26ff
Dingbats | 0x2700—0x27bf | CJKSymPunct | 0x3000—0x303f
Hiragana | 0x3040—0x309f | Katakana | 0x30a0—0x30ff
Bopomofo | 0x3100—0x312f | HangulJamo | 0x3130—0x318f
CJLMisc | 0x3190—0x319f | EnclCJK | 0x3200—0x32ff
CJKCompatibl | 0x3300—0x33ff | Han | 0x3400—0xabff
Hangul | 0xac00—0xd7ff | UTF16Lead | 0xd800—0xdbff
UTF16Trail | 0xdc00—0xdfff | PrivateUse | 0xe000—0xf800
CJKCompIdeog | 0xf900—0xfaff | AlphaPres | 0xfb00—0xfb4f
ArabicPresA | 0xfb50—0xfdff | CombHalfMark | 0xfe20—0xfe2f
CJKCompForm | 0xfe30—0xfe4f | SmallFormVar | 0xfe50—0xfe6f
ArabicPresB | 0xfe70—0xfefe | HalfFullForm | 0xff00—0xffef
Specials | 0xfff0—0xfffd |  |


TOM Interface Conventions

In using VBA-compatible dual interfaces, all TOM methods return HRESULTs. In general, TOM uses standard OLE HRESULT values, namely:

  • E_OUTOFMEMORY
  • E_INVALIDARG
  • E_NOTIMPL
  • E_FILENOTFOUND
  • E_ACCESSDENIED
  • E_FAIL
  • CO_E_RELEASED
  • NOERROR (this is the same as S_OK)
  • S_FALSE

While it is possible to use more specific, custom values, they would complicate documentation and usage. Note that if the editing instance associated with a TOM object such as ITextRange is deleted, then the TOM object becomes useless, and all its methods return CO_E_RELEASED.

In addition to the HRESULT return values, many methods include out parameters, which are pointers used to return values. In particular, all VBA property-get methods have such an out parameter. As for all interfaces, all pointer (ptr) parameters must be checked to be nonzero before use. Required pointers passed with null values cause the method to return an HRESULT = E_INVALIDARG. Optional out pointers with null values are ignored. Such optional out pointers include the pDelta and pB parameters of ITextRange.

Use methods with Get- and Set- prefixes respectively, to get and set properties. This differs from the get_ and put_ prefixes that MkTypLib uses in creating interface prototypes. However, since Get and Set are preferred from a C/C++ perspective, the Tom.h header file has been changed accordingly. BOOL variables use the explicit values tomFalse = zero for FALSE and tomTrue = –1 for TRUE (to agree with VBA).

Reference pages for some TOM interface methods use the phrases "property-put method" and "property-get method" to identify methods that set and retrieve a VBA property. VBA code can use these methods or access the property directly. For example, if tf is an ITextFont object, the following VBA code is equivalent to calling the ITextFont::SetBold method:

    tf.Bold = tomTrue

TOM constants all begin with the prefix tom, for example tomWord, and where possible, agree with the corresponding Word constants, which begin with the prefix WD. Please see the Tom.odh file for object-description language (ODL) prototypes of the TOM methods as well as a complete listing of the TOM constants. Also, the files Tomstub.cpp and Tomstub.h give the headers and dummy bodies for all TOM methods needed to facilitate a TOM implementation.

To obtain clean C/C++ interfaces and to simplify TOM implementations, we take advantage of the VBA strongly typed optional (missing) arguments. For example, an optional Count argument can be declared to be a long value and assigned the default value of 1 in the event that the VBA code omits the Count argument. Since previous versions of VBA need to use VARIANT * for optional arguments, this means that all TOM arguments must be given for use with these older versions. Linear dimensions are given in floating-point points, which is the VBA standard for Microsoft Word and Microsoft Excel. We use the C language–float data type.


Using The Text Object Model

The following code samples show various aspects of using the Text Object Model (TOM).

  • Using TOM GUIDs
  • Using Tab Methods in TOM
  • Using a Font Duplicate


Using TOM GUIDs

TOM GUIDs are given in Tom.h inside the MIDL_INTERFACE() statements. To use the associated interfaces, you must first declare the interface using the GUID. For example, to use ITextDocument, include the following:

#define DEFINE_GUIDXXX(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
        EXTERN_C const GUID CDECL name \
                = { l, w1, w2, { b1, b2,  b3,  b4,  b5,  b6,  b7,  b8 } }

DEFINE_GUIDXXX(IID_ITextDocument,0x8CC497C0,0xA1DF,0x11CE,0x80,0x98,
                0x00,0xAA,0x00,0x47,0xBE,0x5D);


Using Tab Methods in TOM

Platform SDK: Windows User Interface

›Using Tab Methods in TOM

The following sample provides C functions that illustrate the use of the Tab methods. It is assumed that most applications include a toolbar that shows the current position and type of the tabs for the currently selected paragraph.

HRESULT UpdateToolbar(ITextSelection *pSel)
{
    ITextPara *pPara = 0;
    float f;
    long tbt;            // tab type
    long tbp;
    HRESULT hr = S_OK;

    hr = pSel->GetPara(&pPara);
    if (FAILED(hr))
        goto cleanup;        // Paragraph properties are not supported

    f = (float) -1.0;          // Start at beginning
    while (pPara->GetTab(tbgoNext, &f, &tbt, NULL) == S_OK)
    {
            // Do something like draw tab icon on toolbar here
            // DrawTabPicture(f, tbt);
    }

cleanup:
    if (pPara)
        pPara->Release();
    return hr;
}

The following example shows how to copy only the tab information from one ITextPara interface to another. It takes two parameters: ITextPara *pParaFrom (the paragraph from which to copy tabs) and ITextPara *pParaTo (the paragraph to which to copy tabs).

HRESULT CopyOnlyTabs(ITextPara *pParaFrom, ITextPara *pParaTo)
{
    float f;
    short tbt;
    short style;

    pParaTo->ClearAllTabs();

    f = (float) -1.0;
    while (pParaFrom->GetTab(tbgoNext, &f, &tbt, &style) == S_OK)
        pParaTo->AddTab(f, tbt, style);
    return S_OK;
}


Using a Font Duplicate

The following sample shows how a font duplicate can be used to apply a number of changes to a range at once.

void ChangeFontNameSizeBold(ITextSelection *pSel)
{
    ITextFont *pFontSel = NULL, *FontDuplicate = NULL;

    // Get ITextFont version of non-duplicated font.
    if (FAILED(pSel->GetFont( &pFontSel))
        return;

    // Duplicate the font.
    pFontSel->GetValue(&pFontDuplicate);
    pFontSel->Release();
    if(!pFontDuplicate)
        return;

// Changes here happen only to the underlying data structure,
// such as a CHARFORMAT, in the duplicate - NOT to the actual
// story text.
    BSTR bstrTemp =
         UnicodeBstrFromAnsi("Times New Roman");   // Font name
    pFontDuplicate->SetName(bstrTemp);
    SysFreeString(bstrTemp);
    pFontDuplicate->SetBold(tomTrue);    // Bold
    pFontDuplicate->SetSize(10.5);       // 10.5 point font.
    pFontDuplicate->SetAnimation(tomBlackMarchingAnts);

    // Now apply change to text as one change: one screen
    // update, one undo. You can also apply the font object
    // to different ranges before you free it.
    pSel->SetFont(pFontDuplicate);
    pFontDuplicate->Release();
}


Text Object Model Reference

The following element is used with the Text Object Model (TOM):

  • Text Object Model Interfaces


Text Object Model Interfaces

The following interfaces are used with TOM.

Interface | Description
ITextDocument | Retrieves the active selection and range objects for any story in the document.
ITextFont | Encapsulates the functionality of the Microsoft Word Font dialog box.
ITextPara | Encapsulates the functionality of the Microsoft Word Paragraph dialog box.
ITextRange | Enables an application to select text in a story and then examine or change that text.
ITextSelection | A text selection is a text range with selection highlighting. It is associated with some kind of view, and has some UI-oriented methods that allow one to emulate keyboard input.
ITextStoryRanges | Enumerates the stories in an ITextDocument object.


ITextDocument

The ITextDocument interface is the TOM top-level interface, which retrieves the active selection and range objects for any story in the document—whether active or not. It enables the application to:

  • Open and save documents.
  • Control undo behavior and screen updating.
  • Find a range from a screen position.
  • Get an ITextStoryRanges story enumerator.

When to Implement

Applications typically do not implement the ITextDocument interface. Microsoft text solutions, such as rich edit controls, implement ITextDocument as part of their Text Object Model (TOM) implementation.

When to Use

Applications can retrieve an ITextDocument pointer from a rich edit control. To do this, send an EM_GETOLEINTERFACE message to retrieve an IRichEditOle object from a rich edit control. Then, call the object's QueryInterface method to retrieve an ITextDocument pointer.

Methods in Vtable Order

IUnknown Methods

QueryInterface
AddRef
Release

IDispatch Methods

GetTypeInfoCount
GetTypeInfo
GetIDsOfNames
Invoke

ITextDocument Methods

Method | Description
BeginEditCollection | Turns on undo grouping.
EndEditCollection | Turns off undo grouping.
Freeze | Increments the freeze count. If this count is nonzero, screen updating is disabled.
GetDefaultTabStop | Retrieves the default tab width.
GetName | Retrieves the file name of this document.
GetSaved | Determines whether changes have been made since the file was last saved.
GetSelection | Retrieves the active selection.
GetStoryCount | Retrieves the count of stories in this document.
GetStoryRanges | Retrieves a story collection object used to enumerate the stories in a document.
New | Opens a new document.
Open | Opens a specified document.
Range | Retrieves a text range object for a specified range in the active story of the document.
RangeFromPoint | Retrieves the range corresponding to a specified point.
Redo | Performs a specified number of redo operations.
Save | Saves the document to a file or IStream object.
SetDefaultTabStop | Sets the default tab width.
SetSaved | Sets the value of the flag returned by the GetSaved method.
Undo | Performs a specified number of undo operations.
Unfreeze | Decrements the freeze count. If this count goes to zero, screen updating is enabled.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, Using TOM GUIDs


ITextDocument::BeginEditCollection

The ITextDocument::BeginEditCollection method turns on edit collection, that is, Undo Grouping.

STDMETHODIMP ITextDocument::BeginEditCollection(void)

Parameters

This method has no parameters.

Return Values

If BeginEditCollection succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
S_FALSE | Undo is not enabled.
E_NOTIMPL | This method is not implemented.

Remarks

A single Undo command undoes all changes made while edit collection is turned on. While edit collection is on, the screen is frozen even if the freeze count is zero.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextDocument, ITextDocument::EndEditCollection, ITextDocument::Freeze


ITextDocument::EndEditCollection

The ITextDocument::EndEditCollection method turns off edit collection and terminates Undo Grouping.

STDMETHODIMP ITextDocument::EndEditCollection(void)

Parameters

This method has no parameters.

Return Values

If EndEditCollection succeeds, it returns S_OK. If the method fails, it returns the following COM error code. For more information about COM error codes, see Error Handling.

Value | Meaning
E_NOTIMPL | This method is not implemented.

Remarks

The screen is unfrozen unless the freeze count is nonzero.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextDocument, ITextDocument::BeginEditCollection, ITextDocument::Freeze


ITextDocument::Freeze

The ITextDocument::Freeze method increments the freeze count.

STDMETHODIMP ITextDocument::Freeze(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives the updated freeze count.

Return Values

If the Freeze count is nonzero, it returns S_OK. If the Freeze count is zero, it returns FALSE.

Remarks

If the freeze count is nonzero, screen updating is disabled. This allows a sequence of editing operations to be performed without the performance loss and flicker of screen updating. To decrement the freeze count, call the ITextDocument::Unfreeze method.

Note that if edit collection is on (see ITextDocument::BeginEditCollection), the screen is automatically frozen regardless of the freeze count.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextDocument, ITextDocument::Unfreeze, ITextDocument::BeginEditCollection


ITextDocument::GetDefaultTabStop

The ITextDocument::GetDefaultTabStop property-get method retrieves the default tab width.

STDMETHODIMP ITextDocument::GetDefaultTabStop(
  float *pValue
);

Parameters

pValue
Pointer to a variable that receives the default tab width.

Return Values

If GetDefaultTabStop succeeds, it returns S_OK. If pValue is null, the method fails and it returns E_INVALIDARG. For more information about COM error codes, see Error Handling.

Remarks

The default tab width is used whenever no tab exists beyond the current display position. The default width is given in floating-point points.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextDocument, ITextPara::AddTab, ITextPara::ClearAllTabs, ITextPara::DeleteTab, ITextPara::GetListTab, ITextPara::GetTab, ITextPara::GetTabCount, ITextPara::SetListTab


ITextDocument::GetName

The ITextDocument::GetName property-get method retrieves the file name of this document. This is the ITextDocument default property.

STDMETHODIMP ITextDocument::GetName(
  BSTR *pName
);

Parameters

pName
Pointer to a variable that receives a BSTR containing the file name.

Return Values

If GetName succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
S_FALSE | No file name associated with this object.
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory for output string.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextDocument


ITextDocument::GetSaved

The ITextDocument::GetSaved property-get method determines whether changes have been made since the file was last saved.

STDMETHODIMP ITextDocument::GetSaved(
  long *pBool
);

Parameters

pBool
Pointer to a variable that receives the value tomTrue if no changes have been made since the file was last saved, or to the value tomFalse if there are unsaved changes.

Return Values

If GetSaved succeeds, it returns S_OK. If the method fails, it returns the following COM error code. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.

Remarks

To set the Saved property, call the ITextDocument::SetSaved method.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextDocument, ITextDocument::SetSaved


ITextDocument::GetSelection

The ITextDocument::GetSelection property-get method retrieves the active selection.

STDMETHODIMP ITextDocument::GetSelection(
  ITextSelection **ppSel
);

Parameters

ppSel
Pointer to a variable that receives an ITextSelection pointer for the active selection.

Return Values

If GetSelection succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
S_FALSE | Indicates no active selection.
E_INVALIDARG | Invalid argument.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextDocument, ITextSelection


ITextDocument::GetStoryCount

The ITextDocument::GetStoryCount property-get method retrieves the count of stories in this document.

STDMETHODIMP ITextDocument::GetStoryCount(
  LONG *pCount
);

Parameters

pCount
Pointer to a variable that receives the number of stories in the document.

Return Values

If GetStoryCount succeeds, it returns S_OK. If the method fails, it returns the following COM error code. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.

Remarks

Rich edit controls have only one story and do not implement the ITextDocument::GetStoryRanges method. To avoid getting an error when there is only one story, use GetStoryCount to check the story count. If the story count is greater than one, then call GetStoryRanges.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextDocument, ITextDocument::GetStoryRanges


ITextDocument::GetStoryRanges

The ITextDocument::GetStoryRanges property-get method retrieves the story collection object used to enumerate the stories in a document.

STDMETHODIMP ITextDocument::GetStoryRanges(
  ITextStoryRanges **ppStories
);

Parameters

ppStories
Pointer to a variable that receives an ITextStoryRanges pointer.

Return Values

If GetStoryRanges succeeds, it returns S_OK. If the method fails, it returns the following COM error code. For more information about COM error codes, see Error Handling.

Value | Meaning
E_NOTIMPL | Not implemented; only one story in this document.

Remarks

Invoke this method only if ITextDocument::GetStoryCount returns a value greater than 1.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextDocument, ITextDocument::GetStoryCount, ITextStoryRanges


ITextDocument::New

The ITextDocument::New method opens a new document.

STDMETHODIMP ITextDocument::New(void);

Parameters

This method has no parameters.

Return Values

If the New method succeeds, it returns S_OK.

Remarks

If another document is open, this method saves any current changes and closes the current document before opening a new one.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextDocument, ITextDocument::Open


ITextDocument::Open

The ITextDocument::Open method opens a specified document. There are parameters to specify access and sharing privileges, creation and conversion of the file, as well as the code page for the file.

STDMETHODIMP ITextDocument::Open(
  VARIANT FAR *pVar,
  long Flags,
  long CodePage
);

Parameters

pVar
[in] Pointer to a variable that specifies the file name or IStream to open.
Flags
File creation, open, share, and conversion flags. Default value is zero, which gives read/write access and read/write sharing, open always, and automatic recognition of the file format (unrecognized file formats are treated as text). Other values are defined in the following tables.
Access/share flags | Value | Meaning (any combination)
tomReadOnly | 0x0100 | Read only.
tomShareDenyRead | 0x0200 | Other programs cannot read.
tomShareDenyWrite | 0x0400 | Other programs cannot write.
tomPasteFile | 0x1000 | Replaces selection with file.

Create/convert flags | Value | Meaning (mutually exclusive)
tomCreateNew | 0x0010 | Creates new file; fails if it exists already.
tomCreateAlways | 0x0020 | Creates new file; it destroys an existing file.
tomOpenExisting | 0x0030 | Opens existing file; otherwise fails.
tomOpenAlways | 0x0040 | Opens existing file, otherwise creates new.
tomTruncateExisting | 0x0050 | Opens existing file, but truncates it to zero length.
tomRTF | 0x0001 | Opens as RTF.
tomText | 0x0002 | Opens as text (ANSI or Unicode).
tomHTML | 0x0003 | Opens as HTML.
tomWordDocument | 0x0004 | Opens as Word document.

CodePage
Code page to use for the file. Zero (the default value) means CP_ACP (ANSI code page) unless the file begins with a Unicode BOM (0xfeff), in which case the file is considered to be Unicode. Note that code page 1200 is Unicode, CP_UTF8 is UTF-8.

Return Values

The return value can be an HRESULT that corresponds to a Microsoft® Win32® error or COM error code, or it can be one of the following values.

Value | Meaning
S_OK | Method succeeds
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.
E_NOTIMPL | Feature not implemented.

Remarks

If a document is created with the New method and the zero values are used, then the TOM engine has to choose which flags and code page to use. UTF-8 RTF (defined below) is an attractive default.

Rich Edit 3.0 defines a control word, \urtf8, which should be used instead of \rtf1. This means the file is encoded in UTF-8 (Unicode transformation format, 8-bit). On input, RTF files contain the relevant code-page information, but this can be changed for saving purposes, thereby allowing one version to be translated to another.

If the tomPasteFile flag is not set in the Flags parameter, the method first closes the current document after saving any unsaved changes.

A file is recognized as a Unicode text file if it starts with the Unicode byte-order mark (0xfeff, otherwise known as the BOM). The ITextDocument::Open method strips off this Unicode byte-order mark on input and ITextDocument::Save applies it on output. See the comments on the ITextDocument::Save method, which discuss putting the Unicode byte-order mark at the beginning of Unicode plain-text files. The conversion values tomRTF, tomHTML, and tomWordDocument are used primarily for the Save method, since these formats are easily recognized on input.

Errors are reported by negative HRESULTs, but since file operations have many kinds of errors, you may not need all of the error information provided. In particular, you may not care (or you may already know) which file facility is used, namely Win32 (pVar.vt = VT_BSTR) or OLE storage for IStream and IStorage. By masking off bit 18 of an HRESULT, you can ignore the difference and compare an HRESULT for either system to its STG_E_xxx value. For example:

HRESULT hr;
VARIANT Var;

VariantInit(&Var)
Var.vt = VT_BSTR;
Var.bstrVal = SysAllocStr(L"test.txt"); // Will use Win32 file command
hr = pDoc->Open(&Var, tomOpenExisting, 0);
hr &= ~0x40000; // Mask off bit 18
if(hr == STG_E_FILENOTFOUND)
{
…// the rest of the code
}

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextDocument, ITextDocument::Save, IStream, IStorage


ITextDocument::Range

The ITextDocument::Range method retrieves an ITextRange object for a specified range in the active story of the document.

STDMETHODIMP ITextDocument::Range(
  long cpFirst,
  long cpLim,
  ITextRange **ppRange
);

Parameters

cpFirst
Start position of new range. The default value is zero, which represents the start of the document.
cpLim
End position of new range. The default value is zero.
ppRange
Pointer to a variable that receives an ITextRange object for the specified text range.

Return Values

If Range succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information on COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextDocument, ITextRange


ITextDocument::RangeFromPoint

The ITextDocument::RangeFromPoint method retrieves the range corresponding (at or nearest) to the point with the specified (x,y) screen coordinates.

STDMETHODIMP ITextDocument::RangeFromPoint(
  long x,
  long y,
  ITextRange **ppRange
);

Parameters

x
Horizontal coordinate of the specified point.
y
Vertical coordinate of the specified point.
ppRange
Pointer to a variable that receives an ITextRange object for the text range that corresponds to the specified point.

Return Values

If RangeFromPoint succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information on COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.

Remarks

As an example, the following Microsoft® Visual Basic® program gets the range from a point, expands to include the entire visible range, and then prints each character in this range along with its position.

Sub PrintChars(Doc As ITextDocument, x, y)
    Dim r As ITextRange
    r = Doc.RangeFromPoint(x, y)
    r.Expand tomWindow    ' Expand to visible text in story
    While(r.Start < r.End)    ' Walk the range
        r.GetPoint  x1, y1    ' Get position of baseline at Start
        print r.Char, x1, y1    ' Show the folks
        MoveStart tomCharacter    ' Move Start to next character
    Wend
End Sub

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextDocument, ITextRange, ITextRange::Expand, ITextRange::GetPoint, ITextRange::MoveStart


ITextDocument::Redo

The ITextDocument::Redo method performs a specified number of redo operations.

STDMETHODIMP ITextDocument::Redo(
  long Count,
  long *prop
);

Parameters

Count
The number of redo operations specified.
prop
Pointer to a variable that receives the actual count of redo operations performed. This parameter can be null.

Return Values

If Redo succeeds it returns S_OK. If the method fails, it returns the following COM error code. For more information on COM error codes, see Error Handling.

Value | Meaning
S_FALSE | Less than Count redo operations were performed.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextDocument, ITextDocument::Undo


ITextDocument::Save

The ITextDocument::Save method saves the ITextDocument to the target pVar.

STDMETHODIMP ITextDocument::Save(
  VARIANT *pVar,
  long Flags,
  long CodePage
);

Parameters

pVar
[in] The save target. This parameter is a VARIANT, which can be a file name, or null.
Flags
[in] File creation, open, share, and conversion flags as defined in the table given for the ITextDocument::Open method.
CodePage
[in] The specified code page. Common values are CP_ACP (zero: system ANSI code page), 1200 (Unicode), and 1208 (UTF-8).

Return Values

The return value can be an HRESULT that corresponds to a Win32 error or COM error code, or it can be one of the following values.

Value | Meaning
S_OK | Method succeeds.
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.
E_NOTIMPL | Feature not implemented.

Remarks

To use the parameters that were specified for opening the file, use zero values for the parameters. If pVar is null or missing, the file name given by this document's name is used. If both of these are missing or null, the method fails. If pVar specifies a file name, that name should replace the current Name property.

Similarly, the Flags and CodePage arguments can overrule those supplied in the Open method and define the values to use for files created with the New method.

Unicode plain-text files should be saved with the Unicode byte-order mark (0xFEFF) as the first character. This character should be removed when the file is read in; that is, it is only used for import/export to identify the plain text as Unicode and to identify the byte order of that text. Microsoft Notepad adopted this convention, which is now recommended by the Unicode standard.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextDocument, ITextDocument::New, ITextDocument::Open , IStream


ITextDocument::SetDefaultTabStop

The ITextDocument::SetDefaultTabStop property-put method sets the default tab stop, which is used when no tab exists beyond the current display position.

STDMETHODIMP ITextPara::SetDefaultTabStop(
  float Value
);

Parameters

Value
[in] New default tab setting, in floating-point points. Default value is 36.0 points, that is, 0.5 inches.

Return Values

If SetDefaultTabStop succeeds it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information on COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextDocument, ITextDocument::GetDefaultTabStop, ITextPara::AddTab, ITextPara::ClearAllTabs, ITextPara::DeleteTab, ITextPara::GetListTab, ITextPara::GetTab, ITextPara::GetTabCount, ITextPara::SetListTab


ITextDocument::SetSaved

The ITextDocument::SetSaved property-put method sets the document Saved property.

STDMETHODIMP ITextDocument::SetSaved(
  long Bool
);

Parameters

Bool
[in] New value of the Saved property. It can be one of the following values.
Value | Meaning
tomTrue | No changes to the file since the last time it was saved.
tomFalse | There are changes to the file.

Return Values

The return value is S_OK.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextDocument, ITextDocument::GetSaved


ITextDocument::Undo

The ITextDocument::Undo method performs a specified number of undo operations.

STDMETHODIMP ITextDocument::Undo(
  long Count,
  long *prop
);

Parameters

Count
The specified number of undo operations.

If the value of this parameter is tomFalse, undo processing is suspended. If this parameter is tomTrue, undo processing is restored.

prop
Pointer to a variable that receives the actual count of undo operations performed. This parameter can be null.

Return Values

If all of the Count undo operations were performed, it returns S_OK. If the method fails, it returns S_FALSE, indicating that less than Count undo operations were performed. For more information on COM error codes, see Error Handling.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextDocument, ITextDocument::Redo


ITextDocument::Unfreeze

The ITextDocument::Unfreeze method decrements the freeze count.

STDMETHODIMP ITextDocument::Unfreeze(
  long *pCount
);

Parameters

pCount
Pointer to a variable that receives the updated freeze count.

Return Values

If the Freeze count is zero, it returns S_OK. If the method fails, it returns S_FALSE, indicating that the Freeze count is nonzero. For more information about COM error codes, see Error Handling.

Remarks

If the freeze count goes to zero, screen updating is enabled. This method cannot decrement the count below zero, and no error occurs if it is executed with a zero freeze count.

Note, if edit collection is active, screen updating is suppressed, even if the freeze count is zero.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextDocument, ITextDocument::BeginEditCollection, ITextDocument::Freeze


ITextFont

TOM rich text–range attributes are accessed through a pair of dual interfaces, ITextFont and ITextPara. These interfaces encapsulate the functionality of the Microsoft Word Format Font and Paragraph dialog boxes, respectively. Both interfaces include a duplicate (Value) property that can return a duplicate of the attributes in a range object or transfer a set of attributes to a range. As such, they act like programmable format painters. For example, you could transfer all attributes from range r1 to range r2 except for making r2 bold and the font size 12 points by using the following subroutine.

Sub AttributeCopy(r1 As ITextRange, r2 As ITextRange)
    Dim tf As ITextFont
    tf = r1.Font                ' Value is the default property
    tf.Bold = tomTrue             ' You can make some modifications
    tf.Size = 12
    tf.Animation = tomSparkleText
    r2.Font = tf                ' Apply font attributes all at once
End Sub

See ITextRange::SetFont for a similar example written in C++.

The ITextFont attribute interface represents the traditional VBA way of setting properties and it gives the desired VBA notation.

ITextFont uses a special variable type, called tomBool, for rich-text attributes that have binary states. The tomBool type is different from the Boolean type because it can take four values: tomTrue, tomFalse, tomToggle, and tomUndefined. The tomTrue and tomFalse values indicate True and False. The tomToggle value is used to toggle a property. The tomUndefined value, more traditionally called NINCH, is a special no-input, no-change value that works with longs, floats, and COLOREFs. For strings, tomUndefined (or NINCH) is represented by the null string. For Set operations, using tomUndefined does not change the target property. For Get operations, tomUndefined means that the characters in the range have different values (it gives the grayed check box in property dialog boxes).

The rich edit control is able to accept and return all ITextFont properties intact, that is, without modification, both through TOM and through its RTF converters. However, it cannot display the All Caps, Animation, Embossed, Imprint, Shadow, Small Caps, Hidden, Kerning, Outline, and Style font properties.

When to Implement

Applications typically do not implement the ITextFont interface. Microsoft text solutions, such as rich edit controls, implement ITextFont as part of their Text Object Model (TOM) implementation.

When to Use

Applications can retrieve an ITextFont pointer for a text range by calling the ITextRange::GetFont method.

Methods in Vtable Order

IUnknown Methods

QueryInterface
AddRef
Release

IDispatch Methods

GetTypeInfoCount
GetTypeInfo
GetIDsOfNames
Invoke

ITextFont Methods

Method | Description
CanChange | Determines whether the font object can be changed.
GetAllCaps | Retrieves the AllCaps property.
GetAnimation | Retrieves the type of animation.
GetBackColor | Retrieves the background color.
GetBold | Retrieves the Bold property.
GetDuplicate | Creates a duplicate of the font object.
GetEmboss | Retrieves the Emboss property.
GetEngrave | Retrieves the Engrave property.
GetForeColor | Retrieves the foreground (text) color.
GetHidden | Retrieves the Hidden property.
GetItalic | Retrieves the italic state.
GetKerning | Retrieves the font size, above which kerning is turned on.
GetLanguageID | Retrieves the language identifier.
GetName | Retrieves the font name.
GetOutline | Retrieves the Outline property.
GetPosition | Retrieves the character offset relative to the baseline.
GetProtected | Retrieves the Protected property.
GetShadow | Retrieves the Shadow property.
GetSize | Retrieves the font size.
GetSmallCaps | Retrieves the SmallCaps property.
GetSpacing | Retrieves the intercharacter spacing.
GetStrikeThrough | Retrieves the StrikeThrough property.
GetStyle | Retrieves the character style handle for the characters in a range.
GetSubscript | Retrieves the Subscript property.
GetSuperscript | Retrieves the Superscript property.
GetUnderline | Retrieves the underline style.
GetWeight | Retrieves the font weight.
IsEqual | Determines whether two font objects have the same properties.
Reset | Resets the character formatting to the default values.
SetAllCaps | Sets the AllCaps property.
SetAnimation | Sets the type of animation.
SetBackColor | Sets the background color.
SetBold | Sets the Bold property.
SetDuplicate | Sets the character formatting of the specified font object.
SetEmboss | Sets the Emboss property.
SetEngrave | Sets the Engrave property.
SetForeColor | Sets the foreground (text) color.
SetHidden | Sets the Hidden property.
SetItalic | Sets the italic state.
SetKerning | Sets the font size, above which kerning is turned on.
SetLanguageID | Sets the language identifier.
SetName | Sets the font name.
SetOutline | Sets the Outline property.
SetPosition | Sets the character offset relative to the baseline.
SetProtected | Sets the Protected property.
SetShadow | Sets the Shadow property.
SetSize | Sets the font size.
SetSmallCaps | Sets the SmallCaps property.
SetSpacing | Sets the intercharacter spacing.
SetStrikeThrough | Sets the StrikeThrough property.
SetStyle | Sets the character style handle for the characters in a range.
SetSubscript | Sets the Subscript property.
SetSuperscript | Sets the Superscript property.
SetUnderline | Sets the underline style.
SetWeight | Sets the font weight.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, Using TOM GUIDs


ITextFont::CanChange

The ITextFont::CanChange property-get method determines whether the font can be changed.

STDMETHODIMP ITextFont::CanChange(
  long *pbCanChange
);

Parameters

pbCanChange
Pointer to a variable that receives tomTrue if the font can be changed or tomFalse if it cannot be changed. This parameter can be null.

Return Values

If the font can change, CanChange returns S_OK. If the method fails, it returns the following COM error code. For more information about COM error codes, see Error Handling.

Value | Meaning
S_FALSE | The font cannot change.

Remarks

The *pbCanChange returns tomTrue only if the font can be changed. That is, no part of an associated range is protected and an associated document is not read-only. If this ITextFont object is a duplicate, no protection rules apply.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont


ITextFont::GetAllCaps

The ITextFont::GetAllCaps property-get method retrieves the state of the AllCaps property.

STDMETHODIMP ITextFont::GetAllCaps(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives tomTrue when the AllCaps property is on and receives tomFalse when the AllCaps property is off.

Return Values

If GetAllCaps succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | The method included an invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.

Remarks

This property corresponds to the CFE_ALLCAPS effect described in the CHARFORMAT2 structure.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::SetAllCaps, CHARFORMAT2


ITextFont::GetAnimation

The ITextFont::GetAnimation property-get method retrieves the animation type.

STDMETHODIMP ITextFont::GetAnimation(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives one of the following animation types.
Animation type | Value
tomNoAnimation | 0
tomLasVegasLights | 1
tomBlinkingBackground | 2
tomSparkleText | 3
tomMarchingBlackAnts | 4
tomMarchingRedAnts | 5
tomShimmer | 6
tomWipeDown | 7
tomWipeRight | 8

Return Values

If GetAnimation succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::SetAnimation


ITextFont::GetBackColor

The ITextFont::GetBackColor property-get method retrieves the background color.

STDMETHODIMP ITextFont::GetBackColor(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives one of the following values to indicate the background (highlight) color for a range.
Value | Meaning
A COLORREF value | The high-order byte is zero, and the three low-order bytes specify an RGB color.
A value returned by PALETTEINDEX | The high-order byte is 1, and the low-order word specifies the index of a logical-color palette entry.
tomAutocolor (-9999997) | Indicates the range uses the default system background color.

Return Values

If GetBackColor succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, COLORREF, ITextFont::SetBackColor, PALETTEINDEX


ITextFont::GetBold

The ITextFont::GetBold property-get method retrieves the bold state.

STDMETHODIMP ITextFont::GetBold(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives tomTrue if the Bold property is on or tomFalse if it is off.

Return Values

If GetBold succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.

Remarks

You can use the ITextFont::SetWeight and ITextFont::GetWeight methods to set or retrieve the font weight more precisely than the binary Bold property.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::SetBold, ITextFont::GetWeight, ITextFont::SetWeight


ITextFont::GetDuplicate

The ITextFont::GetDuplicate property-get method creates a duplicate of this character format object. The duplicate property is the default property of an ITextFont object.

STDMETHODIMP ITextFont::GetDuplicate(
  ITextFont **ppFont
);

Parameters

ppFont
Pointer to a variable that receives a pointer to a duplicate ITextFont object.

Return Values

If GetDuplicate succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_OUTOFMEMORY | Memory could not be allocated for the new object.
E_INVALIDARG | The method includes an invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.

Remarks

For an example of how to use font duplicates, see ITextRange::SetFont.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::SetDuplicate, ITextRange::SetFont


ITextFont::GetEmboss

The ITextFont::GetEmboss property-get method retrieves the state of the Emboss property, which indicates whether characters should be embossed.

STDMETHODIMP ITextFont::GetEmboss(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives tomTrue if the Emboss property is on, or tomFalse if it is off.

Return Values

If GetEmboss succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.

Remarks

This property corresponds to the CFE_EMBOSS effect described in the CHARFORMAT2 structure.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::SetEmboss, CHARFORMAT2


ITextFont::GetEngrave

The ITextFont::GetEngrave property-get method retrieves the state of the Engrave property, which indicates whether characters should be displayed as imprinted characters.

STDMETHODIMP ITextFont::GetEngrave(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives tomTrue if the Engrave property is on or tomFalse if it is off.

Return Values

If GetEngrave succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.

Remarks

This property corresponds to the CFE_IMPRINT effect described in the CHARFORMAT2 structure.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::SetEngrave, CHARFORMAT2


ITextFont::GetForeColor

The ITextFont::GetForeColor property-get method retrieves the foreground (text) color.

STDMETHODIMP ITextFont::GetForeColor(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives one of the following values to indicate the foreground (text) color for a range.
Value | Meaning
A COLORREF value | The high-order byte is zero, and the three low-order bytes specify an RGB color.
A value returned by PALETTEINDEX | The high-order byte is 1, and the low-order word specifies the index of a logical-color palette entry.
tomAutocolor (-9999997) | Indicates that the range uses the default system foreground color.

Return Values

If GetForeColor succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, COLORREF, ITextFont::SetForeColor, PALETTEINDEX


ITextFont::GetHidden

The ITextFont::GetHidden property-get method retrieves the state of the Hidden property, which indicates whether characters are displayed.

STDMETHODIMP ITextFont::GetHidden(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives tomTrue if the Hidden property is on or tomFalse if it is off.

Return Values

If GetHidden succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.

Remarks

This property corresponds to the CFE_HIDDEN effect described in the CHARFORMAT2 structure.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::SetHidden, CHARFORMAT2


ITextFont::GetItalic

The ITextFont::GetItalic property-get method retrieves the italic state.

STDMETHODIMP ITextFont::GetItalic(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives tomTrue if the Italic property is on, or tomFalse if it is off.

Return Values

If GetItalic succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::SetItalic


ITextFont::GetKerning

The ITextFont::GetKerning property-get method retrieves the minimum kerning size, which is given in floating-point points.

STDMETHODIMP ITextFont::GetKerning(
  float *pValue
);

Parameters

pValue
Pointer to a variable that receives the font size above which kerning is turned on, in floating-point points.

Return Values

If GetKerning succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.

Remarks

If the value pointed to by pValue is zero, kerning is turned off. Positive values turn on pair kerning for font point sizes greater than or equal to the kerning value. For example, the value 1 turns on kerning for all legible sizes, whereas 16 turns on kerning only for font sizes of 16 points and larger.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::SetKerning


ITextFont::GetLanguageID

The ITextFont::GetLanguageID property-get method retrieves the language identifier (more generally the LCID).

STDMETHODIMP ITextFont::GetLanguageID(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives the language identifier.

Return Values

If GetLanguageID succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.

Remarks

The low-order word of the language identifier value has the Win32 language identifier. The high-order word is either zero or contains the high word of the locale identifier (LCID). To be sure you get the language identifier, mask out the high word.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::SetLanguageID


ITextFont::GetName

The ITextFont::GetName property-get method retrieves the font name.

STDMETHODIMP ITextFont::GetName(
  BSTR *pbstr
);

Parameters

pbstr
Pointer to a variable that receives a BSTR containing the font name.

Return Values

If GetName succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Could not allocate memory for string.
CO_E_RELEASED | The font object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::SetName, BSTR


ITextFont::GetOutline

The ITextFont::GetOutline property-get method retrieves the state of the Outline property, which indicates whether characters are displayed as outlined characters.

STDMETHODIMP ITextFont::GetOutline(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives tomTrue if the Outline property is on or tomFalse if it is off.

Return Values

If GetOutline succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.

Remarks

This property corresponds to the CFE_OUTLINE effect described in the CHARFORMAT2 structure.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::SetOutline, CHARFORMAT2


ITextFont::GetPosition

The ITextFont::GetPosition property-get method retrieves the character offset relative to the baseline. The value is given in floating-point points.

STDMETHODIMP ITextFont::GetPosition(
  float *pValue
);

Parameters

pValue
Pointer to a variable that receives the relative vertical offset, in floating-point points.

Return Values

If GetPosition succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.

Remarks

Normally, displayed text has a zero value for this property. Positive values raise the text, and negative values lower it.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::SetPosition


ITextFont::GetProtected

The ITextFont::GetProtected property-get method retrieves the state of the Protected property, which indicates whether the characters are protected against modification attempts.

STDMETHODIMP ITextFont::GetProtected(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives tomTrue if the Protected property is on or tomFalse if it is off.

Return Values

If GetProtected succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.

Remarks

In general, TOM methods that attempt to change the formatting or content of a range will fail with E_ACCESSDENIED if any part of that range is protected or if the document is read only. To make a change in protected text, the TOM client should attempt to turn off the protection of the text to be modified. The owner of the document may permit this to happen. For example in rich edit controls, attempts to change protected text result in an EN_PROTECTED notification message to the creator of the document, who then can refuse or grant permission for the change. The creator is the client that created a windowed rich edit control through the CreateWindow function or the ITextHost object that called the CreateTextServices function to create a windowless rich edit control.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::SetProtected, CreateTextServices, CreateWindow, EN_PROTECTED


ITextFont::GetShadow

The ITextFont::GetShadow property-get method retrieves the state of the Shadow property, which indicates whether characters should be displayed as shadowed characters.

STDMETHODIMP ITextFont::GetShadow(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives tomTrue if the Shadow property is on or tomFalse if it is off.

Return Values

If GetShadow succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.

Remarks

This property corresponds to the CFE_SHADOW effect described in the CHARFORMAT2 structure.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::SetShadow, CHARFORMAT2


ITextFont::GetSize

The ITextFont::GetSize property-get method retrieves the font size.

STDMETHODIMP ITextFont::GetSize(
  float *pValue
);

Parameters

pValue
Pointer to a variable that receives the font size, in floating-point points.

Return Values

If GetSize succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::SetSize


ITextFont::GetSmallCaps

The ITextFont::GetSmallCaps property-get method retrieves the state of the SmallCaps property.

STDMETHODIMP ITextFont::GetSmallCaps(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives tomTrue if the SmallCaps property is on or tomFalse if it is off.

Return Values

If GetSmallCaps succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.

Remarks

This property corresponds to the CFE_SMALLCAPS effect described in the CHARFORMAT2 structure.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::SetSmallCaps, CHARFORMAT2


ITextFont::GetSpacing

The ITextFont::GetSpacing property-get method retrieves the intercharacter spacing.

STDMETHODIMP ITextFont::GetSpacing(
  float *pValue
);

Parameters

pValue
Pointer to a variable that receives the horizontal spacing between characters, in floating-point points.

Return Values

If GetSpacing succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.

Remarks

Normally, spaced text is given by an intercharacter spacing value of zero. Positive values expand the spacing, and negative values compress it.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::SetSpacing


ITextFont::GetStrikeThrough

The ITextFont::GetStrikeThrough property-get method retrieves the state of the StrikeThrough property, which indicates whether characters should be displayed as struck out.

STDMETHODIMP ITextFont::GetStrikeThrough(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives tomTrue if the StrikeThrough property is on or tomFalse if it is off.

Return Values

If GetStrikeThrough succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.

Remarks

This property corresponds to the CFE_STRIKEOUT effect described in the CHARFORMAT2 structure.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::SetStrikeThrough, CHARFORMAT2


ITextFont::GetStyle

The ITextFont::GetStyle property-get method retrieves the character style handle for the characters in a range.

STDMETHODIMP ITextFont::GetStyle(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives a character style handle.

Return Values

If GetStyle succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that was deleted.

For more information on COM error codes, see Error Handling.

Remarks

The Text Object Model (TOM) version 1.0 does not specify the meanings of the style handles. The meanings depend on other facilities of the text system that implements TOM.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::SetStyle


ITextFont::GetSubscript

The ITextFont::GetSubscript property-get method retrieves the state of the Subscript property, which indicates whether characters are displayed as subscript.

STDMETHODIMP ITextFont::GetSubscript(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives tomTrue if the Subscript property is on or tomFalse if it is off.

Return Values

If GetSubscript succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.

Remarks

This property corresponds to the CFE_SUBSCRIPT effect described in the CHARFORMAT2 structure.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::SetSubscript, CHARFORMAT2


ITextFont::GetSuperscript

The ITextFont::GetSuperscript property-get method retrieves the state of the Superscript property.

STDMETHODIMP ITextFont::GetSuperscript(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives tomTrue if the Superscript property is on or tomFalse if it is off.

Return Values

If GetSuperscript succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.

Remarks

This property corresponds to the CFE_SUPERSCRIPT effect described in the CHARFORMAT2 structure.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::SetSuperscript, CHARFORMAT2


ITextFont::GetUnderline

The ITextFont::GetUnderline property-get method retrieves the Underline style.

STDMETHODIMP ITextFont::GetUnderline(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives one of the following values to indicate the Underline style.
Underline style | Meaning
tomNone | No underlining.
tomSingle | Single underline.
tomWords | Underline words only.
tomDouble | Double underline.
tomDotted | Dotted underline.
tomTrue | Single underline.
tomUndefined | The underline style is undefined.

Return Values

If GetUnderline succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::SetUnderline


ITextFont::GetWeight

The ITextFont::GetWeight property-get method retrieves the font weight for the characters in a range.

STDMETHODIMP ITextFont::GetWeight(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives the font weight. For more information, see the Remarks.

Return Values

If GetWeight succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.

Remarks

The Bold property is a binary version of the Weight property that sets the weight to FW_BOLD. The font weight exists in the Win32 LOGFONT and the OLE IFont interfaces, and Win32 defines the following degrees of font weight.

Font weight | Value | Font weight | Value
FW_DONTCARE | 0 | FW_MEDIUM | 500
FW_THIN | 100 | FW_SEMIBOLD | 600
FW_EXTRALIGHT | 200 | FW_BOLD | 700
FW_LIGHT | 300 | FW_EXTRABOLD | 800
FW_NORMAL | 400 | FW_HEAVY | 900

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::SetWeight


ITextFont::IsEqual

The ITextFont::IsEqual method determines whether a specified ITextFont object has the same properties as this ITextFont object.

STDMETHODIMP ITextFont::IsEqual(
  ITextFont *pFont,
  long *pB
);

Parameters

pFont
Pointer to an ITextFont object that is compared to this ITextFont object.
pB
Pointer to a variable that receives tomTrue if the font objects have the same properties or tomFalse if they do not. This parameter can be null.

Return Values

If font objects have the same properties, IsEqual succeeds and returns S_OK. If the font objects do not have the same properties, the method fails and returns S_FALSE. For more information about COM error codes, see Error Handling.

Remarks

The font objects are equal only if *pFont belongs to the same TOM object as the current font object. The IsEqual method ignores entries for which either font object has a tomUndefined value.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont


ITextFont::Reset

The ITextFont::Reset method resets the character formatting to the default values.

STDMETHODIMP ITextFont::Reset(
  long Value
);

Parameters

Value
[in] Default character formatting values. This parameter can be one of the following values.
Value | Meaning
tomDefault | System uses the default values defined by the RTF/plain control word.
tomUndefined | Sets all properties to undefined values.

Return Values

If Reset succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
S_FALSE | Protected from change.
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.

Remarks

Calling ITextFont::Reset with tomUndefined sets all properties to undefined values. Thus, applying the font object to a range changes nothing. This applies to a font object that is obtained by the ITextFont::GetDuplicate method.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::GetDuplicate


ITextFont::SetAllCaps

The ITextFont::SetAllCaps property-put method sets the state of the AllCaps property.

STDMETHODIMP ITextFont::SetAllCaps(
  long Value
);

Parameters

Value
[in] Specifies one of the following values to set the AllCaps property state.
Value | Meaning
tomTrue | Turns on the property.
tomFalse | Turns off the property.
tomToggle | Toggles the current setting.
tomUndefined | No change.

Return Values

If SetAllCaps succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::GetAllCaps


ITextFont::SetAnimation

The ITextFont::SetAnimation property-put method sets the animation type.

STDMETHODIMP ITextFont::SetAnimation(
  long Value
);

Parameters

Value
[in] Specifies one of the following animation types.
Animation type | Value
tomNoAnimation | 0
tomLasVegasLights | 1
tomBlinkingBackground | 2
tomSparkleText | 3
tomMarchingBlackAnts | 4
tomMarchingRedAnts | 5
tomShimmer | 6
tomWipeDown | 7
tomWipeRight | 8

Return Values

If SetAnimation succeeds, it returns S_OK. If the method fails, it returns the following COM error code. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::GetAnimation


ITextFont::SetBackColor

The ITextFont::SetBackColor property-put method sets the background color.

STDMETHODIMP ITextFont::SetBackColor(
  long Value
);

Parameters

Value
[in] Background color. This parameter can be one of the following.
Value | Meaning
A COLORREF value. | An RGB color.
A value returned by PALETTEINDEX | A palette index.
tomUndefined | No change.
tomAutoColor | Use the default background color.

If Value contains an RGB color, generate the COLORREF by using the RGB macro.

Return Values

If SetBackColor succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument
CO_E_RELEASED | The font object is attached to a range that has been deleted.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, COLORREF, ITextFont::GetBackColor, PALETTEINDEX, RGB


ITextFont::SetBold

The ITextFont::SetBold property-put method sets the Bold property state.

STDMETHODIMP ITextFont::SetBold(
  long Value
);

Parameters

Value
[in] One of the following values that sets the Bold property state.
Value | Meaning
tomTrue | Turn on the property.
tomFalse | Turn off the property.
tomToggle | Toggle the current setting.
tomUndefined | No change.

Return Values

If SetBold succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument
CO_E_RELEASED | The font object is attached to a range that has been deleted.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::GetBold, ITextFont::GetWeight, ITextFont::SetWeight


ITextFont::SetDuplicate

The ITextFont::SetDuplicate property-put method sets the character formatting of the specified font object.

STDMETHODIMP ITextFont::SetDuplicate(
  ITextFont *pFont
);

Parameters

pFont
[in] Pointer to an ITextFont object to apply to the font object.

Return Values

If SetDuplicate succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument
CO_E_RELEASED | The font object is attached to a range that has been deleted.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.

Remarks

Values with the tomUndefined attribute have no effect.

For an example of how to use font duplicates, see ITextRange::SetFont.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::GetDuplicate, ITextRange::SetFont


ITextFont::SetEmboss

The ITextFont::SetEmboss property-put method sets the state of the Emboss property, which indicates whether characters should be embossed.

STDMETHODIMP ITextFont::SetEmboss(
  long Value
);

Parameters

Value
[in] Specifies the Emboss property state. It may be one of the following values.
Value | Meaning
tomTrue | Turn the property on.
tomFalse | Turn the property off.
tomToggle | Toggle the current setting.
tomUndefined | No change.

Return Values

If SetEmboss succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::GetEmboss


ITextFont::SetEngrave

The ITextFont::SetEngrave property-put method sets the state of the Engrave property, which indicates whether characters should be displayed as imprinted characters.

STDMETHODIMP ITextFont::SetEngrave(
  long Value
);

Parameters

Value
[in] Specifies the Engrave property state. It can be one of the following values.
Value | Meaning
tomTrue | Turn the property on.
tomFalse | Turn the property off.
tomToggle | Toggle the current setting.
tomUndefined | No change.

Return Values

If SetEngrave succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::GetEngrave


ITextFont::SetForeColor

The ITextFont::SetForeColor property-put method sets the foreground (text) color.

STDMETHODIMP ITextFont::SetForeColor(
  long Value
);

Parameters

Value
[in] Foreground color. This parameter can be one of the following.
Value | Meaning
A COLORREF value. | An RGB color.
A value returned by PALETTEINDEX | A palette index.
tomUndefined | No change.
tomAutoColor | Use the default foreground color.

If Value contains an RGB color, generate the COLORREF by using the RGB macro.

Return Values

If SetForeColor succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, COLORREF, ITextFont::GetForeColor, PALETTEINDEX, RGB


ITextFont::SetHidden

The ITextFont::SetHidden property-put method sets the state of the Hidden property, which indicates whether characters are displayed.

STDMETHODIMP ITextFont::SetHidden(
  long Value
);

Parameters

Value
[in] Specifies the Hidden property state. It can be one of the following values.
Value | Meaning
tomTrue | Turn the property on.
tomFalse | Turn the property off.
tomToggle | Toggle the current setting.
tomUndefined | No change.

Return Values

If SetHidden succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::GetHidden


ITextFont::SetItalic

The ITextFont::SetItalic property-put method sets the Italic property state.

STDMETHODIMP ITextFont::SetItalic(
  long Value
);

Parameters

Value
[in] Specifies the Italic property state. It can be one of the following values.
Value | Meaning
tomTrue | Turn the property on.
tomFalse | Turn the property off.
tomToggle | Toggle the current setting.
tomUndefined | No change.

Return Values

If SetItalic succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::GetItalic


ITextFont::SetKerning

The ITextFont::SetKerning property-put method sets the minimum font size at which kerning occurs.

STDMETHODIMP ITextFont::SetKerning(
  float Value
);

Parameters

Value
[in] New value of the minimum kerning size, in floating-point points.

Return Values

If SetKerning succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.

Remarks

If this value is zero, kerning is turned off. Positive values turn on pair kerning for font sizes greater than this kerning value. For example, the value 1 turns on kerning for all legible sizes, whereas 16 turns on kerning only for font sizes of 16 points and larger.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::GetKerning


ITextFont::SetLanguageID

The ITextFont::SetLanguageID property-put method sets the language identifier (more generally, the LCID).

STDMETHODIMP ITextFont::SetLanguageID(
  long Value
);

Parameters

Value
[in] New language identifier.

Return Values

If SetLanguage ID succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.

Remarks

The low word of the language identifier value has the Win32 language identifier. The high word is either zero or it contains the high word of the locale identifier (LCID). To get the language identifier, mask out the high word.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::GetLanguageID


ITextFont::SetName

The ITextFont::SetName property-put method sets the font name.

STDMETHODIMP ITextFont::SetName(
  BSTR Name
);

Parameters

Name
[in] New font name.

Return Values

If SetName succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Name too long.
CO_E_RELEASED | The font object is attached to a range that has been deleted.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::GetName, BSTR


ITextFont::SetOutline

The ITextFont::SetOutline property-put method sets the state of the Outline property, which indicates whether characters are displayed as outlined characters.

STDMETHODIMP ITextFont::SetOutline(
  long Value
);

Parameters

Value
[in] Specifies the Outline property state. It can be one of the following values.
Value | Meaning
tomTrue | Turn the property on.
tomFalse | Turn the property off.
tomToggle | Toggle the current setting.
tomUndefined | No change.

Return Values

If SetOutline succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::SetOutline


ITextFont::SetPosition

The ITextFont::SetPosition property-put method sets the character offset relative to the baseline.

STDMETHODIMP ITextFont::SetPosition(
  float Value
);

Parameters

Value
[in] New value of the relative vertical offset, in floating-point points.

Return Values

If SetPosition succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.

Remarks

Normally, displayed text has a zero value for this property. Positive values raise the text, and negative values lower it.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::GetPosition


ITextFont::SetProtected

The ITextFont::SetProtected property-put method sets the state of the Protected property, which indicates whether the characters are protected against modification attempts.

STDMETHODIMP ITextFont::SetProtected(
  long Value
);

Parameters

Value
[in] Specifies the Protected property state. It can be one of the following values.
Value | Meaning
tomTrue | Turn on the property.
tomFalse | Turn off the property.
tomToggle | Toggle the current setting.
tomUndefined | No change.

Return Values

If SetProtected succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.

Remarks

In general, TOM methods that attempt to change the formatting or content of a range will fail with E_ACCESSDENIED if any part of that range is protected or if the document is read-only. To make a change in protected text, the TOM client should attempt to turn off the protection of the text to be modified. The owner of the document may permit this to happen. For example in rich edit controls, attempts to change protected text result in an EN_PROTECTED notification message to the creator of the document, who then can refuse or grant permission for the change. The creator is the client that created a windowed rich-edit control through the CreateWindow function or the ITextHost object that called the CreateTextServices function to create a windowless rich edit control.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::GetProtected, CreateTextServices, CreateWindow, EN_PROTECTED


ITextFont::SetShadow

The ITextFont::SetShadow property-put method sets the state of the Shadow property, which indicates whether characters should be displayed as shadowed characters.

STDMETHODIMP ITextFont::SetShadow(
  long Value
);

Parameters

Value
[in] Specifies the Shadow property state. It can be one of the following values.
Value | Meaning
tomTrue | Turn on the property.
tomFalse | Turn off the property.
tomToggle | Toggle the current setting.
tomUndefined | No change.

Return Values

If SetShadow succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::GetShadow


ITextFont::SetSize

The ITextFont::SetSize property-put method sets the font size.

STDMETHODIMP ITextFont::SetSize(
  float Value
);

Parameters

Value
[in] New font size, in floating-point points.

Return Values

If SetSize succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::GetSize


ITextFont::SetSmallCaps

The ITextFont::SetSmallCaps property-put method sets the state of the SmallCaps property.

STDMETHODIMP ITextFont::SetSmallCaps(
  long Value
);

Parameters

Value
[in] Specifies the SmallCaps property state. It can be one of the following values.
Value | Meaning
tomTrue | Turn the property on.
tomFalse | Turn the property off.
tomToggle | Toggle the current setting.
tomUndefined | No change.

Return Values

If SetSmallCaps succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::GetSmallCaps


ITextFont::SetSpacing

The ITextFont::SetSpacing property-put method sets the intercharacter spacing.

STDMETHODIMP ITextFont::SetSpacing(
  float Value
);

Parameters

Value
[in] New horizontal spacing between characters, in floating-point points.

Return Values

If SetSpacing succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.

Remarks

Normally, spaced text is given by an intercharacter spacing value of zero. Positive values expand intercharacter spacing, and negative values compress it.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::GetSpacing


ITextFont::SetStrikeThrough

The ITextFont::SetStrikeThrough property-put method sets the state of the StrikeThrough property, which indicates whether characters should be displayed as struck out.

STDMETHODIMP ITextFont::SetStrikeThrough(
  long Value
);

Parameters

Value
[in] Specifies the StrikeThrough property state. It can be one of the following values.
Value | Meaning
tomTrue | Turn on the property.
tomFalse | Turn off the property.
tomToggle | Toggle the current setting.
tomUndefined | No change.

Return Values

If SetStrikeThrough succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::GetStrikeThrough


ITextFont::SetStyle

The ITextFont::SetStyle property-put method sets the character style handle for the characters in a range.

STDMETHODIMP ITextFont::SetStyle(
  long Value
);

Parameters

Value
[in] New character style handle.

Return Values

If SetStyle succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.

Remarks

The Text Object Model (TOM) version 1.0 has no way to specify the meanings of the style handles, which depend on other facilities of the text system implementing TOM.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::GetStyle


ITextFont::SetSubscript

The ITextFont::SetSubscript property-put method sets the state of the Subscript property, which indicates whether characters are displayed as subscript.

STDMETHODIMP ITextFont::SetSubscript(
  long Value
);

Parameters

Value
[in] Specifies the Subscript property state. It can be one of the following values.
Value | Meaning
tomTrue | Turn the property on.
tomFalse | Turn the property off.
tomToggle | Toggle the current setting.
tomUndefined | No change.

Return Values

If SetSubscript succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::GetSubscript


ITextFont::SetSuperscript

The ITextFont::SetSuperscript property-put method sets the state of the Superscript property.

STDMETHODIMP ITextFont::SetSuperscript(
  long Value
);

Parameters

Value
[in] State of the Superscript property. It can be one of the following values.
Value | Meaning
tomTrue | Turn the property on.
tomFalse | Turn the property off.
tomToggle | Toggle the current setting.
tomUndefined | No change.

Return Values

If SetSuperscript succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::GetSuperscript


ITextFont::SetUnderline

The ITextFont::SetUnderline property-put method sets the Underline property.

STDMETHODIMP ITextFont::SetUnderline(
  long Value
);

Parameters

Value
[in] State of the Underline property. It can be one of the following values.
Underline style | Meaning
tomNone | No underlining.
tomSingle | Single underline.
tomWords | Underline words only.
tomDouble | Double underline.
tomDotted | Dotted underline.
tomTrue | Single underline.
tomUndefined | No change.

Return Values

If SetUnderline succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::GetUnderline


ITextFont::SetWeight

The ITextFont::SetWeight property-put method sets the font weight for the characters in a range.

STDMETHODIMP ITextFont::SetWeight(
  long Value
);

Parameters

Value
[in] New font weight. For more information, see the Remarks.

Return Value

If SetWeight succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The font object is attached to a range that has been deleted.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.

Remarks

The Bold property is a binary version of the Weight property that sets the weight to FW_BOLD. The font weight exists in the Win32 LOGFONT and the OLE IFont interfaces, and Win32 defines the following degrees of font weight.

Font weight | Value | Font weight | Value
FW_DONTCARE | 0 | FW_MEDIUM | 500
FW_THIN | 100 | FW_SEMIBOLD | 600
FW_EXTRALIGHT | 200 | FW_BOLD | 700
FW_LIGHT | 300 | FW_EXTRABOLD | 800
FW_NORMAL | 400 | FW_HEAVY | 900

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextFont::GetWeight


ITextPara

TOM rich text–range attributes are accessed through a pair of dual interfaces, ITextFont and ITextPara. These interfaces encapsulate the functionality of the Microsoft Word Format Font and Paragraph dialog boxes, respectively. Both interfaces include a duplicate (Value) property that can return a duplicate of the attributes in a range object or transfer a set of attributes to a range. As such, they act like programmable format painters. For example, you could transfer all attributes from range r1 to range r2, except for making r2 bold and the font size 12 points, by using the following subroutine.

Sub AttributeCopy(r1 As ITextRange, r2 As ITextRange)
    Dim tf As ITextFont
    tf = r1.Font                ' Value is the default property
    tf.Bold = tomTrue             ' You can make some modifications
    tf.Size = 12
    tf.Animation = tomSparkleText
    r2.Font = tf                ' Apply font attributes all at once
End Sub

See ITextRange::SetFont for a similar example written in C++.

The ITextPara interface encapsulates the Microsoft® Word Paragraph dialog box. All measurements are given in floating-point points. The rich edit control is able to accept and return all ITextPara properties intact (that is, without modification), both through TOM and through its RTF converters. However, the following properties have no effect on what the control displays:

  • DoNotHyphen
  • KeepTogether
  • KeepWithNext
  • LineSpacing
  • LineSpacingRule
  • NoLineNumber
  • PageBreakBefore
  • Tab alignments
  • Tab styles (other than tomAlignLeft and tomSpaces)
  • Style WidowControl

When to Implement

Applications typically do not implement the ITextPara interface. Microsoft text solutions, such as rich edit controls implement ITextPara as part of their Text Object Model (TOM) implementation.

When to Use

Applications can retrieve an ITextPara pointer for a text range by calling the ITextRange::GetPara method.

Methods in Vtable Order

IUnknown Methods

QueryInterface
AddRef
Release

IDispatch Methods

GetTypeInfoCount
GetTypeInfo
GetIDsOfNames
Invoke

ITextPara Methods

Method | Description
AddTab | Adds a tab at a given position.
CanChange | Determines whether the paragraph formatting can be changed.
ClearAllTabs | Clears all tabs, reverting to equally spaced tabs with the default tab spacing.
DeleteTab | Deletes a tab at a specified position.
GetAlignment | Gets the current paragraph alignment value.
GetDuplicate | Creates a duplicate of the specified paragraph format object.
GetFirstLineIndent | Gets the amount used to indent the first line of a paragraph.
GetHyphenation | Determines whether automatic hyphenation is enabled for the range.
GetKeepTogether | Determines whether page breaks are allowed within paragraphs.
GetKeepWithNext | Determines whether page breaks are allowed between paragraphs in the range.
GetLeftIndent | Gets the amount used to indent all but the first line of a paragraph.
GetLineSpacing | Gets the line-spacing value for the text range.
GetLineSpacingRule | Gets the line-spacing rule for the text range.
GetListAlignment | Gets the kind of alignment to use for bulleted and numbered lists.
GetListLevelIndex | Gets the list level index used with paragraphs.
GetListStart | Gets the starting value or code of a list numbering sequence.
GetListTab | Gets the list tab setting.
GetListType | Gets the kind of numbering to use with paragraphs.
GetNoLineNumber | Determines whether line numbering is enabled.
GetPageBreakBefore | Determines whether the paragraphs in the range must begin on a new page.
GetRightIndent | Gets the size of the right margin indent of a paragraph.
GetSpaceAfter | Gets the amount of vertical space below a paragraph.
GetSpaceBefore | Gets the amount of vertical space above a paragraph.
GetStyle | Gets the style handle for the paragraphs in the specified range.
GetTab | Gets tab parameters for the specified tab.
GetTabCount | Gets the tab count.
GetWidowControl | Determines whether the widows and orphans in the paragraphs of a range are controlled.
IsEqual | Determines if two ranges have the same properties.
Reset | Resets paragraph formatting to default values.
SetAlignment | Sets the paragraph alignment.
SetDuplicate | Sets the paragraph formatting.
SetHyphenation | Sets the hyphenation for the paragraphs in the range.
SetIndents | Sets the indents for a paragraph.
SetKeepTogether | Controls whether page breaks are allowed within a paragraph in a range.
SetKeepWithNext | Controls whether page breaks are allowed between the paragraphs in a range.
SetLineSpacing | Sets the paragraph line-spacing rule and the line spacing for a paragraph.
SetListAlignment | Sets the alignment of bulleted or numbered text used for paragraphs.
SetListLevelIndex | Sets the list level index used for paragraphs.
SetListStart | Sets the starting number or Unicode value for a numbered list.
SetListTab | Sets the list tab setting.
SetListType | Sets the type of list to be used for paragraphs.
SetNoLineNumber | Controls whether the numbering of paragraphs in a range is suppressed.
SetPageBreakBefore | Controls whether there is a page break before each paragraph in a range.
SetRightIndent | Sets the right margin of a paragraph.
SetSpaceAfter | Sets the amount of space that follows a paragraph.
SetSpaceBefore | Sets the amount of space that precedes a paragraph.
SetStyle | Sets the paragraph style for the paragraphs in a range.
SetWidowControl | Controls the suppression of widows and orphans.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, Using TOM GUIDs


ITextPara::AddTab

The ITextPara::AddTab method adds a tab at the displacement tbPos, with type tbAlign, and leader style, tbLeader.

STDMETHODIMP ITextPara::AddTab(
  float tbPos,
  long tbAlign,
  long tbLeader
);

Parameters

tbPos
[in] New tab displacement, in floating-point points.
tbAlign
[in] Alignment options for the tab position. It can be one of the following.
Value | Meaning
tomAlignLeft | Text is left justified from the tab position. This is the default.
tomAlignCenter | Text is centered on the tab position.
tomAlignRight | Text is right justified from the tab position.
tomAlignDecimal | The decimal point is set at the tab position. This is useful for aligning a column of decimal numbers.
tomAlignBar | A vertical bar is positioned at the tab position. Text is not affected. Alignment bars on nearby lines at the same position form a continuous vertical line.

tbLeader
[in] Leader character style. A leader character is the character that is used to fill the space taken by a tab character. It can be one of the following.
Value | Meaning
tomSpaces | Spaces are used. This is the default.
tomDots | Dots are used.
tomDashes | A dashed line is used.
tomLines | A solid line is used.

Return Values

If AddTab succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.
CO_E_RELEASED | The paragraph format object is attached to a range that has been deleted.

Remarks

It is assumed that there is never a tab at position zero. If multiple paragraphs are described, the common subset of tabs will be returned with 0x8000 in the upper word of the tab type.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::ClearAllTabs, ITextPara::DeleteTab, ITextPara::GetListTab, ITextPara::GetTab, ITextPara::GetTabCount, ITextPara::SetListTab


ITextPara::CanChange

The ITextPara::CanChange property-get method determines whether the paragraph formatting can be changed.

STDMETHODIMP ITextPara::CanChange(
  long *pbCanChange
);

Parameters

pbCanChange
Pointer to a variable that receives tomTrue if the paragraph formatting can be changed or tomFalse if it cannot be changed. This parameter can be null.

Return Values

If paragraph formatting can change, CanChange succeeds and returns S_OK. If paragraph formatting cannot change, the method fails and returns S_FALSE. For more information about COM error codes, see Error Handling.

Remarks

The *pbCanChange parameter returns tomTrue only if the paragraph formatting can be changed (that is, if no part of an associated range is protected and an associated document is not read-only). If this ITextPara object is a duplicate, no protection rules apply.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara


ITextPara::ClearAllTabs

The ITextPara::ClearAllTabs method clears all tabs, reverting to equally spaced tabs with the default tab spacing.

STDMETHODIMP ITextPara::ClearAllTabs(void)

Parameters

This method has no parameters.

Return Values

If ClearAllTabs succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.
CO_E_RELEASED | The paragraph format object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextDocument::GetDefaultTabStop, ITextPara::AddTab, ITextPara::DeleteTab, ITextPara::GetListTab, ITextPara::GetTab, ITextPara::GetTabCount, ITextPara::SetListTab


ITextPara::DeleteTab

The ITextPara::DeleteTab method deletes a tab at a specified displacement.

STDMETHODIMP ITextPara::DeleteTab(
  float tbPos
);

Parameters

tbPos
Displacement, in floating-point points, at which a tab should be deleted.

Return Values

If DeleteTab succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_ACCESSDENIED | Write access is denied.
E_INVALIDARG | The tbPos value is less than or equal to zero.
E_OUTOFMEMORY | Insufficient memory.
CO_E_RELEASED | The paragraph format object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::AddTab, ITextPara::ClearAllTabs, ITextPara::GetListTab, ITextPara::GetTab, ITextPara::GetTabCount, ITextPara::SetListTab


ITextPara::GetAlignment

The ITextPara::GetAlignment property-get method retrieves the current paragraph alignment value.

STDMETHODIMP ITextPara::GetAlignment(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives the paragraph alignment, which can be one of the following values.
Value | Meaning
tomAlignLeft | Text aligns with the left margin.
tomAlignCenter | Text is centered between the margins.
tomAlignRight | Text aligns with the right margin.
tomAlignJustify | Text starts at the left margin and, if the line extends beyond the right margin, all the spaces in the line are adjusted to be even.

Return Values

If GetAlignment succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | The pValue parameter is null.
CO_E_RELEASED | The paragraph format object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::SetAlignment


ITextPara::GetDuplicate

The ITextPara::GetDuplicate property-get method creates a duplicate of the specified paragraph format object. The duplicate property is the default property of an ITextPara object.

STDMETHODIMP ITextPara::GetDuplicate(
  ITextPara **ppPara
);

Parameters

ppPara
Pointer to a variable that receives a pointer to a duplicate ITextPara object.

Return Values

If GetDuplicate succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_OUTOFMEMORY | Memory could not be allocated for the new object.
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::SetDuplicate


ITextPara::GetFirstLineIndent

The ITextPara::GetFirstLineIndent property-get method retrieves the amount used to indent the first line of a paragraph relative to the left indent. The left indent is the indent for all lines of the paragraph except the first line.

STDMETHODIMP ITextPara::GetFirstLineIndent(
  float *pValue
);

Parameters

pValue
Pointer to a variable that receives the first-line indentation amount in floating-point points.

Return Values

If GetFirstLineIndent succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Remarks

To set the first line indentation amount, call the ITextPara::SetIndents method.

To get and set the indent for all other lines of the paragraph (that is, the left indent), use ITextPara::GetLeftIndent and ITextPara::SetIndents.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::GetLeftIndent , ITextPara::SetIndents


ITextPara::GetHyphenation

The ITextPara::GetHyphenation property-get method determines whether automatic hyphenation is enabled for the range.

STDMETHODIMP ITextPara::GetHyphenation(
  long *pBool
);

Parameters

pBool
Pointer to a variable that receives one of the following values.
Value | Meaning
tomTrue | Automatic hyphenation is enabled.
tomFalse | Automatic hyphenation is disabled.
tomUndefined | The hyphenation property is undefined.

Return Values

If GetHyphenation succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Remarks

This property corresponds to the PFE_DONOTHYPHEN effect described in the PARAFORMAT2 structure.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::SetHyphenation, PARAFORMAT2


ITextPara::GetKeepTogether

The ITextPara::GetKeepTogether property-get method determines whether page breaks are allowed within paragraphs.

STDMETHODIMP ITextPara::GetKeepTogether(
  long *pBool
);

Parameters

pBool
Pointer to a variable that receives one of the following values.
Value | Meaning
tomTrue | Page breaks are not allowed within a paragraph.
tomFalse | Page breaks are allowed within a paragraph.
tomUndefined | The property is undefined.

Return Values

If GetKeepTogether succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Remarks

This property corresponds to the PFE_KEEP effect described in the PARAFORMAT2 structure.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::SetKeepTogether, PARAFORMAT2


ITextPara::GetKeepWithNext

The ITextPara::GetKeepWithNext property-get method determines whether page breaks are allowed between paragraphs in the range.

STDMETHODIMP ITextPara::GetKeepWithNext(
  long *pBool
);

Parameters

pBool
Pointer to a variable that receives one of the following values.
Value | Meaning
tomTrue | Page breaks are not allowed between paragraphs.
tomFalse | Page breaks are allowed between paragraphs.
tomUndefined | The property is undefined.

Return Values

If GetKeepWithNext succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Remarks

This property corresponds to the PFE_KEEPNEXT effect described in the PARAFORMAT2 structure.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::SetKeepWithNext, PARAFORMAT2


ITextPara::GetLeftIndent

The ITextPara::GetLeftIndent property-get method retrieves the distance used to indent all lines except the first line of a paragraph. The distance is relative to the left margin.

STDMETHODIMP ITextPara::GetLeftIndent(
  float *pValue
);

Parameters

pValue
Pointer to a variable that receives the left indentation, in floating-point points.

Return Values

If GetLeftIndent succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Remarks

To set the left indentation amount, call the ITextPara::SetIndents method.

To get the first-line indent, call ITextPara::GetFirstLineIndent.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::GetFirstLineIndent, ITextPara::SetIndents


ITextPara::GetLineSpacing

The ITextPara::GetLineSpacing property-get method retrieves the line-spacing value for the text range.

STDMETHODIMP ITextPara::GetLineSpacing(
  float *pValue
);

Parameters

pValue
Pointer to a variable that receives the line-spacing value. The following table shows how this value is interpreted for the different line-spacing rules.
Line spacing rule | Meaning
tomLineSpaceSingle | The line-spacing value is ignored.
tomLineSpace1pt5 | The line-spacing value is ignored.
tomLineSpaceDouble | The line-spacing value is ignored.
tomLineSpaceAtLeast | The line-spacing value specifies the spacing, in floating-point points, from one line to the next. However, if the value is less than single spacing, the control displays single-spaced text.
tomLineSpaceExactly | The line-spacing value specifies the exact spacing, in floating-point points, from one line to the next (even if the value is less than single spacing).
tomLineSpaceMultiple | The line-spacing value specifies the line spacing, in lines.

Return Values

If GetLineSpacing succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Remarks

To retrieve the line-spacing rule, call the ITextPara::GetLineSpacingRule method.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::GetLineSpacingRule, ITextPara::SetLineSpacing


ITextPara::GetLineSpacingRule

The ITextPara::GetLineSpacingRule property-get method retrieves the line-spacing rule for the text range.

STDMETHODIMP ITextPara::GetLineSpacingRule(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives one of the following values to indicate the line-spacing rule.
Line spacing rule | Meaning
tomLineSpaceSingle | Single space. The line-spacing value is ignored.
tomLineSpace1pt5 | One-and-a-half-line-spacing. The line-spacing value is ignored.
tomLineSpaceDouble | Double line spacing. The line-spacing value is ignored.
tomLineSpaceAtLeast | The line-spacing value specifies the spacing from one line to the next. However, if the value is less than single spacing, text is single-spaced.
tomLineSpaceExactly | The line-spacing value specifies the exact spacing from one line to the next (even if the value is less than single spacing).
tomLineSpaceMultiple | The line-spacing value specifies the line spacing, in lines.

Return Values

If GetLineSpacingRule succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::GetLineSpacing, ITextPara::SetLineSpacing


ITextPara::GetListAlignment

The ITextPara::GetListAlignment property-get method retrieves the kind of alignment to use for bulleted and numbered lists.

STDMETHODIMP ITextPara::GetListAlignment(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives one of the following values to indicate the kind of bullet and numbering alignment.
Value | Meaning
tomAlignLeft | Text is left aligned.
tomAlignCenter | Text is centered in the line.
tomAlignRight | Text is right aligned.

Return Values

If GetListAlignment succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Remarks

For a description of the different types of lists, see the ITextPara::GetListType method.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::GetListType, ITextPara::SetListAlignment


ITextPara::GetListLevelIndex

The ITextPara::GetListLevelIndex property-get method retrieves the list level index used with paragraphs.

STDMETHODIMP ITextPara::GetListLevelIndex(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives the list level index. The value of *pValue can be one of the following.
Value | Meaning
0 | No list.
1 | First-level (outermost) list.
2 | Second-level (nested) list. This is nested under a level 1 list item.
3 | Third-level (nested) list. This is nested under a level 2 list item.
and so forth | Nesting continues similarly.

Up to three levels are common in HTML documents.

Return Values

If GetListLevelIndex succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::SetListLevelIndex


ITextPara::GetListStart

The ITextPara::GetListStart property-get method retrieves the starting value or code of a list numbering sequence.

STDMETHODIMP ITextPara::GetListStart(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives the starting value or code of a list numbering sequence. For the possible values, see the ITextPara::GetListType method.

Return Values

If GetListStart succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Remarks

For a discussion on which sequence to use, see the ITextPara::GetListType method.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::GetListType, ITextPara::SetListStart, ITextPara::SetListType


ITextPara::GetListTab

The ITextPara::GetListTab property-get method retrieves the list tab setting, which is the distance between the first-line indent and the text on the first line. The numbered or bulleted text is left-justified, centered, or right-justified at the first-line indent value.

STDMETHODIMP ITextPara::GetListTab(
  float *pValue
);

Parameters

pValue
Pointer to a variable that receives the list tab setting. The list tab value is in floating-point points.

Return Values

If GetListTab succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Remarks

To determine whether the numbered or bulleted text is left-justified, centered, or right-justified, call ITextPara::GetListAlignment.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::AddTab, ITextPara::ClearAllTabs, ITextPara::DeleteTab, ITextPara::GetFirstLineIndent, ITextPara::GetListAlignment, ITextPara::GetTab, ITextPara::GetTabCount, ITextPara::SetListTab


ITextPara::GetListType

The ITextPara::GetListType property-get method retrieves the kind of numbering to use with paragraphs.

STDMETHODIMP ITextPara::GetListType(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives one of the following values to indicate the kind of list numbering.
List type | Value | Meaning
tomListNone | 0 | Not a list paragraph.
tomListBullet | 1 | List uses bullets (0x2022).
tomListNumberAsArabic | 2 | List is numbered with Arabic numerals. (0, 1, 2, …).
tomListNumberAsLCLetter | 3 | List is ordered with lowercase letters (a, b, c, …).
tomListNumberAsUCLetter | 4 | List is ordered with uppercase Arabic letters (A, B, C, …).
tomListNumberAsLCRoman | 5 | List is ordered with lowercase Roman letters (i, ii, iii, …).
tomListNumberAsUCRoman | 6 | List is ordered with uppercase Roman letters (I, II, III, …).
tomListNumberAsSequence | 7 | The value returned by ITextPara::GetListStart is treated as the first code in a Unicode sequence.

By default, numbers are followed by a right parenthesis, for example: 1). However, the pValue value can include one of the following flags to indicate a different formatting.
List type | Value | Meaning
tomListParentheses | 0x10000 | Encloses the number in parentheses, as in: (1).
tomListPeriod | 0x20000 | Follows the number with a period.
tomListPlain | 0x30000 | Uses the number alone.

Return Values

If GetListType succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Remarks

Values above 32 correspond to Unicode values for bullets.

The following Microsoft® Visual Basic for Applications example numbers the paragraphs in a range, r, starting with the number 2 and following the numbers with a period.

    r.Para.ListStart = 2
    r.Para.ListType = tomListNumberAsArabic + tomListPeriod

For an example of tomListNumberAsSequence, set ListStart = 0x2780, which gives you circled numbers. The Unicode Standard has examples of many more numbering sequences.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::GetListStart, ITextPara::SetListStart, ITextPara::SetListType


ITextPara::GetNoLineNumber

The ITextPara::GetNoLineNumber property-get method determines whether paragraph numbering is enabled.

STDMETHODIMP ITextPara::GetNoLineNumber(
  long *pBool
);

Parameters

pBool
Pointer to a variable that receives one of the following values.
Value | Meaning
tomTrue | Line numbering is disabled.
tomFalse | Line numbering is enabled.
tomUndefined | The property is undefined.

Return Values

If GetNoLineNumber succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Remarks

Paragraph numbering is when the paragraphs of a range are numbered. The number appears on the first line of a paragraph.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::SetNoLineNumber


ITextPara::GetPageBreakBefore

The ITextPara::GetPageBreakBefore property-get method determines whether each paragraph in the range must begin on a new page.

STDMETHODIMP ITextPara::GetPageBreakBefore(
  long *pBool
);

Parameters

pBool
Pointer to a variable that receives one of the following values.
Value | Meaning
tomTrue | Each paragraph in this range must begin on a new page.
tomFalse | The paragraphs in this range do not need to begin on a new page.
tomUndefined | The property is undefined.

Return Values

If GetPageBreakBefore succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::SetPageBreakBefore


ITextPara::GetRightIndent

The ITextPara::GetRightIndent property-get method retrieves the size of the right margin indent of a paragraph.

STDMETHODIMP ITextPara::GetRightIndent(
  float *pValue
);

Parameters

pValue
Pointer to a variable that receives the right indentation, in floating-point points.

Return Values

If GetRightIndent succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::SetRightIndent


ITextPara::GetSpaceAfter

The ITextPara::GetSpaceAfter property-get method retrieves the amount of vertical space below a paragraph.

STDMETHODIMP ITextPara::GetSpaceAfter(
  float *pValue
);

Parameters

pValue
Pointer to a variable that receives the space-after value, in floating-point points.

Return Values

If GetSpaceAfter succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::GetSpaceBefore, ITextPara::SetSpaceAfter, ITextPara::SetSpaceBefore


ITextPara::GetSpaceBefore

The ITextPara::GetSpaceBefore property-get method retrieves the amount of vertical space above a paragraph.

STDMETHODIMP ITextPara::GetSpaceBefore(
  float *pValue
);

Parameters

pValue
Pointer to a variable that receives the space-before value, in floating-point points.

Return Values

If GetSpaceBefore succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::GetSpaceAfter, ITextPara::SetSpaceAfter, ITextPara::SetSpaceBefore


ITextPara::GetStyle

The ITextPara::GetStyle property-get method retrieves the style handle for the paragraphs in the specified range.

STDMETHODIMP ITextPara::GetStyle(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives the paragraph style handle. For more information, see the Remarks.

Return Values

If GetStyle succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Remarks

The Text Object Model (TOM) version 1.0 has no way to specify the meanings of user-defined style handles. They depend on other facilities of the text system implementing TOM. Negative style handles are reserved for built-in character and paragraph styles. Currently defined values are listed in the following table. For a description of the following styles, see the Microsoft Word documentation.

Style | Value | Style | Value
StyleNormal | –1 | StyleTableofAuthorities | –45
StyleHeading1 | –2 | StyleMacroText | –46
StyleHeading2 | –3 | StyleTOAHeading | –47
StyleHeading3 | –4 | StyleList | –48
StyleHeading4 | –5 | StyleListBullet | –49
StyleHeading5 | –6 | StyleListNumber | –50
StyleHeading6 | –7 | StyleList2 | –51
StyleHeading7 | –8 | StyleList3 | –52
StyleHeading8 | –9 | StyleList4 | –53
StyleHeading9 | –10 | StyleList5 | –54
StyleIndex1 | –11 | StyleListBullet2 | –55
StyleIndex2 | –12 | StyleListBullet3 | –56
StyleIndex3 | –13 | StyleListBullet4 | –57
StyleIndex4 | –14 | StyleListBullet5 | –58
StyleIndex5 | –15 | StyleListNumber2 | –59
StyleIndex6 | –16 | StyleListNumber3 | –60
StyleIndex7 | –17 | StyleListNumber4 | –61
StyleIndex8 | –18 | StyleListNumber5 | –62
StyleIndex9 | –19 | StyleTitle | –63
StyleTOC1 | –20 | StyleClosing | –64
StyleTOC2 | –21 | StyleSignature | –65
StyleTOC3 | –22 | StyleDefaultParagraphFont | –66
StyleTOC4 | –23 | StyleBodyText | –67
StyleTOC5 | –24 | StyleBodyTextIndent | –68
StyleTOC6 | –25 | StyleListContinue | –69
StyleTOC7 | –26 | StyleListContinue2 | –70
StyleTOC8 | –27 | StyleListContinue3 | –71
StyleTOC9 | –28 | StyleListContinue4 | –72
StyleNormalIndent | –29 | StyleListContinue5 | –73
StyleFootnoteText | –30 | StyleMessageHeader | –74
StyleAnnotationText | –31 | StyleSubtitle | –75
StyleHeader | –32 | StyleSalutation | –76
StyleFooter | –33 | StyleDate | –77
StyleIndexHeading | –34 | StyleBodyTextFirstIndent | –78
StyleCaption | –35 | StyleBodyTextFirstIndent2 | –79
StyleTableofFigures | –36 | StyleNoteHeading | –80
StyleEnvelopeAddress | –37 | StyleBodyText2 | –81
StyleEnvelopeReturn | –38 | StyleBodyText3 | –82
StyleFootnoteReference | –39 | StyleBodyTextIndent2 | –83
StyleAnnotationReference | –40 | StyleBodyTextIndent3 | –84
StyleLineNumber | –41 | StyleBlockQuotation | –85
StylePageNumber | –42 | StyleHyperlink | –86
StyleEndnoteReference | –43 | StyleHyperlinkFollowed | –87
StyleEndnoteText | –44 |  |

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::SetStyle


ITextPara::GetTab

The ITextPara::GetTab method retrieves tab parameters (displacement, alignment, and leader style) for a specified tab.

STDMETHODIMP ITextPara::GetTab(
  long iTab,
  float *ptbPos,
  long *ptbAlign,
  long *ptbLeader
);

Parameters

iTab
Index of tab for which to retrieve info. It can be either a numerical index or a special value (see the following table). Since tab indexes are zero-based, iTab = zero gets the first tab defined, iTab = 1 gets the second tab defined, and so forth.

The following table summarizes all of the possible values of iTab.
iTab | Value | Meaning
tomTabBack | –3 | Get tab previous to *ptbPos.
tomTabNext | –2 | Get tab following *ptbPos.
tomTabHere | –1 | Get tab at *ptbPos.
≥ 0 | Get tab with index of iTab (and ignore ptbPos).

ptbPos
Pointer to a variable that receives the tab displacement, in floating-point points. The value of *ptbPos is zero if the tab does not exist and the value of *ptbPos is tomUndefined if there are multiple values in the associated range .
ptbAlign
Pointer to a variable that receives the tab alignment. For more information, see ITextPara::AddTab.
ptbLeader
Pointer to a variable that receives the tab leader-character style. For more information, see ITextPara::AddTab.

Return Values

If GetTab succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.
S_FALSE | There is no tab corresponding to iTab.

Remarks

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::AddTab, ITextPara::ClearAllTabs, ITextPara::DeleteTab, ITextPara::GetListTab, ITextPara::GetTabCount, ITextPara::SetListTab


ITextPara::GetTabCount

The ITextPara::GetTabCount property-get method retrieves the tab count.

STDMETHODIMP ITextPara::GetTabCount(
  long *pc
);

Parameters

pc
Pointer to a variable that receives the tab count.

Return Values

If GetTabCount succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Remarks

The tab count of a new instance can be nonzero, depending on the underlying text engine. For example, Microsoft Word stories begin with no explicit tabs defined, while rich edit instances start with a single explicit tab. To be sure there are no explicit tabs (that is, to set the tab count to zero), call ITextPara::ClearAllTabs.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::AddTab, ITextPara::ClearAllTabs, ITextPara::DeleteTab, ITextPara::GetListTab, ITextPara::GetTab, ITextPara::SetListTab


ITextPara::GetWidowControl

The ITextPara::GetWidowControl property-get method retrieves the tomBool value that determines whether to control widows and orphans for the paragraphs in a range.

STDMETHODIMP ITextPara::GetWidowControl(
  long *pBool
);

Parameters

pBool
Pointer to a variable that receives the value that determines how widows and orphans are controlled. The *pBool value can be one of the following.
Value | Meaning
tomTrue | Prevents the printing of a widow or orphan
tomFalse | Allows the printing of a widow or orphan.
tomUndefined | The widow-control property is undefined.

Return Values

If GetWidowControl succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Remarks

A widow is created when the last line of a paragraph is printed by itself at the top of a page. An orphan is when the first line of a paragraph is printed by itself at the bottom of a page.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::SetWidowControl


ITextPara::IsEqual

The ITextPara::IsEqual method determines if the current range has the same properties as a specified range.

STDMETHODIMP ITextPara::IsEqual(
  ITextPara *pPara,
  long *pB
);

Parameters

pPara
Pointer to the ITextPara range that is compared to the current range.
pB
Pointer to a variable that receives the comparison result. The value can be null.

Return Values

If the objects are equal, IsEqual succeeds and returns S_OK. If the objects are not equal, the method fails and returns S_FALSE. For more information about COM error codes, see Error Handling.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara


ITextPara::Reset

The ITextPara::Reset method resets the paragraph formatting to a choice of default values.

STDMETHODIMP ITextPara::Reset(
  long Value
);

Parameters

Value
[in] Type of reset. It can be one of the following.
Value | Usage
tomDefault | Used for paragraph formatting that is defined by the RTF \pard (that is, the paragraph default) control word.
tomUndefined | Used for all undefined values. The tomUndefined value is only valid for duplicate (clone) ITextPara objects.

Return Values

If Reset succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara


ITextPara::SetAlignment

The ITextPara::SetAlignment property-put method sets the paragraph alignment.

STDMETHODIMP ITextPara::SetAlignment(
  long Value
);

Parameters

Value
[in] New paragraph alignment. For a list of possible values, see the ITextPara::GetAlignment method.

Return Values

If SetAlignment succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::GetAlignment


ITextPara::SetDuplicate

The ITextPara::SetDuplicate property-put method sets the formatting for an existing paragraph by copying a given format.

STDMETHODIMP ITextPara::SetDuplicate(
  ITextPara *pPara
);

Parameters

pPara
[in] Pointer to an ITextPara range that contains the new paragraph formatting.

Return Values

If SetDuplicate succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Remarks

The tomUndefined values have no effect, that is, they will not change the target values.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara


ITextPara::SetHyphenation

The ITextPara::SetHyphenation property-put method controls hyphenation for the paragraphs in the range.

STDMETHODIMP ITextPara::SetHyphenation(
  long Value
);

Parameters

Value
[in] Indicates how hyphenation is controlled. It can be one of the following.
Value | Meaning
tomTrue | Automatic hyphenation is enabled.
tomFalse | Automatic hyphenation is disabled.
tomUndefined | The hyphenation property is undefined.

Return Values

If SetHyphenation succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::GetHyphenation


ITextPara::SetIndents

The ITextPara::SetIndents method sets the first-line indent, the left indent, and the right indent for a paragraph.

STDMETHODIMP ITextPara::SetIndents(
  float First,
  float Left,
  float Right
);

Parameters

First
[in] Indent of the first line in a paragraph, relative to the left indent. The value is in floating-point points and can be positive or negative.
Left
[in] Left indent of all lines except the first line in a paragraph, relative to left margin. The value is in floating-point points and can be positive or negative.
Right
[in] Right indent of all lines in paragraph, relative to the right margin. The value is in floating-point points and can be positive or negative. This value is optional.

Return Values

If SetIndent succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Remarks

Line indents are not allowed to position text in the margins. If the first-line indent is set to a negative value (for an outdented paragraph) while the left indent is zero, the first-line indent is reset to zero. To avoid this problem while retaining property sets, set the first-line indent value equal to zero either explicitly or by calling the ITextPara::Reset method. Then, call SetIndents to set a nonnegative, left-indent value and set the desired first-line indent.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::Reset


ITextPara::SetKeepTogether

The ITextPara::SetKeepTogether property-put method controls whether page breaks are allowed within a paragraph in a range.

STDMETHODIMP ITextPara::SetKeepTogether(
  long Value
);

Parameters

Value
[in] Indicates whether page breaks are allowed within a paragraph in a range. It can be one of the following.
Value | Meaning
tomTrue | Page breaks are not allowed within a paragraph.
tomFalse | Page breaks are allowed within a paragraph.
tomUndefined | The property is undefined.

Return Values

If SetKeepTogether succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Remarks

This property corresponds to the PFE_KEEP effect described in the PARAFORMAT2 structure.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, PARAFORMAT2


ITextPara::SetKeepWithNext

The ITextPara::SetKeepWithNext property-put method controls whether page breaks are allowed between the paragraphs in a range.

STDMETHODIMP ITextPara::SetKeepWithNext(
  long Value
);

Parameters

Value
[in] Indicates if page breaks can be used between the paragraphs of a range. It can be one of the following.
Value | Meaning
tomTrue | Page breaks are not allowed between paragraphs.
tomFalse | Page breaks are allowed between paragraphs.
tomUndefined | The property is undefined.

Return Values

If SetKeepWithNext succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Remarks

This property corresponds to the PFE_KEEPNEXT effect described in the PARAFORMAT2 structure.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, PARAFORMAT2


ITextPara::SetLineSpacing

The ITextPara::SetLineSpacing method sets the paragraph line-spacing rule and the line spacing for a paragraph.

STDMETHODIMP ITextPara::SetLineSpacing(
  long Rule,
  float Spacing
);

Parameters

Rule
[in] Value of new line-spacing rule. For a list of possible rule values and further discussion, see the ITextPara::GetLineSpacingRule method.
Spacing
[in] Value of new line spacing. If the line-spacing rule treats the Spacing value as a linear dimension, then Spacing is given in floating-point points.

Return Values

If SetLineSpacing succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Remarks

The line-spacing rule and line spacing work together, and as a result, they must be set together, much as the first and left indents need to be set together.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::GetLineSpacingRule


ITextPara::SetListAlignment

The ITextPara::SetListAlignment property-put method sets the alignment of bulleted or numbered text used for paragraphs.

STDMETHODIMP ITextPara::SetListAlignment(
  long Value
);

Parameters

Value
[in] New list alignment value. For possible values, see ITextPara::GetListAlignment.

Return Values

If SetListAlignment succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::GetListAlignment


ITextPara::SetListLevelIndex

The ITextPara::SetListLevelIndex property-put method sets the list level index used for paragraphs.

STDMETHODIMP ITextPara::SetListLevelIndex(
  long Value
);

Parameters

Value
[in] New list level index value. For possible values, see ITextPara::GetListLevelIndex.

Return Values

If SetListLevelIndex succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Remarks

Setting the list level index does not automatically change a list's indentation and other paragraph properties.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::GetListLevelIndex


ITextPara::SetListStart

The ITextPara::SetListStart property-put method sets the starting number or Unicode value for a numbered list.

STDMETHODIMP ITextPara::SetListStart(
  long Value
);

Parameters

Value
[in] New starting number or Unicode value for a numbered list.

Return Values

If SetListStart succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Remarks

Other characteristics of a list are specified by ITextPara::SetListType.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::SetListType


ITextPara::SetListTab

The ITextPara::SetListTab property-put method sets the list tab setting, which is the distance between the first indent and the start of the text on the first line.

STDMETHODIMP ITextPara::SetListTab(
  float Value
);

Parameters

Value
[in] New list tab value, in floating-point points.

Return Values

If SetListTab succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::AddTab, ITextPara::ClearAllTabs, ITextPara::DeleteTab, ITextPara::GetListTab, ITextPara::GetTab, ITextPara::GetTabCount


ITextPara::SetListType

The ITextPara::SetListType property-put method sets the type of list to be used for paragraphs.

STDMETHODIMP ITextPara::SetListType(
  long Value
);

Parameters

Value
[in] New list type. For possible list types, see the ITextPara::GetListType method.

Return Values

If SetListType succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::GetListType


ITextPara::SetNoLineNumber

The ITextPara::SetNoLineNumber property-put method determines whether to suppress line numbering of paragraphs in a range.

STDMETHODIMP ITextPara::SetNoLineNumber(
  long Value
);

Parameters

Value
[in] Indicates if line numbering is suppressed. It can be one of the following.
Value | Meaning
tomTrue | Line numbering is disabled.
tomFalse | Line numbering is enabled.
tomUndefined | The property is undefined.

Return Values

If SetNoLineNumber succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Remarks

This property concerns the numbering of paragraphs in a range. If Value is tomFalse, the number of the paragraph appears on the first line of the paragraph.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara


ITextPara::SetPageBreakBefore

The ITextPara::SetPageBreakBefore property-put method controls whether there is a page break before each paragraph in a range.

STDMETHODIMP ITextPara::SetPageBreakBefore(
  long Bool
);

Parameters

Bool
[in] tomBool value that controls page ejection before paragraphs. It can be one of the following.
Value | Meaning
tomTrue | The paragraphs in this range must begin on a new page.
tomFalse | The paragraphs in this range do not need to begin on a new page.
tomUndefined | The property is undefined.

Return Values

If SetPageBreakBefore succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara


ITextPara::SetRightIndent

The ITextPara::SetRightIndent property-put method sets the right margin of paragraph.

STDMETHODIMP ITextPara::SetRightIndent(
  float Value
);

Parameters

Value
[in] Right indent, in floating-point points.

Return Values

If SetRightIndent succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara


ITextPara::SetSpaceAfter

The ITextPara::SetSpaceAfter property-put method sets the amount of space that follows a paragraph.

STDMETHODIMP ITextPara::SetSpaceAfter(
  float Value
);

Parameters

Value
[in] New space-after value, in floating-point points.

Return Values

If SetSpaceAfter succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara


ITextPara::SetSpaceBefore

The ITextPara::SetSpaceBefore property-put method sets the amount of space preceding a paragraph.

STDMETHODIMP ITextPara::SetSpaceBefore(
  float Value
);

Parameters

Value
[in] New space-before value, in floating-point points.

Return Values

If SetSpaceBefore succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara


ITextPara::SetStyle

The ITextPara::SetStyle property-put method sets the paragraph style for the paragraphs in a range.

STDMETHODIMP ITextPara::SetStyle(
  long Value
);

Parameters

Value
[in] New paragraph style handle. For a list of styles, see the Remarks section of ITextPara::GetStyle.

Return Values

If SetStyle succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextPara::GetStyle


ITextPara::SetWidowControl

The ITextPara::SetWidowControl property-put method controls the suppression of widows and orphans.

STDMETHODIMP ITextPara::SetWidowControl(
  long Bool
);

Parameters

Bool
[in] A tomBool value that controls the suppression of widows and orphans. It can be one of the following.
Value | Meaning
tomTrue | Prevents printing of widows and orphans.
tomFalse | Allows printing of widows and orphans.
tomToggle | The value is toggled.
tomUndefined | No change.

Return Values

If SetWidowControl succeeds, it returns S_OK. If the method fails, it returns one of the following COM error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid argument.
E_ACCESSDENIED | Write access is denied.
E_OUTOFMEMORY | Insufficient memory.
CO_E_RELEASED | The paragraph formatting object is attached to a range that has been deleted.

Remarks

A widow is created when the last line of a paragraph is printed by itself at the top of a page. An orphan is when the first line of a paragraph is printed by itself at the bottom of a page.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara


ITextRange

The ITextRange objects are powerful editing and data-binding tools that allow a program to select text in a story and then examine or change that text. Multiple text ranges can be active and work cooperatively on the same story and evolve with the story. For example, if one text range deletes specified text before another text range, the latter tracks the change. In this sense, text ranges are similar to Microsoft® Word bookmarks, which also track editing changes. However, bookmarks cannot edit text, while text ranges can. In addition, ranges let you manipulate text without changing the selection or Clipboard, both of which are valuable to end users. The ITextSelection interface inherits from ITextRange and adds some UI-oriented methods and properties as described in the section on ITextSelection.

You can look at a text range using methods based on character positions. Specifically, a text range is characterized by:

  • The first character position, cpFirst, which points at an insertion point immediately preceding the first character (relative to the beginning of the story) in the range.
  • The limit position, cpLim, which points at an insertion point immediately following the last character in the range.

The first character in a story has cpFirst = zero. If a cp argument has a value greater than the number of characters in the story, the number of characters in the story is used instead. If a cp argument is negative, zero is used instead. For those familiar with Microsoft Visual Basic for Applications, call the cpFirst property Start and the cpLim property End (even though the starting position of a range is also an end).

In the following figure, character positions are represented by the lines separating the letters. The corresponding character position values are given beneath the lines. The range starting at cpFirst = 5 and ending at cpLim = 7 contains the two-letter word is. If this figure depicts the complete text in a story, the story length is 30.

The length of a range is given by cpLim - cpFirst or equivalently by End - Start. A range with zero length is called a degenerate or empty range and has equal cp* values, that is, cpFirst = cpLim. An example of a degenerate range is the current insertion point. A non-null selection is an example of a nondegenerate range.

Suppose that the range from 5 to 7 indicated by shaded cells in the preceding figure is told to delete its text (see ITextRange::Delete), thereby turning itself into an insertion point. The range from 25 to 29 would automatically track its contents, namely the word text. We would end up with the new figure

in which the range for text now has been automatically adjusted to have cpFirst = 23 and cpLim = 27. The owner of the range does not have to worry about updating the range character position values in the face of editing.

The names of the move methods indicate which end to move, but note that if any method attempts to move one range end past the other, both ends get moved to the target position. As a result, the insertion point is at the target position. The concept is that cpFirst and cpLim always have to obey the fundamental condition

0 ≤ cpFirst ≤ cpLim ≤ # characters in story

or equivalently for a range r, 0 ≤ r.Start ≤ r.End ≤ r.StoryLength, which is what you would expect from the names of these quantities.

Another important feature is that all stories contain an undeletable final CR (0xD) character at the end. So even an empty story has a single character, namely the final CR. A range can select this character, but cannot become an insertion point beyond it. To see how this works, try selecting the final CR in a Microsoft Word document and then press the right-arrow key to collapse it. The directory tree will collapse before the final CR, but the CR cannot be deleted. The TOM functions the same way. So, if r.Start = r.End, then r.End ≤ r.StoryLength – 1. For a discussion about deleting a CR, see ITextRange::Delete.

Some methods depend on a Unit argument, which can take on the predefined values listed in the following table.

Unit | Value | Meaning
tomCharacter | 1 | Character.
tomWord | 2 | Word.
tomSentence | 3 | Sentence.
tomParagraph | 4 | Paragraph.
tomLine | 5 | Line (on display).
tomStory | 6 | Story.
tomScreen | 7 | Screen (as for PAGE UP/PAGE DOWN).
tomSection | 8 | Section.
tomColumn | 9 | Table column.
tomRow | 10 | Table row.
tomWindow | 11 | Upper-left or lower-right of the window.
tomCell | 12 | Table cell.
tomCharFormat | 13 | Run of constant character formatting.
tomParaFormat | 14 | Run of constant paragraph formatting.
tomTable | 15 | Table.
tomObject | 16 | Embedded object.

Most of the Unit values are self-explanatory. However the following descriptions are provided for additional clarity.

tomWord
The tomWord constant is an end of paragraph or a span of alphanumerics or punctuation including any blanks that follow. To get an on-screen feel for tomWord, watch how the caret moves when you press CTRL+RIGHT ARROW (—>) or CTRL+LEFT ARROW (<—) in a Microsoft Word document.
tomSentence
The tomSentence constant describes a string of text that ends with a period, question mark, or exclamation mark and is followed either by one or more ASCII white space characters (9 through 0xd and 0x20), or the Unicode paragraph separator (0x2029). The trailing white space is part of the sentence. The last sentence in a story does not need to have a period, question mark, or exclamation mark. The start of a story qualifies as the start of a tomSentence, even if the string there does not qualify as a sentence grammatically. Other sentences must follow a sentence end and cannot begin with a period, question mark, or exclamation mark.
tomParagraph
The tomParagraph constant is a string of text terminated by an end-of-paragraph mark (CRLF, CR, VT (for SHIFT+ENTER), LF, FF, or 0x2029). TOM engines always have an undeletable end-of-paragraph mark at the end of a story. Thus, all TOM stories automatically have at least one tomWord, one tomSentence, and one tomParagraph.
tomLine
The tomLine constant corresponds to one line of text on a display, provided that a display is associated with the range. If no display is associated with a range, tomLine is treated as tomParagraph. A selection automatically has a display and a range that is a duplicate (see ITextRange::GetDuplicate). Other ranges may not have a display, depending on the TOM engine and context.

Methods that move one or both ends in terms of Unit, such as ITextRange::Move, ITextRange::MoveEnd, and ITextRange::MoveStart, depend on the signed Count argument. Except for the ITextSelection geometrical movement commands, if Count is greater than zero, the ends to be moved are moved forward (towards the end of the story), and if Count is less than zero, the ends are moved backward (towards the beginning). The default value of Count for these Move methods is 1. These methods attempt to move Count Units, but movement is never beyond the ends of the story.

Methods that move one or both ends by matching character strings or string patterns, such as ITextRange::MoveWhile, ITextRange::MoveEndWhile, and ITextRange::MoveStartWhile, can move up to a maximum number of characters given by the signed Count argument. If Count is greater than zero, the ends to be moved are moved forward, and if Count is less than zero, the ends are moved backward. Two special Count values, tomForward and tomBackward, are defined. These values are guaranteed to reach the end and the start of the story, respectively. The default value of Count is tomForward.

In Move* methods that turn a nondegenerate range into a degenerate one, such as Move, MoveWhile, and MoveUntil, cpFirst is changed if Count is negative and cpLim is changed if Count is positive. After this movement, the other end of the range is also moved to the new location. See the individual methods for more specific Count information. For nondegenerate ranges, the methods MoveStart, MoveEnd, MoveStartWhile, MoveEndWhile, MoveStartUntil and MoveEndUntil move either the starting position (Start) or the ending position (End).

To select a unit that corresponds to a contiguous range, such as a tomWord, tomSentence, and tomParagraph, use the MoveEnd method. To select a unit that corresponds to a noncontiguous range, such as tomObject, use the ITextRange::EndOf method, since the next object may occur after substantial intermediate text, if at all. To select a tomCell unit, the range must be inside a table.

Examples and further explanation of the Count and Unit arguments follow. Note that TOM engines may not support all of the units in the table above. For example, rich edit controls do not offer the concepts of sections, but rather return E_NOTIMPL when given tomSection. However if a TOM engine does support a unit, it has the index value given in the table.

When to Implement

Applications typically do not implement the ITextRange interface. Microsoft text solutions, such as rich edit controls, implement ITextRange as part of their Text Object Model (TOM) implementation.

When to Use

Applications can retrieve an ITextRange pointer by calling the ITextDocument::Range method.

Methods in Vtable Order

IUnknown Methods

QueryInterface
AddRef
Release

IDispatch Methods

GetTypeInfoCount
GetTypeInfo
GetIDsOfNames
Invoke

ITextRange Methods

Method | Description
CanEdit | Determines whether the range can be edited.
CanPaste | Determines whether a data object can be pasted into the range using a specified clipboard format.
ChangeCase | Changes the case of letters in the range, as specified by a parameter.
Collapse | Collapses the range into a degenerate point.
Copy | Copies the text to a data object or the Clipboard.
Cut | Cuts the text from a data object or the Clipboard.
Delete | Provides support for the DELETE and BACKSPACE keys.
EndOf | Moves the end of the range to the end of the last overlapping unit at the end of the range.
Expand | Expands the range to include any partial units.
FindText | Searches forward from the beginning of the range or backward from the end of the range for a specified string.
FindTextEnd | Searches backward from the end of the range for a string using specified criteria.
FindTextStart | Searches forward from the start of the range for a string using specified criteria.
GetChar | Retrieves the first character of the range.
GetDuplicate | Retrieves a duplicate of the range object.
GetEmbeddedObject | Retrieves a pointer to the embedded object at the start of the range.
GetEnd | Retrieves the character position of the end of the range.
GetFont | Retrieves an ITextFont object with the character attributes of the range.
GetFormattedText | Retrieves an ITextRange object with the range's formatted text.
GetIndex | Retrieves the story index of the unit at the start of the range.
GetPara | Retrieves an ITextPara object with the paragraph attributes of the range.
GetPoint | Retrieves the screen coordinates of a specified point in the range.
GetStart | Retrieves the character position of the start of the range.
GetStoryLength | Retrieves the count of characters in this range's story.
GetStoryType | Retrieves the type of this range's story.
GetText | Retrieves the plain text in the range.
InRange | Determines whether this range is within or at the same text as a specified range.
InStory | Determines whether the story of this range is the same as the story of a specified range.
IsEqual | Determines whether this range has the same character positions and story as those of a specified range.
Move | Collapses the range to an insertion point and moves the insertion point forward or backward a specified number of units.
MoveEnd | Moves the end of the range.
MoveEndUntil | Moves the end of the range to the character position of the first character that matches a set of characters. If no characters in the set are found, the range is unchanged.
MoveEndWhile | Moves the end of the range to the character position of the first character past a contiguous range of characters that match a set of characters.
MoveStart | Moves the start of the range.
MoveStartUntil | Moves the start of the range to the character position of the first character that matches a set of characters. If no characters in the set are found, the range is unchanged.
MoveStartWhile | Moves the start of the range either a specified number of characters or to the character position of the first character past a contiguous range of characters that match a set of characters, whichever comes first.
MoveUntil | Moves the insertion point to the first character found from a set of characters. If no characters in the set are found, the range is unchanged.
MoveWhile | Moves the insertion point as long as characters match a set of characters, up to a specified maximum number. If no characters in the set are found, the range is unchanged.
Paste | Pastes the text from a data object or the Clipboard.
ScrollIntoView | Scrolls the range into view.
Select | Sets the start, end, and story values of the active selection to those of this range.
SetChar | Sets the first character of the range.
SetEnd | Sets the character position of the end of the range.
SetFont | Sets the range's character attributes to those given by a specified ITextFont object.
SetFormattedText | Replaces this range's text with formatted text of a specified range.
SetIndex | Sets the unit index of the range.
SetPara | Sets this range's paragraph attributes to those of a specified ITextPara object.
SetPoint | Selects text at or up to a specified point.
SetRange | Sets the start and end character positions of the range.
SetStart | Sets the character position of the start of the range.
SetText | Replaces the text in the range with a specified string.
StartOf | Moves the range end to the start of the first overlapping unit in the range.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, Using TOM GUIDs


ITextRange::CanEdit

The ITextRange::CanEdit method determines if the specified range can be edited.

STDMETHODIMP ITextRange::CanEdit(
  long *pbCanEdit
);

Parameters

pbCanEdit
Pointer to a variable that receives a tomBool value indicating whether the range can be edited. The pointer can be null. The value of the variable *pbCanEdit is tomTrue if and only if the specified range can be edited.

Return Values

If the range can be edited, CanEdit succeeds and returns S_OK. If the range cannot be edited, the method fails and returns S_FALSE. For more information about COM error codes, see Error Handling.

Remarks

The range cannot be edited if any part of it is protected or if the document is read-only.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange


ITextRange::CanPaste

The ITextRange::CanPaste method determines if a data object can be pasted, using a specified format, into the current range.

STDMETHODIMP ITextRange::CanPaste(
  VARIANT *pVar,
  long Format,
  long *pb
);

Parameters

pVar
Pointer to an IDataObject to be pasted. However, the Clipboard contents are checked for pasting if any of the following are true:
  • pVar is null
  • pVar->punkVal is null
  • pVar->vt is not VT_UNKNOWN
  • pVar->punkVal does not return an IDataObject object when queried for one
Format
Clipboard format that is used. Zero represents the best format, which usually is RTF, but CF_UNICODETEXT and other formats are also possible. The default value is zero.
pb
Pointer to a variable that receives the Boolean value. The value can be null. The value of the variable *pb is tomTrue if and only if the data object identified by pVar can be pasted, using the specified format, into the range.

Return Values

The CanPaste method returns the following COM error codes. For more information on COM error codes, see Error Handling.

Value | Meaning
S_OK | The clipboard contents or IDataObject can be pasted.
S_FALSE | The clipboard contents or IDataObject cannot be pasted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::Copy


ITextRange::ChangeCase

The ITextRange::ChangeCase method changes the case of letters in this range according to the Type parameter.

STDMETHODIMP ITextRange::ChangeCase(
  long Type
);

Parameters

Type
[in] Type of case change. The default value is tomLower.
Case change type | Value | Meaning
tomLowerCase | 0 | Sets all text to lowercase.
tomUpperCase | 1 | Sets all text to uppercase.
tomTitleCase | 2 | Capitalizes the first letter of each word.
tomSentenceCase | 4 | Capitalizes the first letter of each sentence.
tomToggleCase | 5 | Toggles the case of each letter.

Return Values

This method returns an HRESULT. If successful, it returns S_OK. Otherwise, it returns S_FALSE.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange


ITextRange::Collapse

The ITextRange::Collapse method collapses the specified text range into a degenerate point at either the beginning or end of the range.

STDMETHODIMP ITextRange::Collapse(
  long bStart
);

Parameters

bStart
[in] Flag specifying the end to collapse at. It can be one of the following.
Value | Meaning
tomStart or tomTrue | Range is collapsed to the start of the range. This is the default.
tomEnd or tomFalse | Range is collapsed to the end of the range.

Return Values

This method returns an HRESULT. If successful, it returns S_OK. Otherwise, it returns S_FALSE.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange


ITextRange::Copy

The ITextRange::Copy method copies the text to a data object.

STDMETHODIMP ITextRange::Copy(
  VARIANT *pVar
);

Parameters

pVar
Pointer to an IDataObject that receives the copied text. pVar->ppunkVal is the out parameter for an IDataObject provided that the following conditions exist:
  • pVar->vt = (VT_UNKNOWN | VT_BYREF)
  • pVar is not null
  • pVar->ppunkVal is not null

    Otherwise, the Clipboard is used.

Return Values

This method returns an HRESULT. If successful, it returns S_OK. Otherwise, it returns E_OUTOFMEMORY.

Remarks

The ITextRange::Cut, ITextRange::Copy, and ITextRange::Paste methods let you perform the usual Cut, Copy, and Paste operations on a range object using an IDataObject, thereby not changing the contents of the Clipboard. Among Clipboard formats typically supported are CF_TEXT and CF_RTF. In addition, private Clipboard formats can be used to reference a text solution's own internal rich text formats.

To copy and replace plain text, you can use the ITextRange::GetText and ITextRange::SetText methods. To copy formatted text from range r1 to range r2 without using the Clipboard, you can use Copy and Paste and also the ITextRange::GetFormattedText and ITextRange::SetFormattedText methods, as shown in the following Visual Basic example:

    r2.GetFormattedText = r1.GetFormattedText

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::Cut, ITextRange::GetFormattedText, ITextRange::GetText, ITextRange::Paste, ITextRange::SetFormattedText, ITextRange::SetText


ITextRange::Cut

The ITextRange::Cut method cuts the plain or rich text to a data object or to the Clipboard, depending on the pVar parameter.

STDMETHODIMP ITextRange::Cut(
  VARIANT *pVar
);

Parameters

pVar
Pointer to an IDataObject that receives the cut text. pVar->ppunkVal is the out parameter for an IDataObject object, provided that the following conditions exist:
  • pVar->vt = (VT_UNKNOWN | VT_BYREF)
  • pVar is not null
  • pVar->ppunkVal is not null

    Otherwise, the Clipboard is used.

Return Values

This method returns an HRESULT. If successful, it returns S_OK. Otherwise it returns one of the following values. For more information about COM error codes, see Error Handling.

Value | Meaning
E_ACCESSDENIED | Text is write-protected.
E_OUTOFMEMORY | Out of memory.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange


ITextRange::Delete

The ITextRange::Delete method mimics the DELETE and BACKSPACE keys, with and without the CTRL key depressed.

STDMETHODIMP ITextRange::Delete(
  long Unit,
  long Count,
  long *pDelta
);

Parameters

Unit
Unit to use. Unit can be tomCharacter (the default value) or tomWord.
Count
Number of Units to delete. If Count = zero, it deletes the text in the range only. If Count is greater than zero, Delete acts as if the DELETE key was pressed Count times. If Count is less than zero, it acts as if the BACKSPACE key was pressed Count times. The default value is 1. For more information, see the Remarks.
pDelta
Pointer to a variable that receives the count of units deleted. It can be null. The *pDelta parameter is set equal to the number of Units deleted. Deleting the text in a nondegenerate range counts as one Unit.

Return Values

This method returns an HRESULT. If successful, it returns S_OK. Otherwise it returns one of the following values. For more information about COM error codes, see Error Handling.

Value | Meaning
E_ACCESSDENIED | Text is write-protected.
S_FALSE | Failure for some other reason.

Remarks

If Count = zero, this method deletes the text in the range, that is, it deletes nothing if the range is only an insertion point.

If Count is not zero, and the range is an insertion point (that is, degenerate), |Count| (absolute value of Count) Units are deleted in the logical direction given by the sign of Count, where a positive value is the direction toward the end of the story, and a negative value is toward the start of the story.

If Count is not zero, and the range is nondegenerate (contains text), the text in the range is deleted (regardless of the values of Unit and Count), thereby creating an insertion point. Then, |Count| - 1 Units are deleted in the logical direction given by the sign of Count.

The text in the range can also be deleted by assigning a null string to the range (executing statement r = where r is the range). However, Delete does not require allocating a BSTR.

Deleting the end-of-paragraph mark (CR) results in the special behavior of the Microsoft Word UI. Four cases are of particular interest:

  • If you delete just the CR but the paragraph includes text, then the CR is deleted, and the following paragraph gets the same paragraph formatting as current one.
  • If you delete the CR as well as some, but not all, of the characters in the following paragraph, the characters left over from the current paragraph get the paragraph formatting of the following paragraph.
  • If you select to the end of a paragraph, but not the whole paragraph, the CR is not deleted.
  • If you delete the whole paragraph (from the beginning through the CR), you delete the CR as well (unless it is the final CR in the file).

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, BSTR


ITextRange::EndOf

The ITextRange::EndOf method moves this range's ends to the end of the last overlapping Unit in the range.

STDMETHODIMP ITextRange::EndOf(
  long Unit,
  long Extend,
  long *pDelta
);

Parameters

Unit
Unit to use. Default value: tomWord. For a list of the other Unit values, see the discussion under ITextRange.
Extend
Indicator of how the shifting of the range ends is to proceed. It can be one of the following.
Value | Meaning
0 or tomMove | Collapses a nondegenerate range to the End of the original range by moving the insertion point. This is the default.
1 (or tomExtend) | Moves End to the end of the overlapping Unit. Does not move Start.

pDelta
Pointer to a variable that receives the count of characters that End is moved past. The value of the pointer can be null. On return, the value of *pDelta is the number of characters the insertion point or End is moved plus 1 if a collapse occurs to the entry End. If the range includes the final CR (at the end of the story) and Extend = tomMove, then *pDelta is set to –1, to indicate that the collapse occurred before the end of the range (because an insertion point cannot exist beyond the final CR).

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_NOTIMPL | Unit is not supported.
S_FALSE | Failure for some other reason.

Remarks

For comparison, the ITextRange::StartOf method moves the range ends to the beginning of the first overlapping Unit in the range. Note, the ITextRange::StartOf and ITextRange::EndOf methods differ from the ITextSelection::HomeKey and ITextSelection::EndKey methods in that the latter extend from the active end, whereas StartOf extends from Start and EndOf extends from End. If the range is an insertion point on a boundary between Units, EndOf does not change End. In particular, calling EndOf (tomCharacter, *, *) does not change End except for an insertion point at the beginning of a story.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::StartOf, ITextSelection::EndKey, ITextSelection::HomeKey


ITextRange::Expand

The ITextRange::Expand method expands this range so that any partial units it contains are completely contained.

STDMETHODIMP ITextRange::Expand(
  long Unit,
  long *pDelta
);

Parameters

Unit
Unit to include, if it is partially within the range. The default value is tomWord. For a list of the other Unit values, see the discussion under ITextRange.
pDelta
Pointer to a variable that receives the count of characters added to the range. The value can be null.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_NOTIMPL | Unit is not supported.
S_FALSE | Failure for some other reason.

Remarks

For example, if an insertion point is at the beginning, the end, or within a word, Expand(tomWord) expands the range to include that word. If the range already includes one word and part of another, Expand(tomWord) expands the range to include both words. Expand(tomWindow) expands the range to include the visible portion of the range's story.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange


ITextRange::FindText

The ITextRange::FindText method searches up to Count characters for the text given by bstr. The starting position and direction are also specified by Count, and the matching criteria are given by Flags.

STDMETHODIMP ITextRange::FindText(
  BSTR bstr,
  long Count,
  long Flags,
  long *pLength
);

Parameters

bstr
String to find.
Count
Maximum number of characters to search. It can be one of the following.
Value | Meaning
tomForward | Searches to the end of the story. This is the default value.
n (greater than 0) | Searches forward for n chars, starting from cpFirst. If the range itself matches bstr, another search is attempted from cpFirst + 1.
n (less than 0) | Searches backward for n chars, starting from cpLim. If the range itself matches bstr, another search is attempted from cpLim – 1.
0 (degenerate range) | Search begins after the range.
0 (nondegenerate range) | Search is limited to the range.

In all cases, if a string is found, the range limits are changed to be those of the matched string and *pLength is set equal to the length of the string. If the string is not found, the range remains unchanged and *pLength is set equal to zero.

Flags
Flags governing comparisons. It can be 0 (the default) or any combination of the following.
Match criterion | Value | Meaning
tomMatchWord | 2 | Matches whole words.
tomMatchCase | 4 | Matches case.
tomMatchPattern | 8 | Matches regular expressions.

pLength
Pointer to a variable that receives the length of string matched.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns S_FALSE. For more information about COM error codes, see Error Handling.

Remarks

The FindText method can also match special characters by using a caret (^) followed by a special letter. For a list of special characters, see the Special list available in the Microsoft Word Find and Replace dialog box. For example, ^p matches the next paragraph mark. Note, ^c can be used to represent the Clipboard contents in the string to be replaced. Thus, using ^c in the find string enables you to search for rich text. For more details, see the Microsoft Word Help files.

As a comparison with the FindText method, the ITextRange::FindTextStart method searches forwards or backwards from the range's Start cp, and the ITextRange::FindTextEnd method searches forwards or backwards from the range's End cp. For more details, see the descriptions of these methods.

The following are several code snippets that show the Find methods.

Example #1. The following Microsoft Visual Basic for Applications program prints all the /* … */ comments in a story identified by the range r.

Sub PrintComments (r As ITextRange)
    r.SetRange 0, 0           ' r = insertion pt at start of story
    Do While r.FindText("/*") And r.FindTextEnd("*/")    ' Select comment
        r.MoveStart tomCharacter, 2        ' But don't include the /*
        r.MoveEnd tomCharacter, -2        '  or */
        Print r                    ' Show the folks
    Loop
End Sub

Instead of these comments being printed, they could be inserted into another edit instance and saved to a file, or they could be inserted into separate cells in a table or spreadsheet.

To print all lines containing one or more occurrences of the word "laser", replace the loop by the following code:

    While r.FindText("laser")            ' Select next occurrence of "laser"
        r.Expand tomLine                ' Select enclosing line
        Print r                    ' Print the line
    Wend

Example #2. The following program prints a telephone list, given a story that contains an address list. The address list entries are separated by two or more paragraph marks, and each entry has the following form.

Person/Business Name
Address (one or more lines)
(area code) telephone number

Note the use of the character ^p in the FindText string argument to locate a pair of consecutive paragraph marks.

Sub PrintTelephoneList (r As ITextRange)
    r.SetRange 0, 0                 ' r = insertion point at start of story
    r.MoveWhile C1_WHITE            ' Bypass any initial white space
    Do
        r.EndOf tomParagraph, 1     ' Select next para (line): has name
        Print r                    ' Print it
        Do
            r.MoveWhile C1_SPACE        ' Bypass possible space chars
            If r.Char = Asc("(") Then Exit Do    ' Look for start of telephone #
        Loop While r.Move(tomParagraph)    ' Go to next paragraph
        r.EndOf tomParagraph, 1        ' Select line with telephone number
        Print r                    ' Print it
    Loop While r.FindText("^p^p")        ' Find two consecutive para marks
End Sub

Example #3. The following subroutine replaces all occurrences of the string, str1, in a range by str2:

Sub Replace ( tr As ITextRange, str1 As String, str2 As String )
    Dim r As ITextRange
    r = tr.Duplicate                ' Copy tr parameters to r
    r.End = r.Start                    ' Convert to insertion point at Start
    While r.FindText(str1, tr.End - r.End)        ' Match next occurrence of str
        r = str2                ' Replace it with rep
    Wend                        ' Iterate till no more matches
End Sub

Example #4. The following line of code inserts a blank before the first occurrence of a right parenthesis, (, that follows an occurrence of HRESULT.

    If r.FindText("HRESULT") And r.FindText("(") Then r = " ("

To do this for all such occurrences, change the If into a While/Wend loop in the above line of code. This an example of a FIND/REPLACE macro that cannot be run with Find and Replace dialog boxes.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::FindTextEnd, ITextRange::FindTextStart


ITextRange::FindTextEnd

The ITextRange::FindTextEnd method searches up to Count characters for the string, bstr, starting from the range's End cp. The search is subject to the comparison parameter, Flags. If the string is found, the End cp is changed to be the end of the matched string, and *pLength is set equal to the length of the string. If the string is not found, the range is unchanged and *pLength is set equal to zero.

STDMETHODIMP ITextRange::FindTextEnd(
  BSTR bstr,
  long Count,
  long Flags,
  long *pLength
);

Parameters

bstr
String that is searched for.
Count
Maximum number of characters to search. It can be one of the following.
Value | Meaning
tomForward | Search to the end of the story. This is the default value.
n (greater than 0) | Search forward for n chars, starting from cpLim.
n (less than 0) | Search backward for n chars, starting from cpLim.

Flags
Flags governing comparisons. It can be 0 (the default) or any combination of the following.
Match criterion | Value | Meaning
tomMatchWord | 2 | Matches whole words.
tomMatchCase | 4 | Matches case.
tomMatchPattern | 8 | Matches regular expressions.

pLength
Pointer to a variable that receives the length of string matched.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns S_FALSE.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::FindText, ITextRange::FindTextStart


ITextRange::FindTextStart

The ITextRange::FindTextStart method searches up to Count characters for the string, bstr, starting at the range's Start cp (cpFirst). The search is subject to the comparison parameter, Flags. If the string is found, the Start cp is changed to the matched string, and *pLength is set equal to the length of the string. If the string is not found, the range is unchanged, and *pLength is set equal to zero.

STDMETHODIMP ITextRange::FindTextStart(
  BSTR bstr,
  long Count,
  long Flags,
  long *pLength
);

Parameters

bstr
The string that is searched for.
Count
Maximum number of characters to search. It can be one of the following.
Value | Meaning
tomForward | Search to the end of the story. This is the default value.
n (greater than 0) | Search forward for n chars, starting from cpLim.
n (less than 0) | Search backward for n chars, starting from cpLim.

Flags
Flags governing the comparisons. It can be 0 (the default) or any combination of the following.
Match criterion | Value | Meaning
tomMatchWord | 2 | Matches whole words.
tomMatchCase | 4 | Matches case.
tomMatchPattern | 8 | Matches regular expressions.

pLength
Pointer to a variable that receives the length of the matched string.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns S_FALSE.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::FindText, ITextRange::FindTextEnd


ITextRange::GetChar

The ITextRange::GetChar property-get method retrieves the character at the range's Start cp (cpFirst).

STDMETHODIMP ITextRange::GetChar(
  long *pChar
);

Parameters

pChar
Pointer to a variable that receives the character at cpFirst.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If pChar is null, the method fails and it returns E_INVALIDARG.

Remarks

The ITextRange::GetChar (LONG *pChar) property-get method sets *pChar equal to the character at cpFirst. For example, the following Microsoft Visual Basic statement sets ch equal to the character pointed to by cpFirst.

ch = r.Char

Similarly, ITextRange::SetChar(Char) overwrites the character at cpFirst with the character, Char. Note that the characters retrieved and set by these methods are LONG variables, which hide the way that they are stored in the backing store, (as bytes, words, variable-length, and so forth), and they do not require using a BSTR.

The Char property, which can do most things that a characters collection can, has two big advantages:

  • It can reference any character in the parent story instead of being limited to the parent range.
  • It is significantly faster, since LONGs are involved instead of range objects.

Accordingly, the Text Object Model does not support a characters collection.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::SetChar


ITextRange::GetDuplicate

The ITextRange::GetDuplicate property-get method retrieves a duplicate of this range object.

STDMETHODIMP ITextRange::GetDuplicate(
  ITextRange **ppRange
);

Parameters

ppRange
Pointer to a variable that receives the pointer to a duplicate of the range.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | ppRange is null.
E_FAIL | Failure for some other reason.

Remarks

To create an insertion point in order to traverse a range, first duplicate the range and then collapse the duplicate at its Start cp. Note, a range is characterized by cpFirst, cpLim, and the story it belongs to.

Even if the range is actually an ITextSelection, the duplicate returned is an ITextRange. For an example, see the ITextRange::FindText method.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::FindText


ITextRange::GetEmbeddedObject

The ITextRange::GetEmbeddedObject method retrieves a pointer to the embedded object at the start of the specified range, that is, at cpFirst. The range must either be an insertion point or it must select only the embedded object.

STDMETHODIMP ITextRange::GetEmbeddedObject(
  IUnknown **ppObject
);

Parameters

ppObject
Pointer to a variable that receives the pointer to the object.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | ppObject is null.
S_FALSE | Failure for some other reason.

Remarks

If the start of this range does not have an embedded object or if the range selects more than a single object, *ppObject is set equal to null.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange


ITextRange::GetEnd

The ITextRange::GetEnd property-get method retrieves this range's End cp (cpLim).

STDMETHODIMP ITextRange::GetEnd(
  long *pcpLim
);

Parameters

pcpLim
Pointer to a variable that receives the End cp value.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If pcpLim is null, the method fails and it returns E_INVALIDARG.

Remarks

Note that, although a pointer to a range remains valid when the text is edited, this is not the case for the cp position. A cp is volatile, that is, it becomes invalid as soon as text is inserted or deleted before the cp position. Thus, users should be careful about using methods that return cp values, especially if the values are to be stored for any length of time.

This method is similar to the ITextRange::GetStart method which sets *pcpFirst = cpFirst.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::GetStart, ITextRange::SetEnd


ITextRange::GetFont

The ITextRange::GetFont property-get method retrieves an ITextFont object with the character attributes of the specified range.

STDMETHODIMP ITextRange::GetFont(
  ITextFont **ppFont
);

Parameters

ppFont
Pointer to a variable that receives a pointer to an ITextFont object.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If ppFont is null, the method fails and it returns E_INVALIDARG.

Remarks

For plain-text controls, these objects do not vary from range to range, but in rich-text solutions, they do. See the section on ITextFont for further details.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextFont, ITextRange


ITextRange::GetFormattedText

The ITextRange::GetFormattedText property-get method retrieves an ITextRange object with the specified range's formatted text.

STDMETHODIMP ITextRange::GetFormattedText(
  ITextRange **ppRange
);

Parameters

ppRange
Pointer to a variable that receives a pointer to the ITextRange object with the formatted text.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | ppRange is null.
E_OUTOFMEMORY | Out of memory.

Remarks

The ITextRange::GetFormattedText method, which amounts to an alias for the ITextRange::GetDuplicate method, is included to be VBA-friendly. The method returns the formatted text in a range. The ITextRange::SetFormattedText method replaces the text in the range with the formatted text given by *pRange. If the ITextRange does not belong to the same TOM engine, call QueryInterface for an IDataObject interface.

Among the formats typically supported by IDataObject are CF_TEXT and CF_RTF. In addition, private formats can be used to reference a text solution's own internal rich-text formats. For example, the following line of Microsoft Visual Basic code uses the FormattedText property to replace the text in the range, r2, by the formatted text in r1.

    r2.FormattedText = r1.FormattedText

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::SetFormattedText


ITextRange::GetIndex

The ITextRange::GetIndex method retrieves the story index of the Unit parameter at the specified range Start cp (cpFirst). The first Unit in a story has an index value of 1. The index of a Unit is the same for all cps from that immediately preceding the Unit up to the last character in the Unit.

STDMETHODIMP ITextRange::GetIndex(
  long Unit,
  long *pIndex
);

Parameters

Unit
Unit that is indexed. For a list of possible Unit values, see the discussion under ITextRange.
pIndex
Pointer to a variable that receives the index value. The value is zero if Unit does not exist.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | pIndex is null.
E_NOTIMPL | Unit does not exist.

Remarks

The ITextRange::GetIndex(Unit, pIndex) method retrieves the story index of a word, line, sentence, paragraph, and so forth, at the range Start. Unit specifies which kind of entity to index, such as words (tomWord), lines (tomLine), sentences (tomSentence), or paragraphs (tomParagraph). For example, GetIndex(tomLine, pIndex) sets *pIndex equal to the line number of the first line in the range. Note that for a range at the end of the story, GetIndex(Unit, pIndex) returns the number of Units in the story. Thus, you can get the number of words, lines, objects, and so forth, in a story.

Note, the index value returned by the GetIndex method is not valid if the text is subsequently edited. Thus, users should be careful about using methods that return index values, especially if the values are to be stored for any length of time. This is in contrast to a pointer to a range, which does remain valid when the text is edited.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange


ITextRange::GetPara

The ITextRange::GetPara property-get method retrieves an ITextPara object with the paragraph attributes of the specified range.

STDMETHODIMP ITextRange::GetPara(
  ITextPara **ppPara
);

Parameters

ppPara
Pointer to a variable that receives a pointer to the ITextPara object.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If ppPara is null, the method fails and it returns E_INVALIDARG.

Remarks

For plain-text controls, these objects do not vary from range to range, but in rich-text solutions, they do. See the section on ITextPara for further details.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextPara, ITextRange


ITextRange::GetPoint

The ITextRange::GetPoint method retrieves screen coordinates for the start or end character position in the text range.

STDMETHODIMP ITextRange::GetPoint(
  long Type,
  long *px,
  long *py
);

Parameters

Type
Flag that indicates the position to retrieve. This parameter can include one value from each of the following tables. Use one of the following values to indicate the start or end of the range.
Value | Meaning
tomStart | Start of range.
tomEnd | End of range.

Use one of the following values to indicate the vertical position.
Value | Meaning
TA_TOP | Top edge of the bounding rectangle.
TA_BASELINE | Base line of the text.
TA_BOTTOM | Bottom edge of the bounding rectangle.

Use one of the following values to indicate the horizontal position.
Value | Meaning
TA_LEFT | Left edge of the bounding rectangle.
TA_CENTER | Center of the bounding rectangle.
TA_RIGHT | Right edge of the bounding rectangle.

px
Pointer to a variable that receives the x coordinate.
py
Pointer to a variable that receives the y coordinate.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Either px or py is null.
S_FALSE | Failure for some other reason.

Remarks

The ITextRange:: GetPoint method gives ITextRange the ability to emulate UI-pointer commands; it is also handy for accessibility purposes.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::SetPoint, SetTextAlign


ITextRange::GetStart

The ITextRange::GetStart property-get method retrieves the specified range Start cp (cpFirst).

STDMETHODIMP ITextRange::GetStart(
  long *pcpFirst
);

Parameters

pcpFirst
Pointer to a variable that receives the Start cp value.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If pcpFirst is null, the method fails and it returns E_INVALIDARG.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::GetEnd, ITextRange::SetStart


ITextRange::GetStoryLength

The ITextRange::GetStoryLength property-get method retrieves the count of characters in the specified range's story.

STDMETHODIMP ITextRange::GetStoryLength(
  long *pCount
);

Parameters

pCount
Pointer to a variable that receives the count of characters in the specified range's story.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If pCount is null, the method fails and it returns E_INVALIDARG.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange


ITextRange::GetStoryType

The ITextRange::GetStoryType property-get method retrieves the type of the specified range's story.

STDMETHODIMP ITextRange::GetStoryType(
  long *pValue
);

Parameters

pValue
Pointer to a variable that receives the type of the range's story. The *pValue value can be one of the following values.
Story type | Value | Story type | Value
tomUnknownStory | 0 | tomEvenPagesHeaderStory | 6
tomMainTextStory | 1 | tomPrimaryHeaderStory | 7
tomFootnotesStory | 2 | tomEvenPagesFooterStory | 8
tomEndnotesStory | 3 | tomPrimaryFooterStory | 9
tomCommentsStory | 4 | tomFirstPageHeaderStory | 10
tomTextFrameStory | 5 | tomFirstPageFooterStory | 11

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If pValue is null, the method fails and it returns E_INVALIDARG.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange


ITextRange::GetText

The ITextRange::GetText property-get method retrieves the plain text in this range. The Text property is the default property of the ITextRange interface.

STDMETHODIMP ITextRange::GetText(
  BSTR *pbstr
);

Parameters

pbstr
Pointer to a variable that receives a BSTR containing the text.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | pbstr is null.
E_OUTOFMEMORY | Insufficient memory to hold the text.

Remarks

The ITextRange::GetText method returns the plain text in the range. The Text property is the default property for ITextRange. As such, it is automatically invoked for the range r, in a Microsoft Visual Basic for Applications statement such as:

    print r

Some of the examples below use this fact. The ITextRange::SetText method substitutes bstr for the range text. For processing a single character, the Char property is more efficient than the Text property and does not require creating a single character range for storing a character. If the range is degenerate, the Text property lets you insert text easily. You can also delete the text in a range r by either of these Visual Basic for Applications statements:

    r.delete

    r = ""

You can use the Text property to copy plain text from one place to another, simply by setting one range equal to another (note, this is quite different from the Duplicate property; for more information, see ITextRange::GetDuplicate). So the Visual Basic statement

    r1 = r2            ' Replace r1's text by r2's

sets the text in the range, r1, to that in the range r2. These ranges can be in different stories or even in different applications. However, they do imply copying the text first into a BSTR and then from that string to the target location. For large amounts of text, the ITextRange::Copy and ITextRange::Paste methods can be faster, since they can perform the copy directly from source to target and with any format supported by the source and target.

The text returned by the Text property is given in Unicode. The end-of-paragraph mark may be given by 0x2029 (the Unicode Paragraph Separator), or by CRLF (0xd, 0xa), or by CR alone, depending on the original file. Microsoft Word uses CR alone, unless it reads another choice in from a file, the Clipboard, or an IDataObject. The placeholder for an embedded object is given by the special character, WCH_EMBEDDING, which has the official Unicode value 0xFFFC.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::Copy, ITextRange::GetDuplicate, ITextRange::Paste, BSTR


ITextRange::InRange

The ITextRange::InRange method determines whether this range is within or at the same text as a specified range.

STDMETHODIMP ITextRange::InRange(
  ITextRange *pRange,
  long *pB
);

Parameters

pRange
Pointer to the ITextRange text that is compared to the current range.
pB
Pointer to a variable that receives the comparison result. The pointer can be null. The method returns *pb = tomTrue if and only if the range is within or at the same text as pRange.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns S_FALSE.

Remarks

For the range r2, to be contained within the range r1, both ranges must be in the same story, and the limits of r2 have to satisfy either of these statements:

  • cpFirst1 = cpFirst2 = cpLim2 = cpLim1 (that is, both ranges are degenerate and have identical insertion points).
  • (cpFirst1 ≤ cpFirst2 ≤ cpLim2 ≤ cpLim1) and (cpFirst2 < cpLim1) (that is, a nondegenerate range with Start and End positions at or within those of the other range with the Start position before the other range's End position).

The following method can be useful for walking one range with another:

    r2 = r1.Duplicate
    r2.End = r2.Start       ' Collapse r2 to Start end
    While r2.InRange(r1)    ' Iterate so long as r2 remains within r1
         ...   ' This code would change the r2 cps
    Wend

When the ITextRange::FindText, ITextRange::MoveWhile, and ITextRange::MoveUntil method families are used, you can use one range to walk another by specifying the appropriate limit count of characters (for an example, see the Remarks in ITextRange::Find).

ITextRange::IsEqual is a special case of InRange that returns *pB tomTrue if the text range *pRange has the same cpFirst and cpLim values as well belonging to the same story.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::FindText, ITextRange::MoveUntil, ITextRange::MoveWhile


ITextRange::InStory

The ITextRange::InStory method determines whether this range's story is the same as a specified range's story.

STDMETHODIMP ITextRange::InStory(
  ITextRange *pRange,
  long *pB
);

Parameters

pRange
Pointer to the ITextRange object whose story is compared to this range's story.
pB
Pointer to a variable that receives the comparison result. The pointer can be null. The method returns *pB = tomTrue if this range's story is the same as *pRange's; otherwise it returns *pB = tomFalse.

Return Values

The method returns an HRESULT. If the two stories are the same, the method returns S_OK. Otherwise, it returns S_FALSE.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange


ITextRange::IsEqual

The ITextRange::IsEqual method determines whether this range has the same character positions and story as those of a specified range.

STDMETHODIMP ITextRange::IsEqual(
  ITextRange *pRange,
  long *pB
);

Parameters

pRange
Pointer to the ITextRange object that is compared to this range.
pB
Pointer to a variable that receives the comparison result. The pointer can be null. The method returns *pb = tomTrue if this range points at the same text (cps and story) as pRange. Otherwise, it returns tomFalse.

Return Values

The method returns an HRESULT. If the ranges have the same character positions and story, the method returns S_OK. Otherwise, it returns S_FALSE.

Remarks

The ITextRange::IsEqual method returns tomTrue only if the range points at the same text as *pRangeI. See "Finding Rich Text" for code that compares two different pieces of text to see if they contain the same plain text and the same character formatting.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces


ITextRange::Move

The ITextRange::Move method moves the insertion point forward or backward a specified number of Units. If the range is nondegenerate, the range is collapsed to an insertion point at either end, depending on Count, and then is moved.

STDMETHODIMP ITextRange::Move(
  long Unit,
  long Count,
  long *pDelta
);

Parameters

Unit
Unit to use. The default value is tomCharacter. For information on other values, see the discussion in ITextRange.
Count
Number of units to move past. The default value is 1. If Count is greater than zero, motion is forward—toward the end of the story—and if Count is less than zero, motion is backward—toward the beginning. If Count = zero, the range is unchanged.
pDelta
Pointer to a variable that receives the actual number of units the insertion point moves past. The pointer can be null. For more information, see the Remarks section.

Return Values

The method returns an HRESULT. If the method succeeds in moving the insertion point, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_NOTIMPL | Unit is not supported.
S_FALSE | Failure for some other reason.

Remarks

If the range is degenerate (an insertion point), this method tries to move the insertion point Count Units.

If the range is nondegenerate and Count is greater than zero, this method collapses the range at cpLim, moves the resulting insertion point forward to a Unit boundary (if it is not already at one), and then tries to move Count -1 Units forward. If the range is nondegenerate and Count is less than zero, this method collapses the range at cpFirst, moves the resulting insertion point backward to a Unit boundary (if it isn't already at one), and then tries to move |Count| -1 Units backward. Thus, in both cases, collapsing a nondegenerate range to an insertion point, whether or not moving to the start or end of the Unit following the collapse, counts as a Unit.

The Move method returns *pDelta = number of Units actually moved. This method never moves the insertion point beyond the story of this range. If Count Units would move the insertion point before the beginning of the story, it is moved to the story beginning and *pDelta is set accordingly. Similarly, if Count Units would move it beyond the end of the story, it is moved to the story end.

The ITextRange::Move method works similarly to the UI-oriented ITextSelection::MoveLeft and ITextSelection::MoveRight methods, except that the direction of motion is logical rather than geometrical. That is, with Move the direction is either toward the end or toward the start of the story. Depending on the language, moving toward the end of the story could be moving to the left or to the right. To get a feel for Count, press CTRL+RIGHT ARROW (—>) in a Microsoft Word document for a variety of selections. In left-to-right text, this keystroke behaves the same as Move(tomWord, 1), and MoveRight(tomWord, 1). Count corresponds to the number of times you press CTRL+RIGHT ARROW.

For example, if you press CTRL+RIGHT ARROW for the selections shown in both of the following figures, you end up with an insertion point at character position 8, since this command

collapses the selections at their cpLims (7 and 8, respectively) and moves to the next tomWord boundary. The first selection doesn't include the blank space at character position 7, so CTRL+ RIGHT ARROW (—>) moves past the space to the tomWord boundary at character position 8. cpLim is already at a tomWord boundary for the second selection, so CTRL+RIGHT ARROW just collapses the selection at that boundary. Similarly, CTRL+LEFT ARROW (<—), which for this text acts like Move(tomWord, -1), and MoveLeft(tomWord, 1) collapses the first selection at character position 5, which is already at a tomWord boundary, so no more motion occurs. But CTRL+LEFT ARROW collapses the second selection at character position 4 and then moves to zero, since that's the next tomWord boundary in the direction of motion.

The return argument, *pDelta, is set equal to the number of Units that the insertion point is moved including one Unit for collapsing a nondegenerate range and moving it to a Unit boundary. So, if no motion and no collapse occur, as when the range is an insertion point at the end of the story, *pDelta is set equal to zero. This approach is useful for controlling program loops that process a whole story.

In both of the cases mentioned above, calling Move(tomWord, 1) sets *pDelta equal to 1 because the ranges were collapsed. Similarly, calling Move(tomWord, -1) sets *pDelta equal to -1 for both cases. Collapsing, with or without moving part of a Unit to a Unit boundary, counts as a Unit moved.

The direction of motion refers to the logical character ordering in the plain-text backing store. This approach avoids the problems of geometrical ordering, such as left versus right and up versus down, in international software. Such geometrical methods are still needed in the edit engine, of course, since keyboards have arrow keys to invoke them. If the range is really an ITextSelection object, then methods like MoveLeft and MoveRight can be used.If Unit specifies characters (tomCharacter), the Text Object Model (TOM) uses the Unicode character set. To convert between Unicode and multibyte character sets the MultiByteToWideChar and WideCharToMultiByte functions provide easy ways to convert between Unicode and multibyte character sets on import and export, respectively. For more information, see ITextDocument::Open. In this connection, the use of a CRLF to separate paragraphs is as problematic as DBCS. The ITextSelection UI methods back up over a CRLF as if it were a single character, but the Move methods count CRLFs as two characters. It's clearly better to use a single character as a paragraph separator, which in TOM is represented by CR, although the Unicode paragraph separator character, 0x2029, is accepted. In general, TOM engines should support CRLF, CR, LF, VT, FF, and 0x2029. Rich Edit 2.0 also supports CRCRLF for backward compatibility.

See also the ITextRange::MoveStart and ITextRange::MoveEnd methods, which move the range Start or End position Count Units, respectively.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextDocument::Open, ITextRange, ITextRange::MoveStart, ITextRange::MoveEnd, ITextSelection::MoveLeft and ITextSelection::MoveRight , MultiByteToWideChar, WideCharToMultiByte,


ITextRange::MoveEnd

The ITextRange::MoveEnd method moves the range End a specified number of Units in a specified direction.

STDMETHODIMP ITextRange::MoveEnd(
  long Unit,
  long Count,
  long *pDelta
);

Parameters

Unit
Unit used in the range move.The default value is tomCharacter. For a list of the other Unit values, see the discussion under ITextRange.
Count
Number of Units to move past. The default value is 1. If Count is greater than zero, motion is forward—toward the end of the story—and if Count is less than zero, motion is backward—toward the beginning. Count = zero leaves the End unchanged.
pDelta
Pointer to a variable that receives the actual number of Units that the range End is moved past. The value can be null.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_NOTIMPL | Unit is not supported.
S_FALSE | Failure for some other reason.

Remarks

If the new End precedes the old Start, the new Start is set equal to the new End, that is, it becomes a degenerate range or an insertion point.

The motion described by MoveEnd is logical rather than geometric. That is, motion is toward the end or toward the start of a story. Depending on the language, moving to the end of the story could be moving left or moving right.

For more information, see the discussion in ITextRange and the Remarks section of ITextRange::Move.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::Move


ITextRange::MoveEndUntil

The ITextRange::MoveEndUntil method moves the range's End to the cp of the first character found that is in the set of characters specified by Cset, provided that the character is found within Count characters of the End.

STDMETHODIMP ITextRange::MoveEndUntil(
  VARIANT *Cset,
  long Count,
  long *pDelta
);

Parameters

Cset
Pointer to the character set to use in the match. This could be an explicit string of characters or a character-set index. For more information, see Character Match Sets.
Count
Maximum number of characters to move past. The default value is tomForward, which searches to the end of the story. If Count is greater than zero, the search moves forward (toward the end of the story). If Count is less than zero, the search moves backwards (toward the beginning of the story). Count = zero leaves the End unchanged.
pDelta
Pointer to a variable that receives the actual count of characters that the end is moved past. The value can be null. The method returns *pDelta = the number of characters the range End is moved, plus 1 for a match if Count is greater than zero and –1 for a match if Count is less than zero.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Cset is invalid.
S_FALSE | Failure for some other reason.

Remarks

If no character from the set specified by Cset is found within Count positions of the range's End, the range is left unchanged. If the new End precedes the old Start, the new Start is set equal to the new End.

The motion described by MoveEndUntil is logical rather than geometric. That is, motion is toward the end or toward the start of a story. Depending on the language, moving to the end of the story could be moving left or moving right.

For more information, see the discussion in ITextRange and the Remarks section of ITextRange::Move.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::Move, ITextRange::MoveUntil


ITextRange::MoveEndWhile

The ITextRange::MoveEndWhile method moves the End either Count characters or just past all contiguous characters that are found in the set of characters specified by Cset, whichever is less.

STDMETHODIMP ITextRange::MoveEndWhile(
  VARIANT *Cset,
  long Count,
  long *pDelta
);

Parameters

Cset
Pointer to the character set to use in the match. This could be an explicit string of characters or a character-set index. For more information, see Character Match Sets.
Count
Maximum number of characters to move past. The default value is tomForward, which searches to the end of the story. If Count is greater than zero, the search moves forward (toward the end of the story). If Count is less than zero, the search moves backwards (toward the beginning of the story). Count = zero leaves the End unchanged.
pDelta
Pointer to a variable that receives the actual number of characters that the end is moved. The value can be null.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Cset is not valid.
S_FALSE | Failure for some other reason.

Remarks

If the new end precedes the old start, the new start is set equal to the new end.

The motion described by MoveEndWhile is logical rather than geometric. That is, motion is toward the end or toward the start of a story. Depending on the language, moving to the end of the story could be moving left or moving right.

For more information, see the discussion in ITextRange and the Remarks section of ITextRange::Move.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::Move, ITextRange::MoveWhile


ITextRange::MoveStart

The ITextRange::MoveStart method moves the range Start a specified number of Units in a specified direction.

STDMETHODIMP ITextRange::MoveStart(
  long Unit,
  long Count,
  long *pDelta
);

Parameters

Unit
Unit used in the move. The default value is tomCharacter. For a list of the other Unit values, see the discussion under ITextRange.
Count
Number of units to move. The default value is 1. If Count is greater than zero, motion is forward—toward the end of the story—and if Count is less than zero, motion is backward—toward the beginning. Count = zero leaves the Start unchanged.
pDelta
Pointer to a variable that receives the actual number of units that the end is moved. The value can be null.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_NOTIMPL | Unit is not supported.
S_FALSE | Failure for some other reason.

Remarks

If the new Start follows the old End, the new End is set equal to the new Start.

The motion described by MoveStart is logical rather than geometric. That is, motion is toward the end or toward the start of a story. Depending on the language, moving to the end of the story could be moving left or moving right.

For more information, see the discussion in ITextRange and the Remarks section of ITextRange::Move.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::Move, ITextRange::MoveEnd


ITextRange::MoveStartUntil

The ITextRange::MoveStartUntil method moves the range's Start to the cp of the first character found that is in the set of characters specified by Cset, provided that character is found within Count characters of Start.

STDMETHODIMP ITextRange::MoveStartUntil(
  VARIANT *Cset,
  long Count,
  long *pDelta
);

Parameters

Cset
Pointer to the character set to use in the match. This could be an explicit string of characters or a character-set index. For more information, see Character Match Sets.
Count
Maximum number of characters to move past. The default value is tomForward, which searches to the end of the story. If Count is greater than zero, the search is forward—toward the end of the story—and if Count is less than zero, search is backward—toward the beginning. Count = zero leaves the Start unchanged.
pDelta
Pointer to a variable that receives the actual number of characters that the end is moved. The value can be null. The method returns *pDelta = the number of characters the range start is moved, plus 1 for a match if Count is greater than zero and –1 for a match if Count is less than zero.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Cset is not valid.
S_FALSE | Failure for some other reason.

Remarks

If no character from Cset is found within Count positions of Start, the range is left unchanged.

If the new Start follows the old End, the new End is set equal to the new Start.

The motion described by MoveStartUntil is logical rather than geometric. That is, motion is toward the end or toward the start of a story. Depending on the language, moving to the end of the story could be moving left or moving right.

For more information, see the discussion in ITextRange and the Remarks section of ITextRange::Move.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::Move, ITextRange::MoveUntil


ITextRange::MoveStartWhile

The ITextRange::MoveStartWhile method moves the Start either Count characters or just past all contiguous characters that are found in the set of characters specified by Cset, whichever is less.

STDMETHODIMP ITextRange::MoveStartWhile(
  VARIANT *Cset,
  long Count,
  long *pDelta
);

Parameters

Cset
Pointer to the character set to use in the match. This could be an explicit string of characters or a character-set index. For more information, see Character Match Sets.
Count
Maximum number of characters to move past. The default value is tomForward, which searches to the end of the story. If Count is greater than zero, the search is forward—toward the end of the story—and if Count is less than zero, search is backward—toward the beginning. Count = zero leaves the Start unchanged.
pDelta
Pointer to a variable that receives the actual count of characters that the Start is moved. This parameter can be null.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Cset is not valid.
S_FALSE | Failure for some other reason.

Remarks

If the new Start follows the old End, the new End is set equal to the new Start.

The motion described by MoveStartWhile is logical rather than geometric. That is, motion is toward the end or toward the start of a story. Depending on the language, moving to the end of the story could be moving left or moving right.

For more information, see the discussion in ITextRange and the Remarks section of ITextRange::Move.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::Move, ITextRange::MoveWhile


ITextRange::MoveUntil

The ITextRange::MoveUntil method searches up to Count characters for the first character in the set of characters specified by Cset. If a character is found, the range is collapsed to that point. The start of the search and the direction are also specified by Count.

STDMETHODIMP ITextRange::MoveUntil(
  VARIANT *Cset,
  long Count,
  long *pDelta
);

Parameters

Cset
Pointer to the character set used in the match. This could be an explicit string of characters or a character-set index. For more information, see Character Match Sets.
Count
Maximum number of characters to move past. The default value is tomForward, which searches to the end of the story. If Count is less than zero, the search is backwards starting at the Start. If Count is greater than zero, the search is forward starting at the End.
pDelta
Pointer to a variable that receives the count of characters that the end is moved including one for the character that is matched. That is, the method returns *pDelta = the number of characters the insertion point is moved, plus 1 for a match if Count is greater than zero and –1 for a match if Count less than zero. The pointer can be null.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Cset is not valid.
S_FALSE | Failure for some other reason.

Remarks

If no character is matched, the range is unchanged.

The motion described by MoveUntil is logical rather than geometric. That is, motion is toward the end or toward the start of a story. Depending on the language, moving to the end of the story could be moving left or moving right.

For more information, see the discussion in ITextRange and the Remarks section of ITextRange::Move.

The ITextRange::MoveStartUntil(Cset, Count, pDelta) and ITextRange::MoveEndUntil(cset, Count, pDelta) methods move the Start and End, respectively, until it finds the first character that is also in the set specified by the Cset parameter.

The ITextRange::MoveUntil method is similar to ITextRange::MoveWhile, but there are two differences. First, MoveUntil moves an insertion point until it finds the first character that belongs to the character set specified by Cset. Second, in MoveUntil the character matched counts as an additional character in the value returned in pDelta. This lets you know that the character at one end of the range or the other belongs to the Cset even though the insertion point stays at one of the range ends.

For example, suppose the range, r, is an insertion point. To see if the character at r (that is, given by r.GetChar()) is in Cset, call

    r.MoveUntil(Cset, 1)

If the character is in Cset, the return value is 1 and the insertion point does not move. Similarly, to see if the character preceding r is in Cset, call

    r.MoveUntil(Cset, –1),

If the character is in Cset, the return value is –1.

The following Visual Basic for Applications (VBA) subroutine prints all numbers in the story identified by the range, r.

Sub PrintNumbers (r As ITextRange)
   r.SetRange 0, 0    ' r = insertion point at start of story
   While r.MoveUntil(C1_DIGIT)  ' Move r to 1st digit in next number
      r.MoveEndWhile C1_DIGIT  ' Select number (span of digits)
      Print r    ' Print it
   Wend
End Sub

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, GetChar, ITextRange::Move, ITextRange::MoveEndUntil, ITextRange::MoveStartUntil, ITextRange::MoveWhile


ITextRange::MoveWhile

The ITextRange::MoveWhile method starts at a specified end of a range and searches while the characters belong to the set specified by Cset and while the number of characters is less than or equal to Count. The range is collapsed to an insertion point when a non-matching character is found.

STDMETHODIMP ITextRange::MoveWhile(
  VARIANT *Cset,
  long Count,
  long *pDelta
);

Parameters

Cset
Pointer to the character set to use in the match. This could be an explicit string of characters or a character-set index. For more information, see Character Match Sets.
Count
Maximum number of characters to move past. The default value is tomForward, which searches to the end of the story. If Count is less than zero, the search starts at Start and goes backward -- toward the beginning of the story. If Count is greater than zero, the search starts at the End and goes forward -- toward the end of the story.
pDelta
Pointer to a variable that receives the actual count of characters end is moved. This parameter can be null.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Cset is not valid.
S_FALSE | Failure for some other reason.

Remarks

The motion described by MoveUntil is logical rather than geometric. That is, motion is toward the end or toward the start of a story. Depending on the language, moving to the end of the story could be moving left or moving right.

For more information, see the discussion in ITextRange and the Remarks section of ITextRange::Move.

The MoveWhile method is similar to ITextRange::MoveUntil , but MoveWhile searches as long as it finds members of the set specified by Cset, and there is no additional increment to the value pDelta.

The ITextRange::MoveStartWhile (Cset, Count, pDelta) and ITextRange::MoveEndWhile(cset, Count, pDelta) methods move the Start and End, respectively, just past all contiguous characters that are found in set of characters specified by the Cset parameter.

The VARIANT type is primarily intended to be used with IDispatch scenarios like Visual Basic for Applications (VBA), but it can be readily used from C or C++ as well. The following C++ code illustrates how to initialize and use the VARIANT argument varg for matching a span of digits in the range r.

VariantInit(&varg);
varg.vt = VT_I4;
varg.lVal = C1_DIGIT;
hr = r.MoveWhile(&varg, tomForward, pDelta); // Move IP past span of digits

Alternatively, an explicit string could be used, as in the following sample.

VariantInit(&varg);
bstr = SysAllocString("0123456789");
varg.vt = VT_BSTR;
varg.bstr = bstr;
hr =r.MoveWhile(&varg, tomForward, pDelta);    // Move IP past span of digits

The following VBA example code matches the body of the next SGML entry in a range, r. SGML entries start with <keyword ...> and end with </keyword>.

r.Find <                  ' Get to start of next tag
r.MoveWhile C1_SPACE      ' Bypass any space characters
r.MoveEndWhile C1_ALPHA   ' Match keyword
s$ = </ + r               ' Create VBA string to search for
r.Find >                  ' Bypass remainder of start tag
r.FindEnd s$              ' Match up to end of closing keyword
r.FindEnd <, tomStart     ' Back up to start of end tag
                          ' r has body of SGML entry

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::Move, ITextRange::MoveEndWhile, ITextRange::MoveStartWhile, ITextRange::MoveUntil


ITextRange::Paste

The ITextRange::Paste method pastes text from a specified data object. See ITextRange::Copy for further discussion.

STDMETHODIMP ITextRange::Paste(
  VARIANT *pVar,
  long Format
);

Parameters

pVar
Pointer to the IDataObject to paste. However, the contents of the Clipboard are used if any of the following are true

pVar is null

pVar->punkVal is null

pVar-> is not VT_UNKNOWN

pVar->punkVal does not return an IDataObject when queried for one

Format
Clipboard format to use in the paste operation. Zero is best format, which usually is RTF, but CF_UNICODETEXT and other formats are also possible. The default value is zero.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_ACCESSDENIED | Destination is write-protected.
E_OUTOFMEMORY | Destination cannot contain the text to be pasted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::Copy


ITextRange::ScrollIntoView

The ITextRange::ScrollIntoView method scrolls the specified range into view.

STDMETHODIMP ITextRange::ScrollIntoView(
  long bStart
);

Parameters

bStart
Flag specifying the end to scroll into view. It can be one of the following.
Value | Meaning
tomEnd | Scrolls the End cp to appear on the bottom line.
tomStart | Scrolls the Start cp to appear on the top line.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns S_FALSE.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange


ITextRange::Select

The ITextRange::Select method sets the Start, End, and story values of the active selection to those of this range.

STDMETHODIMP ITextRange::Select(void)

Parameters

This function has no parameters.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns S_FALSE.

Remarks

The active end of the new selection is at End.

The caret for an ambiguous cp is displayed at the beginning of the line.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange


ITextRange::SetChar

The ITextRange::SetChar property-put method sets the character at the range's Start cp.

STDMETHODIMP ITextRange::SetChar(
  long Char
);

Parameters

Char
New value for character at cpFirst.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_ACCESSDENIED | Text is write-protected.
E_OUTOFMEMORY | Out of memory.

Remarks

SetChar lets you specify the precise character code to use. However, string literals with similar looking glyphs can be misleading.

Note that the characters set by this method are LONG instead of a BSTR. This hides the way that they are stored in the backing store, (as bytes, words, variable-length, and so forth).

Frequently on systems that do not have automatic word-wrapping, documents have hard carriage returns inserted just for line breaks. The following code shows a simple, but not perfect, way to convert such hard carriage returns back to blanks for the story that is associated with the range r.

    Sub EnableWrap(r As ITextRange)   ' Convert false hard CRs to soft
        r.SetRange 0, 0               ' r is set at start of story
        While r.Move(tomParagraph)    ' Go to start of next paragraph
            If r.MoveWhile(C1_WHITE, 1) = 0 Then    ' Next char isn't white space
                r.Move tomCharacter, -1
                r.SetChar = Asc(" ")    ' Replace CR by blank
            End If
        Wend        ' Loop till no more CRs in story
    End Sub

Alternatively, you could use the following inside the IF loop.

r.MoveStart tomCharacter, -1        ' Select previous char (the CR)
r = " "        ' Replace it with a blank

This approach enables you to wrap the text to other widths. However, the algorithm isn't perfect: it assumes that a hard carriage return that is followed by anything other than white space (blank, tab, line-feed, carriage-return, and so forth) should be replaced by a blank. The algorithm also assumes that the carriage return character is a single character like CR or the Unicode EOP 0x2029 character. And, the combination CR-LF isn't matched and would require writing and executing more code (or use FindText(^p)). Another caution is that there are other cases, such as mixed code and documentation, where the algorithm does not work correctly.

However, SetChar is more efficient than a replace operation that is accomplished by a delete followed by an insertion. Thus, rewriting the code without using SetChar would probably be much slower.

The Char property, which can do most things that a characters collection can, has two big advantages: it can reference any character in the parent story instead of being limited to the parent range, and it's significantly faster, since LONGs rather than range objects are involved. Because of these advantages, the Text Object Model doesn't support a characters collection.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange


ITextRange::SetEnd

The ITextRange::SetEnd property-put method sets this range's End cp.

STDMETHODIMP ITextRange::SetEnd(
  long cp
);

Parameters

cp
The new End cp (cpLim).

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns S_FALSE.

Remarks

If the new End cp is less than the Start cp, this also sets Start = cp, that is, the range becomes an insertion point.

If this range is actually the selection, then End becomes the active end and, if the display is not frozen, it is scrolled into view.

ITextRange::SetStart sets the range's Start cp and ITextRange::SetRange sets both range ends simultaneously. To convert a nondegenerate range, r, into a degenerate one (insertion point) at cpFirst , use

r.End = r.Start

Similarly, r.Start = r.End converts r into an insertion point at cpLim.

To add 1 to cpLim, unless it is at the end of the story, use:

r.End = r.End + 1

This also makes cpLim the active end, and it can turn a degenerate range into a nondegenerate one.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::GetEnd, ITextRange::SetRange, ITextRange::SetStart


ITextRange::SetFont

The ITextRange::SetFont property-put method sets this range's character attributes to those given by pFont.

STDMETHODIMP ITextRange::SetFont(
  ITextFont *pFont
);

Parameters

pFont
[in] Pointer to a font object with the desired character format.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_ACCESSDENIED | Text is protected.
E_INVALIDARG | pFont is null.
E_OUTOFMEMORY | Out of memory.

Remarks

For occasional format changes, use the SetFont method. However, to make a number of character formatting changes, it is more efficient to use a font duplicate. This is because every time you execute a statement like range.font.bold = tomTrue, a font object is allocated and freed. However, a font duplicate can be allocated once and used many times. Furthermore, you can save the font duplicate, reset it to the default or undefined states with the ITextFont::Reset method, and give it values as needed for your rich-text processing. For sample code that shows how to use font duplicates, see Using a Font Duplicate.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextFont::Reset


ITextRange::SetFormattedText

The ITextRange::SetFormattedText property-put method replaces this range text with formatted text given by pRange.

STDMETHODIMP ITextRange::SetFormattedText(
  ITextRange *pRange
);

Parameters

pRange
[in] Pointer to the formatted text to replace this range's text.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_ACCESSDENIED | Text is protected.
E_INVALIDARG | pRange is null.
E_OUTOFMEMORY | Out of memory.

Remarks

If the ITextRange doesn't belong to the same TOM engine, call QueryInterface for an IDataObject interface.

Among the formats typically supported by the IDataObject are CF_TEXT and CF_RTF. In addition, private formats can be used to reference a text solution's own internal rich-text formats. As an example, the following line of Microsoft Visual Basic code uses the FormattedText property to replace the text in the range, r2, by the formatted text in r1.

    r2.FormattedText = r1.FormattedText

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::GetDuplicate, ITextRange::GetFormattedText


ITextRange::SetIndex

The ITextRange::SetIndex method changes this range to the specified Unit of the story.

STDMETHODIMP ITextRange::SetIndex(
  long Unit,
  long Index,
  long Extend
);

Parameters

Unit
[in] Unit used to index the range. For a list of Unit values, see the discussion under ITextRange.
Index
[in] Index for the Unit. This range will be relocated to the Unit that has this index number. If positive, the numbering of Units begins at the start of the story and proceeds forward. If negative, the numbering begins at the end of the story and proceeds backwards. The start of the story corresponds to Index = 1 for all units that exist, and the last Unit in the story corresponds to Index = -1.
Extend
[in] Flag that indicates the extent of the range. If zero (the default), the range is collapsed to an insertion point at the Start cp of the indicated Unit. If nonzero, the range is set to the entire Unit.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Index is not valid.
E_NOTIMPL | Unit is not supported.
S_FALSE | Failure for some other reason.

Remarks

This method allows an application to work with line-oriented text, such as programs, in a convenient way. For example, SetIndex (tomLine, 10, 0) converts a range to an insertion point at the start of the tenth line.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange


ITextRange::SetPara

The ITextRange::SetPara property-put method sets the paragraph attributes of this range to those given by pPara.

STDMETHODIMP ITextRange::SetPara(
  ITextPara *pPara
);

Parameters

pPara
[in] Pointer to the paragraph object with the desired paragraph format.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_ACCESSDENIED | Text is write-protected.
E_INVALIDARG | pPara is null.
E_OUTOFMEMORY | Out of memory.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::GetPara


ITextRange::SetPoint

The ITextRange::SetPoint method changes the range based on a specified point.

at or up through (depending on Extend) the point (x, y) aligned according to Type.

STDMETHODIMP ITextRange::SetPoint(
  long x,
  long y,
  long Type,
  long Extend
);

Parameters

x
[in] Horizontal coordinate of the specified point, in absolute screen coordinates.
y
[in] Vertical coordinate of the specified point, in absolute screen coordinates.
Type
[in] The end to move to the specified point. It can be one of the following.
Value | Meaning
tomStart | Move the Start of range.
tomEnd | Move the End of range.

Extend
[in] How to set the endpoints of the range. If Extend = zero, which is the default, the range is an insertion point at the specified point (or at the nearest point with selectable text). If Extend = 1, the end specified by Type is moved to the point and the other end is left alone.

Return Values

The method returns S_OK.

Remarks

An application can use the specified point in the WindowFromPoint function to get the HWND of the window, which usually can be used to find the client-rectangle coordinates (although a notable exception is with Windowless Controls).

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::GetPoint


ITextRange::SetRange

The ITextRange::SetRange property-put method sets the range endpoints to the specified values.

STDMETHODIMP ITextRange::SetRange(
  long cp1,
  long cp2
);

Parameters

cp1
Character position for Start. This must be less than cp2.
cp2
Character position for End. This must be greater than cp1.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | cp1 is greater than cp2.
S_FALSE | Failure for some other reason.

Remarks

If the range is a nondegenerate selection, cp2 is the active end; if it is a degenerate selection, the ambiguous cp is displayed at the start of the line (rather than at the end of the previous line).

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange


ITextRange::SetStart

The ITextRange::SetStart method sets this range's Start cp.

STDMETHODIMP ITextRange::SetStart(
  long cp
);

Parameters

cp
[in] The new Start cp.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns S_FALSE.

Remarks

Note that if cp is greater than End, this method also sets End = cp, thus making the range an insertion point. If this range is actually the selection, then Start becomes the active end and is scrolled into view if the display is not frozen.

ITextRange::SetEnd sets the range's cpLim, and ITextRange::SetRange sets both range ends simultaneously. To convert a nondegenerate range, r, into a degenerate one (insertion point), you can use the following code.

r.End = r.Start

Similarly, r.Start = r.End converts r into an insertion point at cpLim.

To add 1 to cpLim, if it is not at the end of the story, call the following:

r.End = r.End + 1

This also makes cpLim the active end, and it can turn a degenerate range into a nondegenerate one.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::GetStart, ITextRange::SetEnd, ITextRange::SetRange,


ITextRange::SetText

The ITextRange::SetText property-put method replaces the text in this range by the specified text.

STDMETHODIMP ITextRange::SetText(
  BSTR bstr
);

Parameters

bstr
[in] Text that replaces the current text in this range. If null, the current text is deleted.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_ACCESSDENIED | Text is write-protected.
E_INVALIDARG | bstr is null.
E_OUTOFMEMORY | Out of memory.

Remarks

SetText replaces the text in the range with the new text. In contrast, ITextSelection::TypeText replaces the selection with the text bstr and leaves the selection as an insertion point just following the inserted text, just as if you had typed the text in. For UI selection behavior, see ITextSelection::TypeText.

If, after you call SetText, you call ITextRange::GetText, you get back the same text that you set with the SetText method (unless some other range has changed that text in between the calls).

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::GetText, ITextSelection::TypeText


ITextRange::StartOf

The ITextRange::StartOf method moves the range ends to the start of the first overlapping Unit in the range.

STDMETHODIMP ITextRange::StartOf(
  long Unit,
  long Extend,
  long *pDelta
);

Parameters

Unit
Unit to use in the move operation. For a list of Unit values, see the discussion under ITextRange.
Extend
How to move the ends of the range. It can be one of the following
Value | Meaning
0 (or tomMove) | Collapses a nondegenerate range to the Start by moving the insertion point. This is the default.
1 (or tomExtend) | Moves Start to the beginning of the overlapping Unit. Does not move End.

pDelta
Pointer to a variable that receives the number of characters that Start is moved. It can be null. On return, *pDelta = the signed number of characters the insertion point or Start is moved. Note that this value is always less than or equal to zero, since the motion is always toward the beginning of the story.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_NOTIMPL | Unit is not supported.
S_FALSE | Failure for some other reason.

Remarks

If the range is an insertion point on a boundary between Units, StartOf doesn't change Start. Note that if Unit StartOf (tomCharacter, extend, pDelta) does not change Start.

See also the ITextRange::EndOf, which moves the range ends to the end of the last overlapping Unit in the range.

Note, the ITextRange::StartOf and ITextRange::EndOf methods differ from the ITextSelection::HomeKey and ITextSelection::EndKey methods in that the latter extend from the active end, whereas StartOf extends from Start and EndOf extends from End.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextRange::EndOf, ITextSelection::EndKey, ITextSelection::HomeKey


ITextSelection

A text selection is a text range with selection highlighting. It is associated with some kind of view, and has some UI-oriented methods that allow one to emulate keyboard input. Thus, an application can use the ITextRange methods on a text selection, as well as the ITextSelection methods.

For keyboard input emulation, ranges used in selections use the concept of the active end, which is typically the end that was last moved. For example, if an ITextRange::Move* method operates on a range that is actually a text selection, the most recently moved end is the active one. The most familiar examples of the active end are those involving SHIFT+Arrow Key handling, where the active end is the one that moves. Accordingly, the ITextSelection methods include move methods for the active end, such as MoveLeft or MoveRight, and methods to get and set the active end status. These methods manipulate selections in ways similar to the standard Windows cursor-keypad operations. This allows you to implement, for example, a macro recorder facility.

To see how the cursor-keypad methods work, see the following table. A given method corresponds to a cursor-keypad key with the CTRL and SHIFT keys. The Unit parameter is selected by pressing or not pressing the CTRL key, while the Extend parameter is selected by pressing or not pressing the SHIFT key. Note, MoveUp and MoveDown correspond to more than one keypad key. For more information, see the descriptions of the methods.

Method | Cursor-keypad key | Unit given by CTRL pressed (not pressed) | Extend given by SHIFT pressed (not pressed)
EndKey | END | tomStory (tomLine) | tomExtend (tomMove)
HomeKey | HOME | tomStory (tomLine) | tomExtend (tomMove)
MoveLeft | LEFT ARROW | tomWord (tomCharacter) | tomExtend (tomMove)
MoveRight | RIGHT ARROW | tomWord (tomCharacter) | tomExtend (tomMove)
MoveUp | UP ARROW | tomParagraph (tomLine) | tomExtend (tomMove)
MoveDown | DOWN ARROW | tomParagraph (tomLine) | tomExtend (tomMove)
MoveUp | PAGE UP | tomWindow (tomScreen) | tomExtend (tomMove)
MoveDown | PAGE DOWN | tomWindow (tomScreen) | tomExtend (tomMove)

When to Implement

Applications typically do not implement the ITextSelection interface. Instead, Microsoft text solutions such as rich edit controls implement ITextSelection as part of their Text Object Model (TOM) implementation.

When to Use

Applications can retrieve an ITextSelection pointer by calling the ITextDocument::GetSelection method.

Methods in Vtable Order

IUnknown Methods

QueryInterface
AddRef
Release

IDispatch Methods

GetTypeInfoCount
GetTypeInfo
GetIDsOfNames
Invoke

ITextRange Methods

For a table of methods, see ITextRange.

ITextSelection Methods

Method | Description
EndKey | Provides support for the END key.
GetFlags | Retrieves the state of the editing mode flags, such as insert or type over.
GetType | Retrieves the type of selection.
HomeKey | Provides support for the HOME key.
MoveLeft | Provides support for the LEFT ARROW key.
MoveRight | Provides support for the RIGHT ARROW key.
MoveUp | Provides support for the UP ARROW key and the PAGE UP key.
MoveDown | Provides support for the DOWN ARROW key and the PAGE DOWN key.
SetFlags | Sets the editing mode flags.
TypeText | Inserts a string in a selection.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, Using TOM GUIDs


ITextSelection::EndKey

The ITextSelection::EndKey method mimics the functionality of the UI End key.

Extend = tomExtend (or nonzero) corresponds to the SHIFT key being depressed. Unit = tomLine corresponds to the CTRL key not being depressed and tomStory to CTRL being depressed. Returns *pDelta = number of characters the insertion point or active end is moved.

STDMETHODIMP ITextSelection::EndKey(
  long Unit,
  long Extend,
  long *pDelta
);

Parameters

Unit
Unit to use. It can be one of the following.
Value | Meaning
tomLine | Depending on Extend, it moves either the insertion point or the active end to the end of the last line in the selection. This is the default.
tomStory | Depending on Extend, it moves either the insertion point or the active end to the end of the last line in the story.
tomColumn | Depending on Extend, it moves either the insertion point or the active end to the end of the last column in the selection. This is available only if the Text Object Model engine supports tables.
tomRow | Depending on Extend, it moves either the insertion point or the active end to the end of the last row in the selection. This is available only if the Text Object Model engine supports tables.

Extend
Flag that indicates how to change the selection. If Extend = zero (or tomMove), the method collapses the selection to an insertion point. If Extend = 1 (or tomExtend), the method moves the active end and leaves the other end alone. The default value is zero.
pDelta
Pointer to a variable that receives the count of characters that the insertion point or the active end is moved. This parameter can be null.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Unit is neither tomLine nor tomStory.
S_FALSE | Failure for some other reason.

Remarks

The ITextSelection::HomeKey and EndKey methods are used to mimic the standard Microsoft Windows cursor-keypad HOME/END key behavior.

tomLine mimics the HOME or END key behavior without the CTRL key pressed, while tomStory mimics the behavior with the CTRL key pressed. Similarly, tomMove mimics the HOME or END key behavior without the SHIFT key pressed, while tomExtend mimics the behavior with the SHIFT key pressed. So EndKey(tomStory) converts the selection into an insertion point at the end of the associated story, while EndKey(tomStory, tomExtend) moves the active end of the selection to the end of the story and leaves the other end where it was.

The HomeKey and EndKey methods are logical methods like the ITextRange::Move methods, rather than directional methods. Thus, they depend on the language that is involved. For example, in Arabic text, HomeKey moves to the right end of a line, whereas in English text, it moves to the left. Thus, HomeKey and EndKey are different than the ITextSelection::MoveLeft and ITextSelection::MoveRight methods. Also, note that the EndKey method is quite different from the End property, which is the cp at the end of the selection. HomeKey and EndKey also differ from the ITextRange::StartOf and ITextRange::EndOf methods in that they extend from the active end, whereas StartOf extends from Start and EndOf extends from End.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange::Move, ITextRange::StartOf, ITextRange::EndOf, ITextSelection, ITextSelection::HomeKey, ITextSelection::MoveLeft, ITextSelection::MoveRight


ITextSelection::GetFlags

The ITextSelection::GetFlags property-get method retrieves text selection flags.

STDMETHODIMP ITextSelection::GetFlags(
  long *pFlags
);

Parameters

pFlags
Pointer to a variable that receives any combination of the following selection flags.
Selection flag | Value | Meaning
tomSelStartActive | 1 | Start end is active.
tomSelAtEOL | 2 | For degenerate selections, the ambiguous cp corresponding to both the beginning of a line and the end of the preceding line should have the caret displayed at the end of the preceding line.
tomSelOvertype | 4 | Insert/Overtype mode is set to overtype.
tomSelActive | 8 | Selection is active.
tomSelReplace | 16 | Typing and pasting replaces selection.

Each of the table values is binary. Thus, if any value is not set, the text selection has the opposite property.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If pFlags is null, the method fails and it returns E_INVALIDARG.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextSelection, ITextSelection::SetFlags


ITextSelection::GetType

The ITextSelection::GetType property-get method retrieves the type of text selection.

STDMETHODIMP ITextSelection::GetType(
  long *pType
);

Parameters

pType

Pointer to a variable that receives the selection type. The method returns *pType with one of the values in the following table.

Selection type | Value | Meaning
tomNoSelection | 0 | No selection and no insertion point.
tomSelectionIP | 1 | Insertion point.
tomSelectionNormal | 2 | Single nondegenerate range.
tomSelectionFrame | 3 | Frame.
tomSelectionColumn | 4 | Table column.
tomSelectionRow | 5 | Table rows.
tomSelectionBlock | 6 | Block selection.
tomSelectionInlineShape | 7 | Picture.
tomSelectionShape | 8 | Shape.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If pType is null, the method fails and it returns E_INVALIDARG.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextSelection


ITextSelection::HomeKey

The ITextSelection::HomeKey method generalizes the functionality of the UI HOME key.

STDMETHODIMP ITextSelection::HomeKey(
  long Unit,
  long Extend,
  long *pDelta
);

Parameters

Unit
Unit to use in the HOME key operation. It can take on one of the following values.
Value | Meaning
tomLine | Depending on Extend, it moves either the insertion point or the active end to the beginning of the first line in the selection. This is the default.
tomStory | Depending on Extend, it moves either the insertion point or the active end to the beginning of the first line in the story.
tomColumn | Depending on Extend, it moves either the insertion point or the active end to the beginning of the first column in the selection. This is available only if the Text Object Model engine supports tables.
tomRow | Depending on Extend, it moves either the insertion point or the active end to the beginning of the first row in the selection. This is available only if the Text Object Model engine supports tables.

Extend
Flag that indicates how to change the selection. If Extend = zero (or tomMove), the method collapses the selection to an insertion point. If Extend = 1 (or tomExtend), the method moves the active end and leaves the other end alone. The default value is zero.
pDelta
Pointer to a variable that receives the count of characters that the insertion point or the active end is moved. This parameter can be null.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Unit is neither tomLine nor tomStory.
S_FALSE | Failure for some other reason.

Remarks

The HomeKey and ITextSelection::EndKey methods are used to mimic the standard Microsoft Windows cursor-keypad HOME/END key behavior.

tomLine mimics the HOME or END key behavior without the CTRL key pressed, while tomStory mimics the behavior with the CTRL key pressed. Similarly, tomMove mimics the HOME or END key behavior without the SHIFT key pressed, while tomExtend mimics the behavior with the SHIFT key pressed. So HomeKey(tomStory) converts the selection into an insertion point at the beginning of the associated story, while HomeKey(tomStory, tomExtend) moves the active end of the selection to the beginning of the story and leaves the other end where it was.

The HomeKey and EndKey methods are logical methods like the ITextRange::Move methods, rather than directional methods. Thus, they depend on the language that is involved. For example, in Arabic text, HomeKey moves to the right end of a line, whereas in English text, it moves to the left. Thus, HomeKey and EndKey are different than the ITextSelection::MoveLeft and ITextSelection::MoveRight methods. Also, note that the HomeKey method is quite different from the Start property, which is the cp at the beginning of the selection. HomeKey and EndKey also differ from the ITextRange::StartOf and ITextRange::EndOf methods in that they extend from the active end, whereas StartOf extends from Start and EndOf extends from End.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange::Move, ITextRange::StartOf, ITextRange::EndOf, ITextSelection, ITextSelection::EndKey, ITextSelection::MoveLeft, ITextSelection::MoveRight


ITextSelection::MoveDown

The ITextSelection::MoveDown method mimics the functionality of the UI DOWN ARROW and PAGE DOWN keys.

STDMETHODIMP ITextSelection::MoveDown(
  long Unit,
  long Count,
  long Extend,
  long *pDelta
);

Parameters

Unit
Unit to use in the operation. It can be one of the following.
Value | Corresponding key combination | Meaning
tomLine | DOWN ARROW (¯) | Moves down one line. This is the default.
tomParagraph | CTRL+DOWN ARROW (¯) | Moves down one paragraph.
tomScreen | PAGE DOWN | Moves down one screen.
tomWindow | CTRL+PAGE DOWN | Moves to last character in window.

Count
Number of Units to move past. The default value is 1.
Extend
Flag that indicates how to change the selection. If Extend = zero (or tomMove), the method collapses the selection to an insertion point and then moves. If Extend = 1 (or tomExtend), the method moves the active end and leaves the other end alone. The default value is zero.

A nonzero Extend value corresponds to the SHIFT key being pressed in addition to the key combination described in Unit.

pDelta
Pointer to a variable that receives the actual count of Units moved. The method returns *pDelta = actual count of units the insertion point or active end is moved down. This parameter can be null. Note: Collapsing the selection counts as one unit.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Unit is not valid.
S_FALSE | Failure for some other reason.

Remarks

The ITextSelection::MoveUp and ITextSelection::MoveDown methods are similar to the ITextSelection::MoveLeft and ITextSelection::MoveRight methods, except that they reflect the behavior of the UP ARROW (), DOWN ARROW (¯), PAGE UP, and PAGE DOWN keys on the cursor-keypad.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextSelection, ITextSelection::MoveLeft, ITextSelection::MoveRight, ITextSelection::MoveUp


ITextSelection::MoveLeft

The ITextSelection::MoveLeft method generalizes the functionality of the UI LEFT ARROW key.

STDMETHODIMP ITextSelection::MoveLeft(
  long Unit,
  long Count,
  long Extend,
  long *pDelta
);

Parameters

Unit
Unit to use. It can be one of the following.
Value | Corresponding key combination | Meaning
tomCharacter | LEFT ARROW (<—) | Move one character position to the left. This is the default.
tomWord | CTRL+LEFT ARROW (<—) | Move one word to the left.

Note, if Count is less than zero, movement is to the right.

Count
Number of Units to move past. The default value is 1. If Count is less than zero, movement is to the right.
Extend
Flag that indicates how to change the selection. If Extend = zero (or tomMove), the method collapses the selection to an insertion point at the active end and then moves it. If Extend = 1 (or tomExtend), the method moves the active end and leaves the other end alone. The default value is zero.

A nonzero Extend value corresponds to the SHIFT key being pressed in addition to the key combination described in Unit.

pDelta
Pointer to a variable that receives the actual count of Units moved. The method returns *pDelta = actual count of units the insertion point or active end is moved left. This parameter can be null. Note: Collapsing the selection, when Extend = 0, counts as one unit.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Unit is not valid.
S_FALSE | Failure for some other reason.

Remarks

Microsoft WordBasic move methods like CharRight, CharLeft, WordRight, and WordLeft are hybrids that can do four things that are closely related to the standard Windows arrow-key edit behavior:

  • Move the current insertion point if there's no selection.
  • Move the active end of the selection if there is a selection.
  • Turn an insertion point into a selection and vice versa.
  • Return a Boolean stating if movement occurred.

The Extend argument of MoveLeft and MoveRight enables you to be consistent with the first three items above, and the pDelta is a generalization of the fourth. For example, given a selection, s, consisting of a single range, you have the following correspondences (for left-to-right characters).

ITextSelection | WordBasic | Function
s.MoveRight tomWord, 1, 1 | WordRight 1,1 | Moves active end one word right.
s.MoveLeft tomCharacter, 1, 1 | CharLeft 1,1 | Moves active end one character left.

As in WordBasic, if Count is less than zero, the meanings of left and right are interchanged, that is MoveLeft (Unit, Count, Extend) is equivalent to MoveRight (Unit, -Count, Extend).

Similar to WordBasic and the LEFT ARROW (<—) key UI behavior, calling MoveLeft(Unit, Count) on a degenerate selection moves the insertion point the specified number of Units. Calling MoveLeft (Unit, Count is greater than zero, 1) on a degenerate range causes the range to become nondegenerate with the left end being the active end.

When Extend = tomExtend (or is nonzero), MoveLeft moves only the active end of the selection, leaving the other end where it is. However, if Extend equals zero and the selection starts as a nondegenerate range, MoveLeft(Unit, Count > zero) moves the active end Count - 1Units left and then moves the other end to the active end. In other words, it makes an insertion point at the active end. Note, collapsing the range counts as one Unit. Thus, MoveLeft(tomCharacter) converts a nondegenerate selection into a degenerate one at the selection's left end. Here, Count has the default value of 1 and Extend has the default value of zero. This example corresponds to pressing the LEFT ARROW (<—) key. MoveLeft and MoveRight are related to the ITextRange move methods, but differ in that they explicitly use the active end (the end moved by pressing the SHIFT key).

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextSelection, ITextSelection::MoveRight


ITextSelection::MoveRight

The ITextSelection::MoveRight method generalizes the functionality of the UI RIGHT ARROW key.

STDMETHODIMP ITextSelection::MoveRight(
  long Unit,
  long Count,
  long Extend,
  long *pDelta
);

Parameters

Unit
Unit to use. It can be one of the following.
Value | Corresponding key combination | Meaning
tomCharacter | RIGHT ARROW (—>) | Move one character position to the right. This is the default.
tomWord | CTRL+RIGHT ARROW (—>) | Move one word to the right.

Note, if Count is less than zero, movement is to the left.

Count
Number of Units to move past. The default value is 1. If Count is less than zero, movement is to the left.
Extend
Flag that indicates how to change the selection. If Extend = zero (or tomMove), the method collapses the selection to an insertion point at the active end and then moves it. If Extend = 1 (or tomExtend), the method moves the active end and leaves the other end alone. The default value is zero.

A nonzero Extend value corresponds to the SHIFT key being pressed in addition to the key combination described in Unit.

pDelta
Pointer to a variable that receives the actual count of Units moved. The method returns *pDelta = actual count of units the insertion point or active end is moved left. This parameter can be null. Note: Collapsing the selection, when Extend = 0, counts as one unit.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Unit is not valid.
S_FALSE | Failure for some other reason.

Remarks

Microsoft WordBasic move methods like CharRight, CharLeft, WordRight, and WordLeft are hybrids that can do four things that are closely related to the standard Windows arrow-key edit behavior:

  • Move the current insertion point if there's no selection.
  • Move the active end of the selection if there is a selection.
  • Turn an insertion point into a selection and vice versa.
  • Return a Boolean stating if movement occurred.

The Extend argument of MoveLeft and MoveRight enables you to be consistent with the first three items above, and the pDelta is a generalization of the fourth. For example, given a selection, s, consisting of a single range, you have the following correspondences (for left-to-right characters).

ITextSelection | WordBasic | Function
s.MoveRight tomWord, 1, 1 | WordRight 1,1 | Moves active end one word right.
s.MoveLeft tomCharacter, 1, 1 | CharLeft 1,1 | Moves active end one character left.

As in WordBasic, if Count is less than zero, the meanings of left and right are interchanged, that is MoveLeft (Unit, Count, Extend) is equivalent to MoveRight (Unit, -Count, Extend).

Similar to WordBasic and the RIGHT ARROW (—>) key UI behavior, calling MoveRight(Unit, Count) on a degenerate selection moves the insertion point the specified number of Units. Calling MoveRight(Unit, Count is greater than zero, 1) on a degenerate range, it causes the range to become nondegenerate with the right end being the active end.

When Extend = tomExtend (or is nonzero), MoveRight moves only the active end of the selection, leaving the other end where it is. However, if Extend equals zero and the selection starts as a nondegenerate range, MoveRight(Unit, Count > zero) moves the active end Count - 1Units right and then moves the other end to the active end. In other words, it makes an insertion point at the active end. Note, collapsing the range counts as one Unit. Thus, MoveRight(tomCharacter) converts a nondegenerate selection into a degenerate one at the selection's right end. Here, Count has the default value of 1 and Extend has the default value of zero. This example corresponds to pressing the right arrow (—>) key. MoveLeft and MoveRight are related to the ITextRange move methods, but differ in that they explicitly use the active end (the end moved by pressing the SHIFT key).

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextSelection, ITextSelection::MoveLeft


ITextSelection::MoveUp

The ITextSelection::MoveUp method mimics the functionality of the UI UP ARROW and PAGE UP keys.

Nonzero Extend values correspond to the SHIFT key being depressed. Unit corresponds to the CTRL key as described under the ITextSelection::MoveDown method. ITextSelection::MoveUp returns *pDelta = actual number of units the insertion point or active end is moved up.

Note Collapsing the selection counts as one unit.

STDMETHODIMP ITextSelection::MoveUp(
  long Unit,
  long Count,
  long Extend,
  long *pDelta
);

Parameters

Unit
Unit to use in the operation. It can be one of the following.
Value | Corresponding key combination | Meaning
tomLine | UP ARROW () | Moves up one line. This is the default.
tomParagraph | CTRL+UP ARROW () | Moves up one paragraph.
tomScreen | PAGE UP | Moves up one screen.
tomWindow | CTRL+PAGE UP | Moves to first character in window.

Count
Number of Units to move past. The default value is 1.
Extend
Flag that indicates how to change the selection. If Extend = zero (or tomMove), the method collapses the selection to an insertion point and then moves. If Extend = 1 (or tomExtend), the method moves the active end and leaves the other end alone. The default value is zero.

A nonzero Extend value corresponds to the SHIFT key being pressed in addition to the key combination described in Unit.

pDelta
Pointer to a variable that receives the actual count of Units moved. The method returns *pDelta = actual count of units the insertion point or active end is moved down. This parameter can be null. Note: Collapsing the selection counts as one unit.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Unit is not valid.
S_FALSE | Failure for some other reason.

Remarks

The ITextSelection::MoveUp and ITextSelection::MoveDown methods are similar to the ITextSelection::MoveLeft and ITextSelection::MoveRight methods, except that they reflect the behavior of the UP ARROW (), DOWN ARROW(¯), PAGE UP, and PAGE DOWN keys on the cursor-keypad.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextSelection, ITextSelection::MoveDown, ITextSelection::MoveLeft, ITextSelection::MoveRight


ITextSelection::SetFlags

The ITextSelection::SetFlags property-put method sets the text selection flags.

STDMETHODIMP ITextSelection::SetFlags(
  long Flags
);

Parameters

Flags
New flag values. It can be any combination of the following.
Selection flag | Value | Meaning
tomSelStartActive | 1 | Start end is active.
tomSelAtEOL | 2 | For degenerate selections, the ambiguous cp corresponding to both the beginning of a line and the end of the preceding line should have the caret displayed at the end of the preceding line.
tomSelOvertype | 4 | Insert/Overtype mode is set to overtype.
tomSelActive | 8 | Selection is active.
tomSelReplace | 16 | Typing and pasting replaces selection.

Each of the table values is binary. Thus, if any value is not set, the text selection has the opposite property.

Return Values

The method returns S_OK.

Remarks

To make sure that the Start end is active and that the ambiguous cp is displayed at the end of the line, execute the following code:

s.Flags = tomSelStartActive + tomSelAtEOL

The Flags property is useful because an ITextRange object can select itself. With SetFlags, you can change the active end from the default value of End, select the caret position for an ambiguous cp, or change the Insert/Overtype mode.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange, ITextSelection, ITextSelection::GetFlags


ITextSelection::TypeText

The ITextSelection::TypeText method types the string given by bstr at this selection as if someone typed it. This is similar to the underlying ITextRange::SetText method, but is sensitive to the Insert/Overtype key state and UI settings like AutoCorrect and smart quotes.

STDMETHODIMP ITextSelection::TypeText(
  BSTR bstr
);

Parameters

bstr
String to type into this selection.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_ACCESSDENIED | Text is write-protected.
E_INVALIDARG | bstr is null.
E_OUTOFMEMORY | Out of memory.

Remarks

The TypeText method types the string given by bstr at this selection as if someone typed it. Using TypeText is faster than sending characters through the SendMessage function, but it is slower than using ITextRange::SetText.

TypeText is similar to the underlying ITextRange::SetText method, however, it is sensitive to the Insert/Overtype key state and UI settings like AutoCorrect and smart quotes. For example, it deletes any nondegenerate selection and then inserts or overtypes (depending on the Insert/Overtype key state—see the ITextSelection::SetFlags method) the string bstr at the insertion point, leaving this selection as an insertion point following the inserted text.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextRange::SetText, ITextSelection, ITextSelection::SetFlags, SendMessage


ITextStoryRanges

This purpose of the ITextStoryRanges interface is to enumerate the stories in an ITextDocument. You get a pointer to an ITextStoryRanges collection by calling the ITextDocument::GetStoryRanges method. Each story obtained from this collection is represented by an ITextRange object that covers the whole story. Text Object Model engines that only have a single story don't need to implement an ITextStoryRanges interface. Your code should only get a stories collection if ITextDocument::GetStoryCount returns a story count greater than one.

Methods in Vtable Order

IUnknown Methods

QueryInterface
AddRef
Release

IDispatch Methods

GetTypeInfoCount
GetTypeInfo
GetIDsOfNames
Invoke

ITextStoryRanges Methods

Method | Description
_NewEnum | Retrieves an IEnumVARIANT enumerator interface for the stories collection.
Item | Retrieves an ITextRange object for the Indexth story in this stories collection.
GetCount | Retrieves the number of stories in the specified stories collection.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, Using TOM GUIDs


ITextStoryRanges::_NewEnum

The ITextStoryRanges::_NewEnum method retrieves an IEnumVARIANT enumerator interface for this stories collection.

STDMETHODIMP ITextStoryRanges::_NewEnum(
  IUnknown **ppunkEnum
);

Parameters

ppunkEnum
Pointer to a variable that receives the enumerator interface.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | ppunkEnum is null.
E_FAIL | Failure for some other reason.

Remarks

This definition together with the implementation of IEnumVARIANT, enables one to support the following Visual Basic for Applications code:

    Dim t As ITextDocument
    Dim c As ITextStoryRanges
    Dim r As ITextRange

    Set t = gObj
    Set c = t.StoryRanges

    For Each r In c
        Debug.Print r.Text
    Next

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextStoryRanges


ITextStoryRanges::GetCount

The ITextStoryRanges::GetCount property-get method retrieves the number of stories in the specified stories collection.

STDMETHODIMP ITextStoryRanges::GetCount(
  long *pCount
);

Parameters

pCount
Pointer to a variable that receives the count of stories.

Return Values

This method returns S_OK.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextStoryRanges


ITextStoryRanges::Item

The ITextStoryRanges::Item method retrieves an ITextRange object for the Indexth story in this story collection.

STDMETHODIMP ITextStoryRanges::Item(
  LONG Index,
  ITextRange **ppRange
);

Parameters

Index
Index of story range that is retrieved. The default value is 1, which indicates the first story in the collection. Count, given by ITextStoryRanges::GetCount, indicates the last story in the collection. If Index is less than zero, the stories are counted from last to first, with -1 being the index of the last story in the collection, and Index = - Count indicating the first story in the collection.
ppRange
Pointer to a variable that receives the range.

Return Values

The method returns an HRESULT. If the method succeeds, it returns S_OK. If the method fails, it returns one of the following error codes. For more information about COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | ppRange is null or Index is out of range.
E_FAIL | Failure for some other reason.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Tom.h.

See Also

Text Object Model Overview, Text Object Model Interfaces, ITextStoryRanges, ITextStoryRanges::GetCount


Windowless Rich Edit Controls

The Component Object Model (COM) defines a set of interfaces to support windowless objects. Windowless objects can enter the in-place active state without having their own window, but rather use the window of their container. Consequently, a windowless object uses fewer system resources and gives better performance through faster activation and deactivation. In addition, windowless objects can be nonrectangular and transparent.

Windowless rich edit controls provide rich text editing support for windowless objects. Instead of creating a windowed rich edit control, you create a text services object that uses interfaces to provide access to the rich edit functionality.

For more information about windowless objects, see the IOleInPlaceSiteWindowless and IOleInPlaceObjectWindowless interfaces and the Windowless Controls topic in the Platform SDK and the "OC96 and Windowless Controls" topic in the Microsoft® ActiveX® SDK.

  • About Windowless Rich Edit Controls
  • Windowless Rich Edit Controls Reference


About Windowless Rich Edit Controls

A windowless rich edit control, also known as a text services object, is an object that provides the functionality of a rich edit control without providing the window. To provide the functionality of a window, such as the ability to receive messages and a device context into which it can draw, windowless rich edit controls use a pair of interfaces: ITextServices and ITextHost.

To create a windowless rich edit control, call the CreateTextServices function with a pointer to your implementation of the ITextHost interface. CreateTextServices returns an IUnknown pointer that you can query to retrieve a pointer to the ITextServices implementation of the windowless control.

The ITextHost interface has methods that the windowless control calls to retrieve information about your window. For example, the text services object calls the ITextHost::TxGetDC method to retrieve a device context into which it can draw. The windowless control calls the ITextHost::TxNotify method to send notifications, such as the rich edit notification messages, to the text host. The text services object calls other ITextHost methods to request the text host to perform other window-related services. For example, the ITextHost::TxInvalidateRect method requests the text host to add a rectangle to the window's update region.

A standard rich edit control has a window procedure that processes system messages and messages from your application. You can use the control's window handle to send it messages for performing text editing and other operations. But a windowless rich edit control has no window procedure to receive and process messages. Instead, it provides an ITextServices interface. To send messages to a windowless rich edit control, call the ITextServices::TxSendMessage method. You can use this method to send any of the rich edit messages or to pass on other messages that affect the control, such as system messages for mouse or keyboard input.

You can also create the text services object as part of a COM-aggregated object. This makes it easy to aggregate the text services object with a windowless COM object.


Windowless Rich Edit Controls Reference

The following elements are used with windowless rich edit controls:

  • Windowless Rich Edit Control Functions
  • Windowless Rich Edit Control Interfaces


Windowless Rich Edit Control Functions

The following function is used with windowless rich edit controls.

Function | Description
CreateTextServices | Creates an instance of a text services object.


CreateTextServices

The CreateTextServices function creates an instance of a text services object. The text services object supports a variety of interfaces, including ITextServices and the Microsoft Text Object Model (TOM).

HRESULT CreateTextServices(
  IUnknown *punkOuter,   // controlling IUnknown
  ITextHost *pITextHost, // ITextHost implementation
  IUnknown **ppUnk       // private IUnknown
);

Parameters

punkOuter
[in] Pointer to the controlling IUnknown interface on the outer object if the text services object is being created as part of an aggregate object. This parameter can be NULL if the object is not part of an aggregate.
pITextHost
[in] Pointer to your implementation of the ITextHost interface. This pointer must not be NULL.
ppUnk
[out] Pointer to a variable that receives a pointer to the private IUnknown of the text services object. You can call QueryInterface on this pointer to retrieve ITextServices or ITextDocument interface pointers.

Return Values

If the text services object was created successfully, the return value is S_OK.

If the function fails, one of the following COM error codes are returned. For more information on COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | An invalid argument was passed in.
E_OUTOFMEMORY | Memory for text services object could not be allocated.
E_FAIL | The text services object could not be initialized.

Remarks

A text services object can be created as part of a standard COM-aggregated object. If it is, then callers should follow standard OLE32 rules for dealing with aggregated objects and caching interface pointers obtained through QueryInterface from the private IUnknown.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.
Library: Use Riched20.lib.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Functions, ITextDocument, ITextHost, ITextServices


Windowless Rich Edit Control Interfaces

The following interfaces are used with windowless rich edit controls.

Interface | Description
ITextHost | Used by a text services object to obtain text host services.
ITextServices | Extends the Microsoft Text Object Model to provide extra functionality for windowless operation.


ITextHost

The ITextHost interface is used by a text services object to obtain text host services.

When to Implement

You must implement the ITextHost interface before you call the CreateTextServices function.

When to Use

Applications do not call the ITextHost methods. A text services object created by the CreateTextServices function calls the interface methods.

Methods in Vtable Order

IUnknown Methods

QueryInterface
AddRef
Release

ITextHost Methods

Method | Description
OnTxCharFormatChange | Notifies the host that the default character format has changed.
OnTxParaFormatChange | Notifies the host that the default paragraph format has changed.
TxActivate | Notifies the text host that the text services object is active.
TxClientToScreen | Converts the client coordinates of a specified point to screen coordinates.
TxCreateCaret | Creates a new shape for the caret.
TxDeactivate | Notifies the text host that the text services object is inactive.
TxEnableScrollBar | Enables or disables the scroll bar arrows.
TxGetAcceleratorPos | Gets the accelerator character.
TxGetBackStyle | Gets the background style (either opaque or transparent).
TxGetCharFormat | Gets the default character format for the text.
TxGetClientRect | Retrieves the client coordinates of a window's client area.
TxGetDC | Gets the device context for the text host window.
TxGetExtent | Gets the native size of the control.
TxGetMaxLength | Gets the maximum length for the text.
TxGetParaFormat | Gets the default paragraph format for the text.
TxGetPasswordChar | Gets the character to display for password input.
TxGetPropertyBits | Gets the bit property settings for the text host.
TxGetScrollBars | Gets information about the scroll bars supported by the text host.
TxGetSelectionBarWidth | Returns the size of selection bar in HIMETRIC.
TxGetSysColor | Gets the color for the specified window display element.
TxGetViewInset | Gets the view rectangle relative to the inset.
TxImmGetContext | Retrieves the input method editor (IME) input context associated with the text services host. Asian-language versions only.
TxImmReleaseContext | Releases the IME input context. Asian-language versions only.
TxInvalidateRect | Invalidates a specified rectangle.
TxKillTimer | Destroys a timer.
TxNotify | Notifies the host of events.
TxReleaseDC | Releases the device context obtained from TxGetDC.
TxScreenToClient | Converts screen coordinates of a specified point to the client coordinates.
TxScrollWindowEx | Scrolls the content of the specified window's client area.
TxSetCapture | Sets mouse capture.
TxSetCaretPos | Sets the caret position.
TxSetCursor | Establishes a new cursor shape.
TxSetFocus | Sets the focus to the text window.
TxSetScrollPos | Sets the scroll position.
TxSetScrollRange | Sets the scroll range.
TxShowCaret | Shows or hides the caret.
TxShowScrollBar | Shows or hides the scroll bar.
TxSetTimer | Creates a timer with the specified time-out.
TxViewChange | Indicates to the text host that the update region has changed.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces


ITextHost::OnTxCharFormatChange

The ITextHost::OnTxCharFormatChange method sets the default character format for the text host.

HRESULT ITextHost::OnTxCharFormatChange(
  const CHARFORMAT *pcf
);

Parameters

pcf
[in] Pointer to a CHARFORMAT structure containing the new default-character format.

Return Values

Return S_OK if the method succeeds.

Return one of the following COM error codes if the method fails. For more information on COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | One or more arguments are invalid.
E_FAIL | Unspecified error.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , CHARFORMAT


ITextHost::OnTxParaFormatChange

The ITextHost::OnTxParaFormatChange method sets the default paragraph format for the text host.

HRESULT ITextHost::OnTxParaFormatChange(
  const PARAFORMAT *ppf
);

Parameters

ppf
[in] Pointer to a PARAFORMAT structure containing the new default paragraph format.

Return Values

Return S_OK if the method succeeds.

Return one of the following COM error codes if the method fails. For more information on COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | One or more arguments are invalid.
E_FAIL | Unspecified error.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , PARAFORMAT


ITextHost::TxActivate

The ITextHost::TxActivate method notifies the text host that the control is active.

HRESULT ITextHost::TxActivate(
  LONG *plOldState
);

Parameters

plOldState
Pointer to a variable that receives the previous activation state.

Return Values

Return S_OK if the method succeeds.

Return the following COM error code if the method fails. For more information on COM error codes, see Error Handling.

Value | Meaning
E_FAIL | Activation is not possible at this time.

Remarks

It is legal for the host to refuse an activation request; for example, the control may be minimized and thus invisible.

The caller should be able to gracefully handle failure to activate.

No matter how many times this method is called, only one TxDeactivate call is necessary to deactivate the control.

This function returns an opaque handle in plOldState. The caller (the text services object) should save this handle and use it in a subsequent call to TxDeactivate.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , ITextHost::TxDeactivate


ITextHost::TxClientToScreen

The ITextHost::TxClientToScreen method converts text host coordinates to screen coordinates.

BOOL ITextHost::TxClientToScreen(
  LPPOINT lppt
);

Parameters

lppt
[in] Pointer to a POINT structure containing the client coordinates to convert.

Return Values

Return TRUE if the method succeeds.

Return FALSE if the method fails.

Remarks

This call is valid at any time, although it is allowed to fail. In general, if the text services object needs to translate from client coordinates (for example, for the TOM ITextRange::GetPoint method) the text services object is visible.

However, if no conversion is possible, then the method fails.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , ITextRange::GetPoint, POINT


ITextHost::TxCreateCaret

The ITextHost::TxCreateCaret method creates a new shape for text host's caret.

BOOL ITextHost::TxCreateCaret(
  HBITMAP hbmp,
  INT xWidth,
  INT yHeight
);

Parameters

hbmp
[in] Handle to the bitmap for the new caret shape.
xWidth
[in] Caret width, in logical units.
yHeight
[in] Caret height, in logical units.

Return Values

Return TRUE if the method succeeds.

Return FALSE if the method fails.

Remarks

This method is only valid when the control is in-place active; calls while the control is inactive may fail.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , CreateCaret


ITextHost::TxDeactivate

The ITextHost::TxDeactivate method notifies the text host that the control is now inactive.

HRESULT ITextHost::TxDeactivate(
  LONG lNewState
);

Parameters

lNewState
New state of the control. Typically it is the value returned by TxActivate.

Return Values

Return S_OK if the method succeeds.

Return the following COM error code if the method fails. For more information on COM error codes, see Error Handling.

Value | Meaning
E_FAIL | Unspecified error.

Remarks

No matter how many times this method is called, only one call to TxActivate is necessary to activate the control.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , ITextHost::TxActivate


ITextHost::TxEnableScrollBar

The ITextHost::TxEnableScrollBar method enables or disables one or both scroll bar arrows in the text host window.

BOOL ITextHost::TxEnableScrollBar(
  INT fuSBFlags,
  INT fuArrowflags
);

Parameters

fuSBFlags
[in] Specifies which scroll bar is affected. This parameter can be one of the following values.
Value | Meaning
SB_BOTH | Affects both the horizontal and vertical scroll bars.
SB_HORZ | Affects the horizontal scroll bar.
SB_VERT | Affects the vertical scroll bar.

fuArrowflags
[in] Specifies which scroll bar 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

Return nonzero if the arrows are enabled or disabled as specified.

Return zero if the arrows are already in the requested state or an error occurs.

Remarks

This method is only valid when the control is in-place active; calls while the control is inactive may fail.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces


ITextHost::TxGetAcceleratorPos

The ITextHost::TxGetAcceleratorPos method requests the special character to use for the underlining accelerator character.

HRESULT ITextHost::TxGetAcceleratorPos(
  LONG *pcp
);

Parameters

pcp
Pointer to a variable that receives the character position of the character to underline. This variable is set by the text host. A character position of –1 (that is, negative one) indicates that no character should be underlined.

Return Values

The return value is S_OK.

Remarks

Accelerators allow keyboard shortcuts, or accelerator keys, to various UI elements (such as buttons). Typically, the shortcut character is underlined.

This method tells the text services object which character is the accelerator and thus should be underlined. Note that the text services object does not process accelerators; that is the responsibility of the host.

This method is typically only called if the TXTBIT_SHOWACCELERATOR bit is set in the text services object. See ITextServices::OnTxPropertyBitsChange.

Note Any change to the text in the text services object results in the invalidation of the accelerator underlining. In this case, it is the host's responsibility to recalculate the appropriate character position and inform the text services object that a new accelerator is available.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , ITextServices::OnTxPropertyBitsChange


ITextHost::TxGetBackStyle

The ITextHost::TxGetBackStyle method requests the background style of the text host.

HRESULT ITextHost::TxGetBackStyle(
  TXTBACKSTYLE *pstyle
);

Parameters

pstyle
Pointer to a variable that the text host sets to indicate the background style. The style is one of the values from the TXTBACKSTYLE enumeration.

Return Values

The return value is S_OK.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, TXTBACKSTYLE


ITextHost::TxGetCharFormat

The ITextHost::TxGetCharFormat method requests the text host's default character format.

HRESULT ITextHost::TxGetCharFormat(
  const CHARFORMAT **ppCF
);

Parameters

ppCF
Pointer to a variable in which the text host returns a pointer to a CHARFORMAT structure containing the default character format.

Return Values

Return S_OK if the method succeeds.

Return the following COM error code if the method fails. For more information on COM error codes, see Error Handling.

Value | Meaning
E_NOTIMPL | Not implemented.

Remarks

The text host retains ownership of the CHARFORMAT returned. However, the pointer returned must remain valid until the text host notifies the text services object through OnTxPropertyBitsChange that the default character format has changed.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , CHARFORMAT, OnTxPropertyBitsChange


ITextHost::TxGetClientRect

The ITextHost::TxGetClientRect method retrieves the client coordinates of the text host's client area.

HRESULT ITextHost::TxGetClientRect(
  LPRECT prc
);

Parameters

prc
Pointer to a RECT structure that the text host fills with the client coordinates of the text host's client area.

Return Values

Return S_OK if the method succeeds.

Return the following COM error code if the method fails. For more information on COM error codes, see Error Handling.

Value | Meaning
E_FAIL | Unspecified error.

Remarks

The client rectangle is the rectangle that the text services object is responsible for painting and managing. The host relies on the text services object for painting that area. And, the text services object must not paint or invalidate areas outside of that rectangle.

The host forwards mouse messages to the text services object when the cursor is over the client rectangle.

The client rectangle is expressed in client coordinates of the containing window.

IMPORTANT The TxGetClientRect method will fail if called at an inactive time.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, RECT


ITextHost::TxGetDC

The ITextHost::TxGetDC method requests the device context for the text host window.

HDC ITextHost::TxGetDC(void);

Parameters

This method has no parameters.

Return Values

If the method succeeds, return the handle of the device context for the client area of the text host window.

If the method fails, return NULL. For more information on COM error codes, see Error Handling.

Remarks

This method is only valid when the control is in-place active; calls while the control is inactive may fail.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , GetDC


ITextHost::TxGetExtent

The ITextHost::TxGetExtent method requests the native size of the control in HIMETRIC.

HRESULT ITextHost::TxGetExtent(
  LPSIZEL lpExtent
);

Parameters

lpExtent
Pointer to a SIZEL structure in which the text host returns the size of the control in HIMETRIC, that is, where the unit is .01 millimeter.

Return Values

Return S_OK if the method succeeds.

Return the following COM error code if the method fails. For more information on COM error codes, see Error Handling.

Value | Meaning
E_NOTIMPL | Not implemented.

Remarks

This method is used by the text services object to implement zooming. The text services object derives the zoom factor from the ratio between the himetric and device pixel extent of the client rectangle. Each HIMETRIC unit corresponds to 0.01 millimeter.

[vertical zoom factor] = [pixel height of the client rect] * 2540 / [HIMETRIC vertical extent] * [pixel per vertical inch (from device context)]

If the vertical and horizontal zoom factors are not the same, the text services object can ignore the horizontal zoom factor and assume it is the same as the vertical one.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , SIZEL


ITextHost::TxGetMaxLength

The ITextHost::TxGetMaxLength method gets the text host's maximum allowed length for the text.

HRESULT ITextHost::TxGetMaxLength(
  DWORD *pLength
);

Parameters

pLength
Pointer to a variable that the text host sets to the maximum allowed text length, in number of characters. If INFINITE is returned, the text services object can use as much memory as needed to store any specified text.

Return Values

The return value is S_OK.

Remarks

When this maximum is reached, the text services object should reject any further character insertion and pasted text. TxSetText however should still accept (and set) text longer than the maximum length. This is because this method is used for binding and is critical to maintaining the integrity of the data to which the control is bound.

This method parallels the EM_LIMITTEXT message.

If the limit returned is less than the number of characters currently in the text services object, no data is lost. Instead, no edits are allowed to the text other than deletion until the text is reduced to below the limit.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , EM_LIMITTEXT


ITextHost::TxGetParaFormat

The ITextHost::TxGetParaFormat method requests the text host's default paragraph format.

HRESULT ITextHost::TxGetParaFormat(
  const PARAFORMAT **ppPF
);

Parameters

ppPF
Pointer to a variable in which the text host returns a pointer to a PARAFORMAT structure containing the default paragraph format.

Return Values

Return S_OK if the method succeeds.

Return the following COM error code if the method fails. For more information on COM error codes, see Error Handling.

Value | Meaning
E_NOTIMPL | Not implemented.

Remarks

The host object retains ownership of the PARAFORMAT structure that is returned. However, the pointer returned must remain valid until the host notifies the text services object, through OnTxPropertyBitsChange, that the default paragraph format has changed.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , OnTxPropertyBitsChange, PARAFORMAT


ITextHost::TxGetPasswordChar

The ITextHost::TxGetPasswordChar method requests the text host's password character.

HRESULT ITextHost::TxGetPasswordChar(
  TCHAR *pch
);

Parameters

pch
Pointer to a variable that the text host sets to the password character.

Return Values

Return S_OK if the password character is enabled.

Return S_FALSE if the password character is not enabled. For more information on COM error codes, see Error Handling.

Remarks

The password character is only shown if the TXTBIT_USEPASSWORD bit is enabled in the text services object. If the password character changes, re-enable the TXTBIT_USEPASSWORD bit through OnTxPropertyBitsChange.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , OnTxPropertyBitsChange


ITextHost::TxGetPropertyBits

The ITextHost::TxGetPropertyBits method requests the bit property settings for the text host.

HRESULT ITextHost::TxGetPropertyBits(
  DWORD dwMask,
  DWORD *pdwBits
);

Parameters

dwMask
Mask of properties in which the caller is interested. This can be a combination of the rich edit control style bits.
pdwBits
Pointer to a variable that the text host sets to its current settings for the properties specified by dwMask.

Return Values

The return value is S_OK.

Remarks

This call is valid at any time, for any combination of requested property bits.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces


ITextHost::TxGetScrollBars

The ITextHost::TxGetScrollBars method requests information about the scroll bars supported by the text host.

HRESULT ITextHost::TxGetScrollBars(
  DWORD *pdwScrollBar
);

Parameters

pdwScrollBar
Pointer to a variable that the text host sets to indicate scroll bar support. This parameter can be a combination of the following window styles related to scroll bars.
Value | Meaning
WS_VSCROLL | Supports a vertical scroll bar.
WS_HSCROLL | Supports a horizontal scroll bar.
ES_AUTOVSCROLL | Automatically scrolls text up one page when the user presses ENTER on the last line.
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 ENTER, the control scrolls all text back to position zero.
ES_DISABLENOSCROLL | Disables scroll bars instead of hiding them when they are not needed.

Return Values

The return value is S_OK.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces


ITextHost::TxGetSysColor

The ITextHost::TxGetSysColor method retrieves the text host's color for a specified display element.

COLORREF ITextHost::TxGetSysColor(
  INT nIndex
);

Parameters

nIndex
[in] Specifies the display element whose color is to be retrieved. For a list of possible values for this parameter, see the GetSysColor function.

Return Values

The return value is a COLORREF value that identifies the red, green, and blue (RGB) color value of the specified element.

Remarks

Note that the color returned may be different than the color that would be returned from a call to GetSysColor. This is the case if the host overrides the default system behavior.

Note, hosts should be careful about overriding normal system behavior because it can result in inconsistent UI (particularly with respect to Accessibility options).

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , COLORREF, GetSysColor


ITextHost::TxGetViewInset

The ITextHost::TxGetViewInset method requests the dimensions of the white space inset around the text in the text host window.

HRESULT ITextHost::TxGetViewInset(
  LPRECT prc
);

Parameters

prc
Pointer to a RECT structure that the text host fills with the inset size, in client coordinates. The top, bottom, left, and right members of the RECT structure indicate how far in each direction the drawing should be inset.

Return Values

The return value is S_OK.

Remarks

The view inset is the amount of space on each side between the client rectangle and the view rectangle. The view rectangle (also called the Formatting rectangle) is the rectangle in which the text should be formatted .

The view insets are passed in a RECT structure, but this is not really a rectangle. It should be treated as four independent values to subtract on each side of the client rectangle to figure the view rectangle.

The view insets are passed in HIMETRIC (each HIMETRIC unit corresponds to 0.01 millimeter) so that they do not depend on the client rectangle and the rendering device context.

View insets can be negative on either side of the client rectangle, leading to a bigger view rectangle than the client rectangle. The text should then be clipped to the client rectangle. If the view rectangle is wider than the client rectangle, then the host may add a horizontal scroll bar to the control.

Single line–text services objects ignore the right boundary of the view rectangle when formatting text.

The view inset is available from the host at all times, active or inactive.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , RECT


ITextHost::TxInvalidateRect

The ITextHost::TxInvalidateRect method specifies a rectangle for the text host to add to the update region of the text host window.

void ITextHost::TxInvalidateRect(
  LPCRECT prc,
  BOOL fMode
);

Parameters

prc
[in] Pointer to a RECT structure that specifies the invalid rectangle.
fMode
[in] Specifies whether the background within the update region is to be erased when the update region is processed. If this parameter is TRUE, the background is erased when the BeginPaint function is called. If this parameter is FALSE, the background remains unchanged.

Return Values

This method has no return value.

Remarks

This function may be called while inactive; however, the host implementation is free to invalidate an area greater than the requested RECT.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , BeginPaint, RECT


ITextHost::TxKillTimer

The ITextHost::TxKillTimer method requests the text host to destroy the specified timer.

void ITextHost::TxKillTimer(
  UINT idTimer
);

Parameters

idTimer
[in] Identifier of the timer created by the TxSetTimer method.

Return Values

This method has no return value.

Remarks

This method may be called at any time, whether the control is active or inactive.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , ITextHost::TxSetTimer


ITextHost::TxNotify

The ITextHost::TxNotify method notifies the text host of various events.

HRESULT ITextHost::TxNotify(
  DWORD iNotify,
  void *pv
);

Parameters

iNotify
[in] Event to notify host of. One of the EN_ notification messages.
pv
[in] Extra data, dependent on iNotify.

Return Values

Return S_OK if the method succeeds.

Return S_FALSE if the method fails. For more information on COM error codes, see Error Handling.

Remarks

Note that there are two basic categories of events, direct and delayed . Direct events are sent immediately because they need some processing, for example, EN_PROTECTED. Delayed events are sent after all processing has occurred; the control is thus in a stable state. Examples of delayed notifications are EN_CHANGE, EN_ERRSPACE, and EN_SELCHANGE.

The notification events are the same as the notification messages sent to the parent window of a rich edit window. The firing of events may be controlled with a mask set through the EM_SETEVENTMASK message.

In general, it is legal to make calls to the text services object while processing this method; however, implementers are cautioned to avoid excessive recursion.

The following is a list of the notifications that may be sent.

Notification | Meaning
EN_CHANGE | Sent after the system updates the screen, when the user takes an action that may have altered text in the control.
EN_DROPFILES | Sent when either a WM_DROPFILES message or an IDropTarget::DragEnter notification is received.
EN_ERRSPACE | Sent when a control cannot allocate enough memory to meet a specified request.
EN_HSCROLL | Sent when the user clicks the control's horizontal scroll bar before the screen is updated.
EN_KILLFOCUS | Sent when the control loses the keyboard focus.
EN_LINK | Sent when a rich edit control receives various messages, such as mouse click messages, when the mouse pointer is over text that has the CFE_LINK effect.
EN_MAXTEXT | Sent when the current text insertion has exceeded the maximum number of characters for the control.
EN_OLEOPFAILED | Sent when a user action on an OLE object has failed.
EN_PROTECTED | Sent when the user takes an action that changes the protected range of text.
EN_REQUESTRESIZE | Sent when a rich edit control's contents are different from the control's window size.
EN_SAVECLIPBOARD | Sent when an edit control is being destroyed. The text host should indicate whether or not OleFlushClipboard should be called. Data indicating the number of characters and objects to be flushed is sent in the ENSAVECLIPBOARD data structure. Mask value is nothing.
EN_SELCHANGE | Sent when the current selection has changed. A SELCHANGE data structure is also sent, which indicates the new selection range at the type of data the selection is currently over. Controlled through the ENM_SELCHANGE mask.
EN_SETFOCUS | Sent when the edit control receives the keyboard focus. No extra data is sent; there is no mask.
EN_STOPNOUNDO | Sent when an action occurs for which the control cannot allocate enough memory to maintain the undo state. If S_FALSE is returned, the action will be stopped; otherwise, the action will continue.
EN_UPDATE | Sent before an edit control requests a redraw of altered data or text. No additional data is sent. This event is controlled through the ENM_UPDATE mask. Rich Edit 2.0 and later: The ENM_UPDATE mask is ignored and the EN_UPDATE notification message is always sent. However, when Rich Edit 3.0 emulates Rich Edit 1.0, the ENM_UPDATE mask controls this notification.
EN_VSCROLL | Sent when the user clicks an edit control's vertical scroll bar or when the user scrolls the mouse wheel over the edit control, before the screen is updated. This is controlled through the ENM_SCROLL mask; no extra data is sent.

Note The EN_MSGFILTER is not sent to TxNotify. To filter window messages, use ITextServices::TxSendMessage.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , EM_SETEVENTMASK, EN_CHANGE, EN_DROPFILES, EN_ERRSPACE, EN_HSCROLL, EN_KILLFOCUS, EN_LINK, EN_MAXTEXT, EN_OLEOPFAILED, EN_PROTECTED, EN_REQUESTRESIZE, EN_SAVECLIPBOARD, EN_SELCHANGE, EN_SETFOCUS, EN_STOPNOUNDO, EN_UPDATE, EN_VSCROLL


ITextHost::TxReleaseDC

The ITextHost::TxRelease DC method releases the device context obtained by the TxGetDC method.

INT ITextHost::TxReleaseDC(
  HDC hdc
);

Parameters

hdc
[in] Handle for the device context to release.

Return Values

Return 1 if hdc was released.

Return 0 if hdc was not released. For more information on COM error codes, see Error Handling.

Remarks

This method is only valid when the control is in-place active; calls while the control is inactive may fail.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces


ITextHost::TxGetSelectionBarWidth

The ITextHost::TxGetSelectionBarWidth method returns the size of selection bar in HIMETRIC.

HRESULT ITextHost::TxGetSelectionBarWidth(
  LONG *lSelBarWidth
);

Parameters

lSelBarWidth
Pointer to a variable that receives the width, in HIMETRIC (that is, where the units are .01 millimeter), of the selection bar.

Return Values

The return value is S_OK.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces


ITextHost::TxScreenToClient

The ITextHost::TxScreenToClient method converts the screen coordinates to the text host window coordinates.

BOOL ITextHost::TxScreenToClient(
  LPPOINT lppt
);

Parameters

lppt
[in] Pointer to a POINT structure containing the screen coordinates to convert.

Return Values

Return TRUE if the call succeeds.

Return FALSE if the call fails.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , POINT


ITextHost::TxScrollWindowEx

The ITextHost::TxScrollWindowEx method requests the text host to scroll the content of the specified client area.

void ITextHost::TxScrollWindowEx(
  INT dx,
  INT dy,
  LPCRECT lprcScroll,
  LPCRECT lprcClip,
  HRGN hrgnUpdate,
  LPRECT lprcUpdate,
  UINT fuScroll
);

Parameters

dx
[in] Amount of horizontal scrolling.
dy
[in] Amount of vertical scrolling.
lprcScroll
[in] Pointer to a RECT structure that contains the coordinates for the scroll rectangle.
lprcClip
[in] Pointer to a RECT structure that contains the coordinates for the clip rectangle.
hrgnUpdate
[in] Handle to the update region.
lprcUpdate
[in] Pointer to a RECT structure that contains the coordinates for the update rectangle.
fuScroll
[in] Scrolling flags.

Return Values

There is no return value.

Remarks

This method is only valid when the control is in-place active; calls while the control is inactive may fail.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , RECT


ITextHost::TxSetCapture

The ITextHost::TxSetCapture method sets the mouse capture in the text host's window.

void ITextHost::TxSetCapture(
  BOOL fCapture
);

Parameters

fCapture
[in] Indicates whether to set or release the mouse capture. If TRUE, the mouse capture is set. If FALSE, the mouse capture is released.

Return Values

There is no return value.

Remarks

This method is only valid when the control is in-place active; calls while the control is inactive may do nothing.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces


ITextHost::TxSetCaretPos

The ITextHost::TxSetCaretPos method moves the caret position to the specified coordinates in the text host window.

BOOL ITextHost::TxSetCaretPos(
  INT x,
  INT y
);

Parameters

x
[in] Horizontal position (in client coordinates).
y
[in] Vertical position (in client coordinates).

Return Values

Return TRUE if the method succeeds.

Return FALSE if the method fails.

Remarks

This method is only valid when the control is in-place active; calls while the control is inactive may fail.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces


ITextHost::TxSetCursor

The ITextHost::TxSetCursor method establishes a new cursor shape (I-beam) in the text host's window.

void ITextHost::TxSetCursor(
  HCURSOR hcur,
  BOOL fText
);

Parameters

hcur
[in] Handle to the cursor.
fText
[in] If TRUE, indicates the caller is trying to set the text cursor. See the Remarks section for more information.

Return Values

There is no return value.

Remarks

This method may be called at any time, whether the control is active or inactive.

TxSetCursor should be called by the text services object to set the mouse cursor. If the fText parameter is TRUE, the text services object is trying to set the text cursor (the cursor appears as an I-beam when it is over text that is not selected). In this case, the host can set it to whatever the control MousePointer property is. This is required for Microsoft® Visual Basic® compatibility since, through the MousePointer property, the VB programmer has control over the shape of the mouse cursor.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces


ITextHost::TxSetFocus

The ITextHost::TxSetFocus method sets the focus to the text host window.

void ITextHost::TxSetFocus(void);

Parameters

None.

Return Values

This method has no return value.

Remarks

This method is only valid when the control is in-place active; calls while the control is inactive may fail.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces


ITextHost::TxSetScrollPos

The ITextHost::TxSetScrollPos method tells the text host to set 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.

BOOL ITextHost::TxSetScrollPos(
  INT fnBar,
  INT nPos,
  BOOL fRedraw
);

Parameters

fnBar
[in] Scroll bar flag.
nPos
[in] New position in scroll box. This must be within the range of scroll bar values set by TxSetScrollRange.
fRedraw
[in] Redraw flag. If TRUE, the scroll bar is redrawn with the new position of the scroll box. If FALSE, the scroll bar is not redrawn.

Return Values

Return TRUE if the method succeeds.

Return FALSE if the method fails.

Remarks

This method is only valid when the control is in-place active; calls while the control is inactive may fail.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , ITextHost::TxSetScrollRange


ITextHost::TxSetScrollRange

The ITextHost::TxSetScrollRange method sets the minimum and maximum position values for the specified scroll bar in the text host window.

BOOL ITextHost::TxSetScrollRange(
  INT fnBar,
  LONG nMinPos,
  INT nMaxPos,
  BOOL fRedraw
);

Parameters

fnBar
[in] Scroll bar flag.
nMinPos
[in] Minimum scrolling position.
nMaxPos
[in] Maximum scrolling position.
fRedraw
Redraw flag. If TRUE, the scroll bar is redrawn to reflect the changes. If FALSE, the scroll bar is not redrawn.

Return Values

Return TRUE if the arrows are enabled or disabled as specified.

Return FALSE if the arrows are already in the requested state or an error occurs.

Remarks

This method is only valid when the control is in-place active; calls while the control is inactive may fail.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces


ITextHost::TxSetTimer

The ITextHost::TxSetTimer method requests the text host to create a timer with a specified time-out.

BOOL ITextHost::TxSetTimer(
  UINT idTimer,
  UINT uTimeout
);

Parameters

idTimer
[in] Timer identifier.
uTimeout
[in] Time-out in milliseconds.

Return Values

Return TRUE if the method succeeds.

Return FALSE if the method fails.

Remarks

idTimer is used in ITextHost::TxKillTimer.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , ITextHost::TxKillTimer


ITextHost::TxShowCaret

The ITextHost::TxShowCaret method shows or hides the caret at the caret position in the text host window.

BOOL ITextHost::TxShowCaret(
  BOOL fShow
);

Parameters

fShow
[in] Flag. If TRUE, the caret is visible. If FALSE, the caret is hidden.

Return Values

Return TRUE if the method succeeds.

Return FALSE if the method fails.

Remarks

This method is only valid when the control is in-place active; calls while the control is inactive may fail.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , ITextHost::TxCreateCaret, ITextHost::TxSetCaretPos


ITextHost::TxShowScrollBar

The ITextHost::TxShowScrollBar shows or hides the scroll bar in the text host window.

BOOL ITextHost::TxShowScrollBar(
  INT fnBar,
  BOOL fShow
);

Parameters

fnBar
[in] Specifies the scroll bar(s) to be shown or hidden.
fShow
[in] Flag. If TRUE, the scroll bar is visible. If FALSE, the scroll bar is hidden.

Return Values

Return TRUE if the method succeeds.

Return FALSE if the method fails.

Remarks

This method is only valid when the control is in-place active; calls while the control is inactive may fail.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces


ITextHost::TxImmGetContext

The ITextHost::TxImmGetContext method retrieves the input method editor (IME) input context associated with the text services host.

This method is used only in Asian-language versions of the operating system.

HIMC ITextHost::TxImmGetContext(void);

Parameters

This method has no parameters.

Return Values

Return the handle to the input context.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, TxImmReleaseContext


ITextHost::TxImmReleaseContext

The ITextHost::TxImmReleaseContext method releases an input context returned by the TxImmGetContext method and unlocks the memory associated with the context.

This method is used only in Asian-language versions of the operating system.

void ITextHost::TxImmReleaseContext(
  HIMC himc
);

Parameters

himc
[in] Handle to the input context.

Return Values

This method has no return value.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, TxImmGetContext


ITextHost::TxViewChange

The ITextHost::TxViewChange method indicates to the text host that the update region has changed.

void ITextHost::TxViewChange(
  BOOL fUpdate
);

Parameters

fUpdate
[in] Update flag. If TRUE, the text host calls UpdateWindow; otherwise it does nothing. See the Remarks section.

Return Values

This method has no return value.

Remarks

The text services object must call TxViewChange every time its visual representation has changed, even if the control is inactive. If the control is active, then text services must also make sure the control's window is updated. It can do this in a number of ways:

  • Call ITextHost::TxGetDC to get a device context for the control's window and then repaint or update the window. Afterwards, call ITextHost::TxReleaseDC.
  • Call ITextHost::TxInvalidateRect to invalidate the control's window .
  • Call ITextHost::TxScrollWindowEx to scroll the control's window.

After the text services object has updated the active view, it can call TxViewChange and set fUpdate to TRUE along with the call. By passing TRUE, the text host calls UpdateWindow to make sure any unpainted areas of the active control are repainted.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , ITextHost::TxGetDC, ITextHost::TxInvalidateRect, ITextHost::TxReleaseDC, ITextHost::TxScrollWindowEx, UpdateWindow


ITextServices

The ITextServices interface extends the Microsoft Text Object Model to provide extra functionality for windowless operation. In conjunction with the ITextHost interface, ITextServices provides the means by which a rich edit control can be used without creating a window.

When to Implement

Applications do not implement the ITextServices interface.

When to Use

Applications can call the CreateTextServices function to create a text services object. To retrieve an ITextServices pointer, call QueryInterface on the private IUnknown pointer returned by CreateTextServices. You can then call the ITextServices methods to send messages to the text services object.

Methods in Vtable Order

IUnknown Methods

QueryInterface
AddRef
Release

ITextServices Methods

Method | Description
OnTxInPlaceActivate | Notifies the text services object that this control is in-place active.
OnTxInPlaceDeactivate | Notifies the text services object that this control is no longer in-place active.
OnTxPropertyBitsChange | Bulk bit property change notifications.
OnTxSetCursor | Sets cursor.
OnTxUIActivate | Informs text services object that the control in now UI active..
OnTxUIDeactivate | Informs the text services object that the control is no longer UI active.
TxDraw | Draws the text services objectRendering
TxGetBaseLinePos | Gets the base line position of the first visible line relative to the text services client rectangle.
TxGetCachedSize | Returns the cached drawing size.
TxGetCurTargetX | Gets the target x position of the caret.
TxGetDropTarget | Gets the drop target for the text control.
TxGetHScroll | Returns horizontal scroll bar information.
TxGetNaturalSize | Resizes the control to fit the content appropriately.
TxGetText | Gets text in the control.
TxGetVScroll | Returns vertical scroll bar information.
TxQueryHitPoint | Tests whether a point is within the rectangle of the text services object.
TxSendMessage | Sends messages from the text host window to the text services object.
TxSetText | Sets text in control.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces


ITextServices::TxGetCachedSize

The ITextServices::TxGetCachedSize method returns the cached drawing size (if any) that text services is using. Typically, this will be the size of the last client rectangle used in TxDraw, OnTxSetCursor, and so forth, although it is not guaranteed to be.

HRESULT ITextServices::TxGetCachedSize(
  DWORD *pdwWidth,
  DWORD *pdwHeight
);

Parameters

pdwWidth
[in] Pointer to a variable that holds the width (in client coordinates).
pdwHeight
[in] Pointer to a variable that holds the height (in client coordinates).

Return Values

If the method succeeds, the return value is an HRESULT code.

Remarks

This method can free the host from the need to maintain the cached drawing size information and the need to keep in synchronization.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , TxDraw, OnTxSetCursor


ITextServices::OnTxInPlaceActivate

The ITextServices::OnTxInPlaceActivate method notifies the text services object that this control is in-place active

HRESULT ITextServices::OnTxInPlaceActivate(
  const RECT *prcClient
);

Parameters

prcClient
[in] Pointer to a RECT structure containing the control's client rectangle.

Return Values

If the object is successfully activated, the return value is S_OK.

If the object could not be activated due to error, the return value is E_FAIL. For more information on COM error codes, see Error Handling.

Remarks

In-place active means that an embedded object is running in-place (for example, for regular controls and embeddings, it would have a window to draw in). In contrast, UI active means that an object currently has the editing focus. For example, things like menus and toolbars on the container may also contain elements from the UI-active control/embedding. There is only one UI-active control at any given time, while there can be many in-place active controls.

Note, UI activation is different from getting the focus. To signal the text services object know that the control is getting or losing focus, the host sends WM_SETFOCUS and WM_KILLFOCUS messages. Also, note that a windowless host will pass NULL as the wParam (window that lost the focus) for these messages.

When making the transition directly from a nonactive state to the UI-active state, the host should call OnTxInPlaceActivate first and then OnTxUIActivate.

OnTxInPlaceActivate takes as a parameter the client rectangle of the view being activated. This rectangle is given in client coordinates of the containing window. It is the same as would be obtained by calling TxGetClientRect on the host.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , ITextHost::TxGetClientRect, ITextServices::OnTxUIActivate, RECT, WM_KILLFOCUS, WM_SETFOCUS


ITextServices::OnTxInPlaceDeactivate

The ITextServices::OnTxInPlaceDeactivate method notifies the text services object that this control is no longer in-place active.

HRESULT ITextServices::OnTxInPlaceDeactivate(void);

Parameters

This method has no parameters.

Return Values

Currently, the return value is always S_OK.

Remarks

In-place activation refers to an embedded object running in-place (for example, for regular controls and embeddings, it would have a window to draw in). In contrast, UI active means that an object currently has the editing focus. Specifically, things like menus and toolbars on the container may also contain elements from the UI-active control/embedding. There can only be one UI-active control at any given time, while many can be in-place active at once.

Note, UI activation is different from getting the focus. To let the text services object know that the control is getting or losing focus, the host will send WM_SETFOCUS and WM_KILLFOCUS messages. Also, note that a windowless host will pass NULL as the wParam (window that lost the focus) for these messages.

When making the transition from the UI-active state to a nonactive state, the host should call OnTxUIDeactivate first and then OnTxInPlaceDeactivate.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, ITextServices::OnTxUIDeactivate, WM_KILLFOCUS, WM_SETFOCUS


ITextServices::OnTxPropertyBitsChange

The ITextServices::OnTxPropertyBitsChange method sets properties (represented by bits) for the control.

HRESULT ITextServices::OnTxPropertyBitsChange(
  DWORD dwMask,
  DWORD dwBits
);

Parameters

dwMask
[in] Bits representing properties to be changed. For the possible bit values, see the TXTBIT_* values list in dwBits.
dwBits
[in] New values for bit properties. It can be any combination of the following.
Value | Meaning
TXTBIT_ALLOWBEEP | If TRUE, beeping is enabled.
TXTBIT_AUTOWORDSEL | If TRUE, the AutoWordSelect feature is enabled.
TXTBIT_BACKSTYLECHANGE | If TRUE, the backstyle changed. See TXTBACKSTYLE.
TXTBIT_CHARFORMATCHANGE | If TRUE, the character format changed.
TXTBIT_CLIENTRECTCHANGE | If TRUE, the client rectangle changed.
TXTBIT_DISABLEDRAG | If TRUE, dragging is disabled.
TXTBIT_EXTENTCHANGE | If TRUE, the size of the client rectangle changed.
TXTBIT_HIDESELECTION If TRUE, the text services object should hide the selection when the control is inactive. If FALSE, the selection should be displayed when the control is inactive.

Note, this implies TXTBIT_SAVESELECTION is TRUE.
TXTBIT_MAXLENGTHCHANGE | If TRUE, the maximum length for text in the control changed.
TXTBIT_MULTILINE If TRUE, the text services object should work in multiline mode. Use the TXTBIT_WORDWRAP value to determine whether to wrap the lines to the view rectangle or clip them.

If FALSE, the text services object should not process the CR key and it should truncate incoming text containing hard line breaks just before the first line break. It is also acceptable to truncate text that is set with ITextServices::TxSetText, because it is the responsibility of the host not to use a single-line control when bound to a multiline field.
TXTBIT_PARAFORMATCHANGE | If TRUE, the paragraph format changed.
TXTBIT_READONLY | If TRUE, the text services object should not accept any editing change through the user interface. However, it should still accept programmatic changes through EM_SETTEXT, EM_REPLACETEXT, and ITextServices::TxSetText. Also, the user should still be able to move the insertion point, select text, and carry out other noncontent-modifying operations, such as Copy.
TXTBIT_RICHTEXT If TRUE, the text services object should be in rich-text mode.

If FALSE, it is in plain-text mode.

Note, this affects how editing commands are applied. For example, applying bold to part of the text in a plain-edit control makes the entire text bold. However, for a rich-edit control, this makes only the selected text bold.
TXTBIT_SAVESELECTION If TRUE, the boundaries of the selection should be saved when the control is inactive.

If FALSE, when the control goes active again the selection boundaries can be reset to start = 0, length = 0.
TXTBIT_SCROLLBARCHANGE | If TRUE, the scroll bar has changed.
TXTBIT_SELBARCHANGE | If TRUE, the selection bar width has changed
TXTBIT_SHOWACCELERATOR If set, the accelerator character should be underlined.

This must be set in order to call ITextHost::TxGetAcceleratorPos.
TXTBIT_USECURRENTBKG | Not currently implemented.
TXTBIT_USEPASSWORD If TRUE, display text using the password character obtained by TxGetPasswordChar.

The notification on this property can mean either that the password character changed or that the password character was not used before but it used now (or vice versa).
TXTBIT_VERTICAL | Not currently implemented.
TXTBIT_VIEWINSETCHANGE | If TRUE, the inset changed.
TXTBIT_WORDWRAP If TRUE and TXTBIT_MULTILINE is also TRUE, multiline controls should wrap the line to the view rectangle. If this property is FALSE and TXTBIT_MULTILINE is TRUE, the lines should not be wrapped but clipped. The right side of the view rectangle should be ignored.

If TXTBIT_MULTILINE is FALSE, this property has no effect.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value is the following HRESULT code. For more information on COM error codes, see Error Handling.

Value | Meaning
E_NOTIMPL | Not implemented.

Remarks

The client rectangle is the rectangle that the text services object is responsible for painting and managing. The host relies on the text services object for painting that area. The text services object must not paint or invalidate areas outside of that rectangle. In addition, the host will forward mouse messages to the text services object when the cursor is over this rectangle. This rectangle is expressed in client coordinates of the containing window.

The view inset is the amount of space on each side between the client rectangle and the view rectangle. The view rectangle (also called the Formatting rectangle) is the rectangle in which the text should be formatted . For more information, see ITextHost::TxGetViewInset.

The backstyle is the style of the background of the client rectangle. It can be either TXTBACK_TRANSPARENT or TXTBACK_SOLID. See TXTBACKSTYLE.

The scroll bar property indicates changes to the scroll bar: which scroll bar is present, whether scroll bars are hidden or disabled when scrolling is impossible, and also if auto-scrolling is enabled when the insertion point gets off the client rectangle.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, ITextHost::TxGetAcceleratorPos, ITextHost::TxGetClientRect, ITextHost::TxGetPasswordChar, ITextServices::TxSetText, RECT, TXTBACKSTYLE


ITextServices::OnTxSetCursor

The ITextServices::OnTxSetCursor method notifies the text services object to set the cursor.

HRESULT ITextServices::OnTxSetCursor(
  DWORD dwDrawAspect,
  LONG lindex,
  void *pvAspect,
  DVTARGETDEVICE *ptd,
  HDC hdcDraw,
  HDC hicTargetDev,
  LPCRECT lprcClient,
  INT x,
  INT y
);

Parameters

dwDrawAspect
[in] Draw aspect can be one of the following values.
Value Meaning
DVASPECT_CONTENT Renders a screen image of the text content to the hdcDraw device context.

The hicTargetDev and ptd parameters give information on the target device context if any (usually a printer).
DVASPECT_DOCPRINT Renders the object to the hdcDraw device context as though it were printed to a printer. Thus, the text services object can optimize for the printer (for example, not painting the background color, if white). Also, certain screen-specific elements (such as the selection) should not be rendered.

OnTxSetCursor should render the lprcBounds rectangle, starting at the current scrolling position.

lindex
Currently unused.
pvAspect
[in] Information for drawing optimizations.
ptd
[in] Pointer to a DVTARGETDEVICE structure containing information on the target device.
hdcDraw
[in] Rendering device context.
hicTargetDev
[in] Target information context.
lprcClient
[in] Pointer to a RECT structure containing the control's client rectangle. The coordinates of the rectangle are in client coordinates of the containing window. NULL is a legal value.
x
[in] x position of cursor, in the client coordinates of the containing window.
y
[in] y position of cursor, in the client coordinates of the containing window.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value is the following HRESULT code. For more information on COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | One or more illegal parameters.

Remarks

The text services object may remeasure as a result of this call to determine the correct cursor. The correct cursor is set through ITextHost::TxSetCursor.

The lprcClient parameter is the client rectangle of the view of the control over which the mouse cursor is positioned. The lprcClient parameter is in device coordinates of the containing window in the same way the WM_SIZE message is. This may not be the view that was rendered last. Furthermore, if the control is in-place active, this may not be the current active view . As a consequence, the text services object should check this rectangle against its current caches value and determine whether recalculating the lines is necessary or not. The zoom factor should be included in this computation. For a discussion of the zoom factor, see ITextHost::TxGetExtent.

This method should be called only for screen views of the control. Therefore the device context is not passed in, but should be assumed to be a screen DC.

For more information, see the Remarks in ITextServices::TxDraw.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , ITextServices::TxDraw, ITextHost::TxGetExtent, ITextHost::TxSetCursor, WM_SIZE


ITextServices::OnTxUIActivate

The ITextServices::OnTxUIActivate method informs the text services object that the control is now UI active.

HRESULT ITextServices::OnTxUIActivate(void);

Parameters

This method has no parameters.

Return Values

Currently, the method always returns S_OK.

Remarks

See OnTxInPlaceActivate for a detailed description of activation.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, OnTxInPlaceActivate


ITextServices::OnTxUIDeactivate

The ITextServices::OnTxUIDeactivate method informs the text services object that the control is no longer UI active.

HRESULT ITextServices::OnTxUIDeactivate(void);

Parameters

This method has no parameters.

Return Values

Currently, the method always returns S_OK.

Remarks

See OnTxInPlaceActivate for a detailed description of deactivation.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, OnTxInPlaceActivate


ITextServices::TxDraw

The ITextServices::TxDraw method draws the text services object.

HRESULT ITextServices::TxDraw(
  DWORD dwDrawAspect,
  LONG lindex,
  void *pvAspect,
  DVTARGETDEVICE *ptd,
  HDC hdcDraw,
  HDC hicTargetDev,
  LPCRECTL lprcBounds,
  LPCRECTL lprcWBounds,
  LPRECT lprcUpdate,
  BOOL (CALLBACK *pfnContinue),
  DWORD dwContinue,
  LONG lViewId
);

Parameters

dwDrawAspect
[in] Specifies the aspect to be drawn, that is, how the object is to be represented. Draw aspect can be one of the following values.
Value Meaning
DVASPECT_CONTENT Renders a screen image of the text content to the hdcDraw device context.

The hicTargetDev and ptd parameters give information on the target device context if any (usually a printer).
DVASPECT_DOCPRINT Renders the object to the hdcDraw device context as though it were printed to a printer. Thus, the text services object can optimize for the printer (for example, not painting the background color, if white). Also, certain screen-specific elements (such as the selection) should not be rendered.

TxDraw should render the lprcBounds rectangle, starting at the current scrolling position.

lindex
Currently unused.
pvAspect
[in] Pointer for information for drawing optimizations.
ptd
[in] Pointer to a DVTARGETDEVICE structure containing information on the target device.
hdcDraw
[in] Rendering device context.
hicTargetDev
[in] Target information context.
lprcBounds
[in] Pointer to a RECTL structure containing the bounding (client) rectangle.
lprcWBounds
[in] Pointer to a RECTL structure containing the clipping rectangle for metafiles.
lprcUpdate
[in] Pointer to a RECT structure containing the update region inside lprcBounds.
CALLBACK * pfnContinue
Currently unused.
dwContinue
Parameter to pass to continue function.
lViewId
Currently unused.

Return Values

The return value is typically S_OK.

Remarks

This method renders the text services object. It accepts the same parameters as the corresponding IViewObject::Draw method in OLE, with the extra lprcUpdate and the lViewId parameters. It can be used while the host is in-place active or inactive.

The lprcBounds parameter gives the rectangle to render, also called the client rectangle. This rectangle represents the position and extent of the entire image of the text services object to be drawn. It is expressed in the logical coordinate system of hdcDraw. If lprcBounds is NULL then the control must be active. In this case, the text services object should render the in-place active view (that is, the client rectangle that can be obtained by calling TxGetClientRect on the host).

If the lprcUpdate parameter is not NULL, it gives the rectangle to update inside that client rectangle, in the logical coordinate system of hdcDraw. If lprcUpdate is NULL, the entire client rectangle should be painted.

The text services object should render with the appropriate zoom factor, which can be obtained from the client rectangle and the native size given by ITextHost::TxGetExtent. For a discussion of the zoom factor, see ITextHost::TxGetExtent.

General comments on OLE hosts and TxDraw (also for OnTxSetCursor, and TxQueryHitPoint):

An OLE host can call the TxDraw method at any time with any rendering device context or client rectangle. An OLE object that is inactive only retains an extent. To get the rectangle in which to render, the host calls the IViewObject::Draw method. This rectangle is valid only for the scope of that method. Thus, the same control can be rendered consecutively in different rectangles and different device contexts, for example, because it is displayed simultaneously in different views on the screen.

Normally, the client rectangle and device context passed to TxDraw should not be cached, because this would force the text services object to recalculate lines for every draw, which would impede performance. Instead, the text services object could cache the information that is computed for a specific client rectangle and device context (such as line breaks). On the next call to TxDraw, however, the validity of the cached information should be checked before it gets used, and updated information should be regenerated, if necessary.

Also, take great care when the control is in-place active. This problem is even more complex since TxDraw can still be called to render other views than the one that is in-place active. In other words, the client rectangle passed to TxDraw may not be the same as the active one (passed to OnTxInPlaceActivate and obtained through TxGetClientRect on the host).

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , DVTARGETDEVICE, ITextHost::TxGetClientRect, ITextHost::TxGetExtent, ITextServices::OnTxInPlaceActivate, IViewObject::Draw, RECT, RECTL


ITextServices::TxGetBaseLinePos

The ITextServices::TxGetBaseLinePos method gets the base line position of the first visible line, in pixels, relative to the text services client rectangle. This permits aligning controls on their base lines.

HRESULT ITextServices::TxGetBaseLinePos(
  LONG *pBaseLinePos
);

Parameters

pBaseLinePos
Pointer to a variable that receives the base line position of the first visible line.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value is the following HRESULT code. For more information on COM error codes, see Error Handling.

Value | Meaning
E_NOTIMPL | Not implemented.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces


ITextServices::TxGetCurTargetX

The ITextServices::TxGetCurTargetX method gets the target x position, that is, the current horizontal position of the caret.

HRESULT ITextServices::TxGetCurTargetX(
  LONG *px
);

Parameters

px
Pointer to a variable that receives the target x location in client coordinates.

Return Values

If the x position of the caret is returned, the return value is S_OK.

If the method fails the return value is the following HRESULT code. For more information on COM error codes, see Error Handling.

Value | Meaning
E_FAIL | There is no selection.
E_INVALIDARG | The input argument is invalid.

Remarks

Together with OnTxSetCursor, this method allows you to maintain the horizontal caret position when moving the caret up and down. This capability is useful when moving the caret through forms.

The target caret position is expressed as an x-coordinate on the display because other controls do not necessarily share the same attributes for column position.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , ITextServices::OnTxSetCursor


ITextServices::TxGetDropTarget

The ITextServices::TxGetDropTarget method gets the drop target for the text control.

HRESULT ITextServices::TxGetDropTarget(
  IDropTarget **ppDropTarget
);

Parameters

ppDropTarget
Pointer to a variable that receives a pointer to the IDropTarget interface on the object that is the target of a drag-and-drop operation in a specified window.

Return Values

If the method got the drop target successfully, the return value is S_OK.

If the method fails, the return value is the following HRESULT code. For more information on COM error codes, see Error Handling.

Value | Meaning
E_OUTOFMEMORY | Could not create the drop target.

Remarks

The host (caller) is responsible for calling RegisterDragDrop or RevokeDragDrop, and for calling IUnknown::Release on the returned drop target when done.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , RegisterDragDrop, RevokeDragDrop, IDropTarget, IUnknown::Release


ITextServices::TxGetHScroll

The ITextServices::TxGetHScroll method returns horizontal scroll bar information.

HRESULT ITextServices::TxGetHScroll(
  LONG *plMin,
  LONG *plMax,
  LONG *plPos,
  LONG *plPage,
  BOOL *pfEnabled
);

Parameters

plMin
Pointer to a variable that receives the minimum scroll position.
plMax
Pointer to a variable that receives the maximum scroll position.
plPos
Pointer to a variable that receives the current scroll position.
plPage
Pointer to a variable that receives the view width, in pixels.
pfEnabled
Pointer to a BOOL that indicates whether horizontal scrolling is enabled. If TRUE, horizontal scrolling is enabled.

Return Values

Currently, the method always returns S_OK.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces


ITextServices::TxGetNaturalSize

The ITextServices::TxGetNaturalSize method allows a control to be resized so it fits its content appropriately.

HRESULT ITextServices::TxGetNaturalSize(
  DWORD dwAspect,
  HDC hdcDraw,
  HDC hicTargetDev,
  DVTARGETDEVICE *ptd,
  DWORD dwMode,
  const SIZEL *psizelExtent,
  LONG *pwidth,
  LONG *pheight
);

Parameters

dwAspect
The aspect for the drawing. It can be any of the values from the OLE DVASPECT enumeration.
hdcDraw
The device context into which drawing occurs.
hicTargetDev
The device context for which text should be formatted (that is, for WYSIWYG).
ptd
Pointer to a DVTARGETDEVICE structure that contains more information on the target device.
dwMode
The type of fitting requested. It can be one of the following.
Value Meaning
TXTNS_FITTOCONTENT Resize the control to fit the entire text by formatting the text to the width that is passed in. The text services object returns the height of the entire text and the width of the widest line.

For example, this should be done when the user double-clicks one of the control's handles.
TXTNS_ROUNDTOLINE Resize the control to show an integral number of lines (no line is clipped). Format enough text to fill the width and height that is passed in, and then return a height that is rounded to the nearest line boundary.

Note, the passed and returned width and height correspond to the view rectangle. The host should adjust back to the client rectangle as needed. Becaue these values represent the extent of the text object, they are input and output in HIMETRIC coordinates (each HIMETRIC unit is .01 millimeter), and measuring does not include any zoom factor. For a discussion of the zoom factor, see ITextHost::TxGetExtent.

psizelExtent
Currently unused.
pwidth
[in/out] Pointer to a variable that contains the width for the fitting defined by dwMode.
pheight
[in/out] Pointer to a variable that contains the height for the fitting defined by dwMode.

Return Values

If the method succeeds, the return value is S_OK.

If text services could not activate the object, the return value is one of the following HRESULT codes. For more information on COM error codes, see Error Handling.

Value | Meaning
E_FAIL | Unable to determine correct size.
E_INVALIDARG | One or more arguments are invalid.
E_OUTOFMEMORY | Insufficient memory.

Remarks

The first four parameters are similar to equivalent parameters in TxDraw and give the same information. In the case where the lines must be recalculated, it should use these values the same ways as in TxDraw.

The pWidth and pHeight parameters are in/out parameters. The host passes in the tentative width and height of the natural extent of the text object. The text services object compares these values against its current cached state, and if different, recalculate lines. Then, it computes and returns the natural size, as specified by dwMode.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, , DVTARGETDEVICE, ITextHost::TxGetExtent, ITextServices::TxDraw


ITextServices::TxGetText

The ITextServices::TxGetText method returns all of the UNICODE plain text in the control as an OLE BSTR.

HRESULT ITextServices::TxGetText(
  BSTR *pbstrText
);

Parameters

pbstrText
Pointer to the BSTR that receives the Unicode plain text.

Return Values

If the text is successfully returned in the output argument, the return value is S_OK.

If the method fails, the return value is one of the following HRESULT codes. For more information on COM error codes, see Error Handling.

Value | Meaning
E_INVALIDARG | Invalid BSTR pointer passed in.
E_OUTOFMEMORY | Could not allocate memory for copy of the text.

Remarks

The host (caller) takes ownership of the returned BSTR.

Other ways to retrieve plain text data are to use WM_GETTEXT or the TOM ITextRange::GetText method.

If there is no text in the control, no BSTR will be allocated and NULL will be returned.

The returned text will not necessarily be NULL terminated.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, ITextRange::GetText, WM_GETTEXT, BSTR


ITextServices::TxGetVScroll

The ITextServices::TxGetVScroll method returns vertical scroll bar state information.

HRESULT ITextServices::TxGetVScroll(
  LONG *plMin,
  LONG *plMax,
  LONG *plPos,
  LONG *plPage,
  BOOL *pfEnabled
);

Parameters

plMin
Pointer to a variable that receives the minimum scroll position.
plMax
Pointer to a variable that receives the maximum scroll position.
plPos
Pointer to a variable that receives the current scroll position.
plPage
Pointer to a variable that receives the height of view in pixels.
pfEnabled
Pointer to a BOOL that indicates whether the vertical scroll bar is enabled. If TRUE, the vertical scroll bar is enabled; otherwise it is disabled.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value is one of the following HRESULT codes. For more information on COM error codes, see Error Handling.

Value | Meaning
E_FAIL | Unspecified error.
E_INVALIDARG | One or more arguments are invalid.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces


ITextServices::TxQueryHitPoint

The ITextServices::TxQueryHitPoint method tests whether a specified point is within the rectangle of the text services object.

HRESULT ITextServices::TxQueryHitPoint(
  DWORD dwDrawAspect,
  LONG lindex,
  void *pvAspect,
  DVTARGETDEVICE *ptd,
  HDC hdcDraw,
  HDC hicTargetDev,
  LPCRECT lprcClient,
  INT x,
  INT y,
  DWORD *pHitResult
);

Parameters

dwDrawAspect
[in] Draw aspect can be one of the following values.
Value Meaning
DVASPECT_CONTENT Renders a screen image of the text content to the hdcDraw device context.

The hicTargetDev and ptd parameters give information on the target device context if any (usually a printer).
DVASPECT_DOCPRINT Renders the object to the hdcDraw device context as though it were printed to a printer. Thus, the text services object can optimize for the printer (for example, not painting the background color, if white). Also, certain screen-specific elements (such as the selection) should not be rendered.

TxGetNaturalSize should render the lprcBounds rectangle, starting at the current scrolling position.

lindex
Currently unused.
pvAspect
[in] Information for drawing optimizations.
ptd
[in] Pointer to a DVTARGETDEVICE structure containing information on the target device.
hdcDraw
[in] Rendering device context.
hicTargetDev
[in] Target information context.
lprcClient
Pointer to a RECT structure that contains the control's client rectangle, in client (device) coordinates of the view in which the hit testing is done.
x
x coordinate to check, in client coordinates of the view in which hit testing is done.
y
y coordinate to check, in client coordinates of the view in which hit testing is done.
pHitResult
Pointer to a variable that receives the result of the hit test. It can be any of the TXTHITRESULT enumeration values.
Value | Meaning
TXTHITRESULT_CLOSE | The point is in the client rectangle and close to a nontransparent area.
TXTHITRESULT_HIT | The point is in the client rectangle and either over text or the background is not transparent.
TXTHITRESULT_NOHIT | The point is outside of the client rectangle.
TXTHITRESULT_TRANSPARENT | The point is in the client rectangle and either not over text or the background was transparent.

Return Values

The return value is an HRESULT code.

Remarks

This method allows the host to implement transparent hit testing on text.

For more information, see the Remarks section in ITextService::TxDraw and and OnTxSetCursor.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, ITextServices::OnTxSetCursor, ITextServices::TxDraw


ITextServices::TxSendMessage

The ITextServices::TxSendMessage method is used by the window host to forward messages sent from its window to the text services object.

HRESULT ITextServices::TxSendMessage(
  UINT msg,
  WPARAM wparam,
  LPARAM lparam,
  LRESULT *plresult
);

Parameters

msg
The message identifier.
wparam
The WPARAM from the window's message.
lparam
The LPARAM from the window's message.
plresult
Pointer to a variable that receives the message's return LRESULT.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value is one of the following HRESULT codes. For more information on COM error codes, see Error Handling.

Value | Meaning
E_OUTOFMEMORY | Insufficient memory. NOERROR Message was processed, and some action was taken.
S_FALSE | Message was not processed. Typically indicates that the caller should process the message itself, potentially by calling DefWindowProc.
S_MSG_KEYIGNORED | Message processed, but no action was taken for the keystroke.

Remarks

Note that two return values are passed back from this function. The return value that should be passed back from a window procedure is plresult. However, in some cases, the returned LRESULT does not contain enough information. For example, to implement moving the cursor around controls, it's useful to know if a keystroke (such as right arrow) was processed but ignored (for example, the caret is already at the rightmost position in the text). In these cases, more information may be returned through the returned HRESULT.

WM_CHAR and WM_KEYDOWN should return the value S_MSG_KEYIGNORED when a key or character is recognized, but has no effect, given the current state. For example, S_MSG_KEYIGNORED should be returned in the following cases:

  • Any keystroke that tries to move the insertion point to or beyond the beginning or the end of the document; when it is already at the beginning or end of the document, respectively.
  • Any keystroke that tries to move the insertion point to or past the next line when it is already on the last line; or to or before the previous line when it is already on the first line.
  • Any insertion of the character from WM_CHAR that would move the insertion point past the maximum length of the control.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, DefWindowProc, WM_CHAR, WM_KEYDOWN


ITextServices::TxSetText

The ITextServices::TxSetText method sets all of the text in the control.

HRESULT ITextServices::TxSetText(
  LPCTSTR pszText
);

Parameters

pszText
[in] Pointer to a string which will replace the current text.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value is the following HRESULT code. For more information on COM error codes, see Error Handling.

Value | Meaning
E_FAIL | Text could not be updated.

Remarks

This method should be used with care; it essentially reinitializes the text services object with some new data. Any previous data and formatting information will be lost, including undo information.

If previous data has been copied to the clipboard, that data will be rendered completely to the clipboard (through OleFlushClipboard) before it is discarded.

This method does not support Undo.

Two alternate approaches to setting text are WM_SETTEXT and ITextRange::SetText.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Interfaces, ITextRange::SetText, OleFlushClipboard, WM_SETTEXT


Windowless Rich Edit Control Enumeration Types

The following enumeration types are used with windowless rich edit controls.

TXTBACKSTYLE
TXTHITRESULT
TXTNATURALSIZE


TXTBACKSTYLE

The TXTBACKSTYLE enumeration type defines different background styles.

enum TXTBACKSTYLE {
  TXTBACK_TRANSPARENT,
  TXTBACK_OPAQUE
};

Enumeration Values

TXTBACK_TRANSPARENT
Background shows through.
TXTBACK_OPAQUE
Background does not show through.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Enumeration Types, ITextHost::TxGetBackStyle


TXTHITRESULT

The TXTHITRESULT enumeration type defines different hit results.

enum TXTHITRESULT {
  TXTHITRESULT_NOHIT,
  TXTHITRESULT_TRANSPARENT,
  TXTHITRESULT_CLOSE,
  TXTHITRESULT_HIT
};

Enumeration Values

TXTHITRESULT_NOHIT
No hit.‹ Point is outside the client rectangle.›
TXTHITRESULT_TRANSPARENT
Point is within the text's rectangle, but in a transparent region.
TXTHITRESULT_CLOSE
Point is close to the text.
TXTHITRESULT_HIT
Dead-on hit.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Enumeration Types, ITextServices::TxQueryHitPoint


TXTNATURALSIZE

The TXTNATURALSIZE enumeration type defines values for TxGetNaturalSize.

enum TXTNATURALSIZE {
  TXTNS_FITTOCONTENT,
  TXTNS_ROUNDTOLINE
};

Enumeration Values

TXTNS_FITTOCONTENT
Gets a size that fits the content.
TXTNS_ROUNDTOLINE
Rounds to the nearest whole line.

Requirements

Version: Requires Rich Edit 2.0 or later.
Header: Declared in Textserv.h.

See Also

Windowless Rich Edit Controls Overview, Windowless Rich Edit Control Enumeration Types, ITextServices::TxGetNaturalSize


Scroll Bars

A window in a 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
  • Using Scroll Bars
  • Scroll Bar Reference

Microsoft® Internet Explorer version 4.0 introduces a new control called a flat scroll bar. Functionally, flat scroll bars behave just like standard scroll bars. The difference is that you can customize their appearance to a greater extent than standard scroll bars.


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
  • Standard Scroll Bars and Scroll Bar Controls
  • Scroll Box Position and Scrolling Range
  • Scroll Bar Visibility
  • Scroll Bar Requests
  • Keyboard Interface for a Scroll Bar
  • Scrolling the Client Area
  • Scroll Bar Colors and Metrics


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 standard scroll bar is part of its associated window and therefore does not have a window handle of its own.

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 specified 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 request 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 request code that the user generates when clicking various parts of a scroll bar.

The SB_ values 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, the user's action is specified for each value, followed by the application's response. In each case, a unit is defined by the application as appropriate for the data. For example, the typical unit for scrolling text vertically is a line of text.

Request | 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 specified 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 specified 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 request code 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 SB_THUMBPOSITION and SB_THUMBTRACK request code when the user clicks and drags the scroll box. An application should be programmed to process either the SB_THUMBTRACK or SB_THUMBPOSITION request code.

The SB_THUMBPOSITION request code 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.

The SB_THUMBTRACK request code occurs as the user drags the scroll box. If an application processes SB_THUMBTRACK request codes, it can scroll the content of a window as the user drags the scroll box. However, a scroll bar can generate many SB_THUMBTRACK request code in a short period, so an application should process these request codes 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 request code is sent with each message corresponding to the arrow key the user has pressed. Following are the arrow keys and their corresponding request codes.

Arrow key | Request code
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 request codes. The SB_TOP request code 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 request code indicates that the user has reached the bottom value of the scrolling range. If an application processes the SB_BOTTOM request code, 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 request codes, which typically require completely new content.

For some request codes, 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 request code that indicates the direction and magnitude of the scrolling action.

When the WM_HSCROLL and WM_VSCROLL messages are processed, the scroll bar request code 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 request code 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 request code. 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 request code.

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 elements are used with scroll bars.

  • Scroll Bar Functions
  • Scroll Bar Structures
  • Scroll Bar Messages
  • Scroll Bar Control Styles


Scroll Bar Functions

The following functions are used with scroll bars.

Function | Description
EnableScrollBar | Enables or disables one or both scroll bar arrows.
GetScrollBarInfo | Retrieves information about the specified scroll bar.
GetScrollInfo | Retrieves the parameters of a scroll bar.
GetScrollPos | Retrieves the current position of the scroll box.
GetScrollRange | Retrieves the current minimum and maximum scroll box positions.
ScrollDC | Scrolls a rectangle of bits horizontally and vertically.
ScrollWindow | Scrolls the contents of the specified window's client area.
ScrollWindowEx | Scrolls the contents of the specified window's client area.
SetScrollInfo | Sets the parameters of a scroll bar.
SetScrollPos | Sets the position of the scroll box.
SetScrollRange | Sets the minimum and maximum scroll box position.
ShowScrollBar | Shows or hides the specified scroll bar.


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
  UINT wArrows   // scroll bar arrow options
);

Parameters

hWnd
[in] Handle to a window or a scroll bar control, depending on the value of the wSBflags parameter.
wSBflags
[in] 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 | Indicates that the scroll bar is a scroll bar control. The hWnd 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
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Scroll Bars Overview, Scroll Bar Functions, ShowScrollBar


GetScrollBarInfo

The GetScrollBarInfo function retrieves information about the specified scroll bar.

BOOL GetScrollBarInfo(
  HWND hwnd,           // handle to window
  LONG idObject,       // scroll bar object
  PSCROLLBARINFO psbi  // scroll bar information
);

Parameters

hwnd
[in] Handle to a window associated with the scroll bar whose information is to be retrieved. If the idObject parameter is OBJID_CLIENT, hwnd is a handle to a scroll bar control. Otherwise, hwnd is a handle to a window created with WS_VSCROLL and/or WS_HSCROLL style.
idObject
[in] Specifies the scroll bar object. This parameter can be one of the following values.
Value | Meaning
OBJID_CLIENT | The hwnd parameter is a handle to a scroll bar control.
OBJID_HSCROLL | The horizontal scroll bar of the hwnd window.
OBJID_VSCROLL | The vertical scroll bar of the hwnd window.

psbi
[out] Pointer to a SCROLLBARINFO structure to receive the information. Before calling GetScrollBarInfo, set the cbSize member to sizeof(SCROLLBARINFO).

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP6 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Scroll Bars Overview, Scroll Bar Functions, SCROLLBARINFO


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
  int fnBar,         // scroll bar type
  LPSCROLLINFO lpsi  // scroll bar parameters
);

Parameters

hwnd
[in] Handle to a scroll bar control or a window with a standard scroll bar, depending on the value of the fnBar parameter.
fnBar
[in] 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 window's standard horizontal scroll bar.
SB_VERT | Retrieves the parameters for the window's standard vertical scroll bar.

lpsi
[in/out] 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 one or more 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 request code 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;
        .
        .
        .
    }

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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.

Note The GetScrollPos function is provided for backward compatibility. New applications should use the GetScrollInfo function.

int GetScrollPos(
  HWND hWnd, // handle to window
  int nBar   // scroll bar options
);

Parameters

hWnd
[in] Handle to a scroll bar control or a window with a standard scroll bar, depending on the value of the nBar parameter.
nBar
[in] 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 request code in a WM_HSCROLL or WM_VSCROLL message, use the GetScrollInfo function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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.

Note The GetScrollRange function is provided for compatibility only. New applications should use the GetScrollInfo function.

BOOL GetScrollRange(
  HWND hWnd,       // handle to window
  int nBar,        // scroll bar options
  LPINT lpMinPos,  // receives minimum position
  LPINT lpMaxPos   // receives maximum position
);

Parameters

hWnd
[in] Handle to a scroll bar control or a window with a standard scroll bar, depending on the value of the nBar parameter.
nBar
[in] 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
[out] Pointer to the integer variable that receives the minimum position.
lpMaxPos
[out] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 DC
  int dx,                  // horizontal scrolling
  int dy,                  // vertical scrolling
  CONST RECT *lprcScroll,  // scrolling rectangle
  CONST RECT *lprcClip,    // clipping rectangle
  HRGN hrgnUpdate,         // handle to scrolling region
  LPRECT lprcUpdate        // update rectangle
);

Parameters

hDC
[in] Handle to the device context that contains the bits to be scrolled.
dx
[in] Specifies the amount, in device units, of horizontal scrolling. This parameter must be a negative value to scroll to the left.
dy
[in] Specifies the amount, in device units, of vertical scrolling. This parameter must be a negative value to scroll up.
lprcScroll
[in] Pointer to a RECT structure containing the coordinates of the bits to be scrolled. The only bits affected by the scroll operation are bits in the intersection of this rectangle and the rectangle specified by lprcClip. If lprcScroll is NULL, the entire client area is used.
lprcClip
[in] Pointer to a RECT structure containing the coordinates of the clipping rectangle. The only bits that will be painted are the bits that remain inside this rectangle after the scroll operation has been completed. If lprcClip is NULL, the entire client area is used.
hrgnUpdate
[in] Handle to the region uncovered by the scrolling process. ScrollDC defines this region; it is not necessarily a rectangle.
lprcUpdate
[out] Pointer to a 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Scroll Bars Overview, Scroll Bar Functions, InvalidateRgn, RECT, ScrollWindowEx


ScrollWindow

The ScrollWindow function scrolls the contents of the specified window's client area.

Note The ScrollWindow function is provided for backward compatibility. New applications should use the ScrollWindowEx function.

BOOL ScrollWindow(
  HWND hWnd,              // handle to window
  int XAmount,            // horizontal scrolling
  int YAmount,            // vertical scrolling
  CONST RECT *lpRect,     // client area
  CONST RECT *lpClipRect  // clipping rectangle
);

Parameters

hWnd
[in] Handle to the window where the client area is to be scrolled.
XAmount
[in] 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
[in] 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
[in] 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
[in] 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.

For an example, see Example of Scrolling Text.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Scroll Bars Overview, Scroll Bar Functions, RECT, ScrollDC, ScrollWindowEx, UpdateWindow


ScrollWindowEx

The ScrollWindowEx function scrolls the contents of the specified window's client area.

int ScrollWindowEx(
  HWND hWnd,             // handle to window
  int dx,                // horizontal scrolling
  int dy,                // vertical scrolling
  CONST RECT *prcScroll, // client area
  CONST RECT *prcClip,   // clipping rectangle
  HRGN hrgnUpdate,       // handle to update region
  LPRECT prcUpdate,      // invalidated region
  UINT flags             // scrolling options
);

Parameters

hWnd
[in] Handle to the window where the client area is to be scrolled.
dx
[in] Specifies the amount, in device units, of horizontal scrolling. This parameter must be a negative value to scroll to the left.
dy
[in] Specifies the amount, in device units, of vertical scrolling. This parameter must be a negative value to scroll up.
prcScroll
[in] Pointer to a RECT structure that specifies the portion of the client area to be scrolled. If this parameter is NULL, the entire client area is scrolled.
prcClip
[in] Pointer to a RECT structure that contains 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. This parameter may be NULL.
hrgnUpdate
[in] Handle to the region that is modified to hold the region invalidated by scrolling. This parameter may be NULL.
prcUpdate
[out] Pointer to a RECT structure that receives the boundaries of the rectangle invalidated by scrolling. This parameter may be NULL.
flags
[in] 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 98, Windows 2000: 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.

For an example, see Example of Scrolling Text.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
  int fnBar,           // scroll bar type
  LPCSCROLLINFO lpsi,  // scroll parameters
  BOOL fRedraw         // redraw flag
);

Parameters

hwnd
[in] Handle to a scroll bar control or a window with a standard scroll bar, depending on the value of the fnBar parameter.
fnBar
[in] 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 window's standard horizontal scroll bar.
SB_VERT | Sets the parameters of the window's standard vertical scroll bar.

lpsi
[in] 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 one or more 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
[in] 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.

For an example, see Example of Scrolling Text.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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.

Note The SetScrollPos function is provided for backward compatibility. New applications should use the SetScrollInfo function.

int SetScrollPos(
  HWND hWnd,     // handle to window
  int nBar,      // scroll bar
  int nPos,      // new position of scroll box
  BOOL bRedraw   // redraw flag
);

Parameters

hWnd
[in] Handle to a scroll bar control or a window with a standard scroll bar, depending on the value of the nBar parameter.
nBar
[in] 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
[in] 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
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 scroll box positions for the specified scroll bar.

Note The SetScrollRange function is provided for backward compatibility. New applications should use the SetScrollInfo function.

BOOL SetScrollRange(
  HWND hWnd,    // handle to window
  int nBar,     // scroll bar
  int nMinPos,  // minimum scrolling position
  int nMaxPos,  // maximum scrolling position
  BOOL bRedraw  // redraw flag
);

Parameters

hWnd
[in] Handle to a scroll bar control or a window with a standard scroll bar, depending on the value of the nBar parameter.
nBar
[in] 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
[in] Specifies the minimum scrolling position.
nMaxPos
[in] Specifies the maximum scrolling position.
bRedraw
[in] 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.

For an example, see Using the Owner-Display Clipboard Format.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
  int wBar,   // scroll bar
  BOOL bShow  // scroll bar visibility
);

Parameters

hWnd
[in] Handle to a scroll bar control or a window with a standard scroll bar, depending on the value of the wBar parameter.
wBar
[in] 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
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Scroll Bars Overview, Scroll Bar Functions, EnableScrollBar


Scroll Bar Structures

The following structures are used with scroll bars.

SCROLLBARINFO
SCROLLINFO


SCROLLBARINFO

The SCROLLBARINFO structure contains scroll bar information.

typedef struct tagSCROLLBARINFO {
    DWORD cbSize;
    RECT  rcScrollBar;
    int   dxyLineButton;
    int   xyThumbTop;
    int   xyThumbBottom;
    int   reserved;
    DWORD rgstate[CCHILDREN_SCROLLBAR+1];
} SCROLLBARINFO, *PSCROLLBARINFO, *LPSCROLLBARINFO;

Members

cbSize
Specifies the size, in bytes, of the structure. Before calling the GetScrollBarInfo function, set cbSize to sizeof(SCROLLBARINFO).
rcScrollBar
Pointer to a RECT structure that indicates the coordinates of the scroll bar.
dxyLineButton
Height or width of the thumb.
xyThumbTop
Position of the top or left of the thumb.
xyThumbBottom
Position of the bottom or right of the thumb.
reserved
Reserved.
rgstate
An array of DWORD elements. Each element indicates the state of a scroll bar component. The following table shows the scroll bar component that corresponds to each array index.
Index | Scroll bar component
0 | The scroll bar itself.
1 | The top or right arrow button.
2 | The page up or page right region.
3 | The scroll box (thumb).
4 | The page down or page left region.
5 | The bottom or left arrow button.

The DWORD element for each scroll bar component can include a combination of the following bit flags.
Value | Meaning
STATE_SYSTEM_INVISIBLE | For the scroll bar itself, indicates the specified vertical or horizontal scroll bar does not exist. For the page up or page down regions, indicates the thumb is positioned such that the region does not exist.
STATE_SYSTEM_OFFSCREEN | For the scroll bar itself, indicates the window is sized such that the specified vertical or horizontal scroll bar is not currently displayed
STATE_SYSTEM_PRESSED | The arrow button or page region is pressed.
STATE_SYSTEM_UNAVAILABLE | The component is disabled.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP6 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Scroll Bars Overview, Scroll Bar Structures, GetScrollBarInfo, RECT


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 {
    UINT cbSize;
    UINT fMask;
    int  nMin;
    int  nMax;
    UINT nPage;
    int  nPos;
    int  nTrackPos;
}   SCROLLINFO, *LPSCROLLINFO;
typedef SCROLLINFO CONST *LPCSCROLLINFO;

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 request code. An application cannot set the immediate scroll position; the SetScrollInfo function ignores this member.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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_GETSCROLLBARINFO 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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  SBM_ENABLE_ARROWS,        // message to send
  (WPARAM) wParam,          // scroll bar arrow options
  (LPARAM) lParam          // not used; must be zero
);

Parameters

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

lParam
This parameter is not used.

Return Values

If the message succeeds, the return value is TRUE; otherwise, it is FALSE.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  SBM_GETPOS,               // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

The return value is the current position of the scroll box in the scroll bar.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  SBM_GETRANGE,             // message to send
  (WPARAM) wParam,          // minimum position (LPINT)
  (LPARAM) lParam          // maximum position (LPINT)
);

Parameters

wParam
Pointer to a variable that receives the minimum scrolling position.
lParam
Pointer to a variable that receives the maximum scrolling position.

Return Values

This message does not return a value.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Scroll Bars Overview, Scroll Bar Messages, SBM_GETPOS, SBM_SETPOS, SBM_SETRANGE, SBM_SETRANGEREDRAW


SBM_GETSCROLLBARINFO

[This is preliminary documentation and subject to change.]

An application sends the SBM_GETSCROLLBARINFO message to retrieve information about the specified scroll bar.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  HWND hWnd,              // handle to destination window
  SBM_GETSCROLLBARINFO,   // message to send
  WPARAM wParam,          // not used; must be zero
  LPARAM psbi             // pointer to SCROLLBARINFO
);

Parameters

wParam
This parameter is not used; it must be zero.
psbi
Pointer to a SCROLLBARINFO structure that receives the 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.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Scroll Bars Overview, Scroll Bar Messages, GetScrollBarInfo, SCROLLBARINFO


SBM_GETSCROLLINFO

An application sends the SBM_GETSCROLLINFO message to retrieve the parameters of a scroll bar.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  SBM_GETSCROLLINFO,        // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // parameters (LPSCROLLINFO)
);

Parameters

wParam
This parameter is not used.
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 one or more 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.
SIF_POS | Copies the scroll position to the nPos member.
SIF_RANGE | Copies the scroll range to the nMin and nMax members.
SIF_TRACKPOS | Copies the current scroll box tracking position to the nTrackPos member.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  SBM_SETPOS,               // message to send
  (WPARAM) wParam,          // new position
  (LPARAM) lParam          // redraw option
);

Parameters

wParam
Specifies the new position of the scroll box. It must be within the scrolling range.
lParam
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 lParam parameter to FALSE is useful.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  SBM_SETRANGE,             // message to send
  (WPARAM) wParam,          // minimum scrolling position
  (LPARAM) lParam          // maximum scrolling position
);

Parameters

wParam
Specifies the minimum scrolling position.
lParam
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 wParam and lParam parameters must not be greater than MAXLONG.

If the minimum and maximum position values are equal, the scroll bar control is hidden and, in effect, disabled.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  SBM_SETRANGEREDRAW,       // message to send
  (WPARAM) wParam,          // minimum scrolling position
  (LPARAM) lParam          // maximum scrolling position
);

Parameters

wParam
Specifies the minimum scrolling position.
lParam
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 wParam and lParam parameters must not be greater than MAXLONG.

If the minimum and maximum position values are equal, the scroll bar control is hidden and, in effect, disabled.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Scroll Bars Overview, Scroll Bar Messages, SBM_GETPOS, SBM_GETRANGE, SBM_SETPOS, SBM_SETRANGE


SBM_SETSCROLLINFO

An application sends the SBM_SETSCROLLINFO message to set the parameters of a scroll bar.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  SBM_SETSCROLLINFO,        // message to send
  (WPARAM) wParam,          // redraw option
  (LPARAM) lParam          // parameters (LPSCROLLINFO)
);

Parameters

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.
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 one or more 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.
SIF_POS | Sets the scroll position to the value specified in the nPos member.
SIF_RANGE | Sets the scroll range to the value specified in the nMin and nMax members.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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 display context handle to set the background color of the scroll bar control.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_CTLCOLORSCROLLBAR
  WPARAM wParam,   // handle to DC (HDC)
  LPARAM lParam    // handle to scroll bar (HWND)
);

Parameters

wParam
Handle to the device context for the scroll bar control.
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.

Remarks

By default, the DefWindowProc function selects the default system colors for the scroll bar control.

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.

The WM_CTLCOLORSCROLLBAR message is used only by child scrollbar controls. Scrollbars attached to a window (WS_SCROLL and WS_VSCROLL) do not generate this message. To customize the appearance of scrollbars attached to a window, use the flat scroll bar functions.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Scroll Bars Overview, Scroll Bar Messages, DefWindowProc, RealizePalette, SelectPalette, WM_CTLCOLORBTN, WM_CTLCOLORDLG, WM_CTLCOLOREDIT, WM_CTLCOLORLISTBOX, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_HSCROLL
  WPARAM wParam,   // request and position
  LPARAM lParam    // handle to scroll bar (HWND)
);

Parameters

wParam
The low-order word specifies a scroll bar value that indicates the user's scrolling request. This word 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 high-order word 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 high-order word indicates the position that the scroll box has been dragged to.

The high-order word specifies the current position of the scroll box if the low-order word is SB_THUMBPOSITION or SB_THUMBTRACK; otherwise, this word is not used.

lParam
If the message is sent by a scroll bar, then this parameter is the handle to the scroll bar control. If the message is not sent by a scroll bar, this parameter is NULL.

Return Values

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

Remarks

The SB_THUMBTRACK request code 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_VSCROLL
  WPARAM wParam,   // request and position
  LPARAM lParam    // handle to scroll bar (HWND)
);

Parameters

wParam
The low-order word 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 high-order word 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 high-order word indicates the position that the scroll box has been dragged to.
SB_TOP | Scrolls to the upper left.

The high-order word specifies the current position of the scroll box if the low-order word is SB_THUMBPOSITION or SB_THUMBTRACK; otherwise, this word is not used.

lParam
If the message is sent by a scroll bar, this parameter is the handle to the scroll bar control. If the message is not sent by a scroll bar, this parameter is NULL.

Return Values

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

Remarks

The SB_THUMBTRACK request code 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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_SIZEBOXBOTTOMRIGHTALIGN | 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
  • Using Static Controls
  • Static Control Reference


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 can be 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 a pointer to 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_GETTEXT | Returns the number of characters copied.
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);
            // Note that DestroyIcon is not correct here.
            // LoadIcon obtains a shared icon, which is valid as long
            // as the module from which it was loaded is in memory.

            return 0;
    }
    return FALSE;
        UNREFERENCED_PARAMETER(lParam);
}


Static Control Reference

The following elements are used with static controls.

  • Static Control 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

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


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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  STM_GETICON,              // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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 (icon or bitmap) associated with a static control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  STM_GETIMAGE,             // message to send
  (WPARAM) wParam,          // image type
  (LPARAM) lParam          // not used; must be zero
);

Parameters

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

lParam
This parameter is not used.

Return Values

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  STM_SETICON,              // message to send
  (WPARAM) wParam,          // handle to icon (HICON)
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Handle to the icon to associate with the icon control.
lParam
This parameter is not used.

Return Values

The return value is a handle to the icon previously associated with the icon control, or zero if an error occurs.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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 with a static control.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  STM_SETIMAGE,             // message to send
  (WPARAM) wParam,          // image type
  (LPARAM) lParam          // handle to image (HANDLE)
);

Parameters

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

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.

Remarks

To associate an image with a static control, the control must have the proper style. The following table shows the style needed for each image type.

Image type | Static control style
IMAGE_BITMAP | SS_BITMAP
IMAGE_CURSOR | SS_ICON
IMAGE_ENHMETAFILE | SS_ENHMETAFILE
IMAGE_ICON | SS_ICON

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Static Controls Overview, Static Control Messages, STM_GETIMAGE


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.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // control identifier, STN_CLICKED
  LPARAM lParam    // handle to static control (HWND)
);

Parameters

wParam
The low-order word is a static control identifier.

The high-order word is the notification message.

lParam
Handle to the static control.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Static Controls Overview, Static Control Messages, HIWORD, LOWORD, 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.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // control identifier, STN_DBLCLK
  LPARAM lParam    // handle to static control (HWND)
);

Parameters

wParam
The low-order word is a static control identifier.

The high-order word is the notification message.

lParam
Handle to the static control.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Static Controls Overview, Static Control Messages, HIWORD, LOWORD, 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.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // control identifier, STN_DISABLE
  LPARAM lParam    // handle to static control (HWND)
);

Parameters

wParam
The low-order word is a static control identifier.

The high-order word is the notification message.

lParam
Handle to the static control.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Static Controls Overview, Static Control Messages, HIWORD, LOWORD, 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.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMMAND
  WPARAM wParam,   // control identifier, STN_ENABLE
  LPARAM lParam    // handle to static control (HWND)
);

Parameters

wParam
The low-order word is a static control identifier.

The high-order word is the notification message.

lParam
Handle to the static control.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Static Controls Overview, Static Control Messages, HIWORD, LOWORD, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_CTLCOLORSTATIC
  WPARAM wParam,   // handle to DC (HDC)
  LPARAM lParam    // handle to static control (HWND)
);

Parameters

wParam
Handle to the device context for the static control window.
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.

Remarks

By default, the DefWindowProc function selects the default system colors for the static control.

Edit controls that are not read-only or disabled do not send the WM_CTLCOLORSTATIC message; instead, they send the WM_CTLCOLOREDIT message. 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Static Controls Overview, Static Control Messages, DefWindowProc, RealizePalette, SelectPalette, WM_CTLCOLORBTN, WM_CTLCOLORDLG, WM_CTLCOLOREDIT, WM_CTLCOLORLISTBOX, 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 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 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. Words that are longer than the width of the control are truncated.
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 | Windows NT/2000 or later: If the end of a string does not fit in the rectangle, it is truncated and ellipses are added. If a word that is not at the end of the string goes beyond the limits of the rectangle, it is truncated without ellipses. Compare with SS_PATHELLIPSIS and SS_WORDELLIPSIS.
SS_ENHMETAFILE | Specifies an enhanced metafile is to be displayed in the static control. The 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. If the control is created as part of a dialog box, the text is the name of an icon (not a filename) defined elsewhere in the resource file. If the control is created via CreateWindow or a related function, the text is the name of an icon (not a filename) defined in the resource file associated with the module specified by the hInstance parameter to CreateWindow. 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 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. Words that are longer than the width of the control are truncated.
SS_LEFTNOWORDWRAP | Specifies a simple rectangle and left-aligns the 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_PATHELLIPSIS | Windows 2000 or later: Replaces characters in the middle of the string with ellipses so that the result fits in the specified rectangle. If the string contains backslash (\) characters, SS_PATHELLIPSIS preserves as much as possible of the text after the last backslash. Compare with SS_ENDELLIPSIS and SS_WORDELLIPSIS.
SS_REALSIZECONTROL | Whistler: Ensures that the control is the specified size by stretching the bitmap image. By default, the control is resized to fit the image.
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 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. Words that are longer than the width of the control are truncated.
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. Also, if the control is disabled, the control does not gray its text.
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 | Windows NT/2000 or later: Truncates any word that does not fit in the rectangle and adds ellipses. Compare with SS_ENDELLIPSIS and SS_PATHELLIPSIS.


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 information. An application-defined resource, also called a custom resource, contains any data required by a specific application.

  • About Resources
  • Using Resources
  • Resource Reference


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 | Strings
Version information | Version Information

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.


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. For a group list of the structures that describe the format of resources, see Resource Structures.

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

Cursor and Icon Resources

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.

Dialog Box Resources

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.

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

Menu Resources

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.

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

Version Resources

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.


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(hResLoad);
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.

Function | Description
BeginUpdateResource | Returns a handle that can be used by UpdateResource to add, delete, or replace resources.
CopyImage | Creates a new icon, cursor, or bitmap and copies the attributes of the old one to the new one.
EndUpdateResource | Ends a resource update in an executable file.
EnumResLangProc | An application-defined callback function used with EnumResourceLanguages.
EnumResNameProc | An application-defined callback function used with EnumResourceNames
EnumResourceLanguages | Searches for resources of a specified type and name and passes the language to a callback function.
EnumResourceNames | Searches for resources of a specified type and passes the name or the ID to a callback function
EnumResourceTypes | Searches for resources and passes each type to a callback function.
EnumResTypeProc | An application-defined callback function used with EnumResourceTypes.
FindResource | Finds a resource with a specified type and name.
FindResourceEx | Finds a resource with a specified type, name, and language.
LoadImage | Loads an icon, cursor, or bitmap
LoadResource | Loads a resource into global memory.
LockResource | Locks a resource in memory.
SizeofResource | Returns the size of a resource.
UpdateResource | Adds, deletes, or replaces a resource.


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,             // executable file name
  BOOL bDeleteExistingResources  // deletion option
);

Parameters

pFileName
[in] Pointer to a null-terminated string that specifies the 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
[in] 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.

For an example, see Updating Resources.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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
  UINT uType,     // type of image to copy
  int cxDesired,  // desired width of new image
  int cyDesired,  // desired height of new image
  UINT fuFlags    // copy options
);

Parameters

hImage
[in] Handle to the image to be copied.
uType
[in] 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
[in] Specifies the desired width, in pixels, of the image. If this is zero, then the returned image will have the same width as the original hImage.
cyDesired
[in] Specifies the desired height, in pixels, of the image. If this is zero, then the returned image will have the same height as the original hImage.
fuFlags
[in] This parameter can be one or more of the following values.
Value | Meaning
LR_COPYDELETEORG | Deletes the original image after creating the copy.
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.
LR_COPYRETURNORG | Returns the original hImage if it satisfies the criteria for the copy—that is, correct dimensions and color depth—in which case the LR_COPYDELETEORG flag is ignored. If this flag is not specified, a new object is always created.
LR_CREATEDIBSECTION | If this is set and a new bitmap is created, the bitmap is created as a DIB section. Otherwise, the bitmap image is created as a device-dependent bitmap. This flag is only valid if uType is IMAGE_BITMAP.
LR_MONOCHROME | Creates a new monochrome image.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 option
);

Parameters

hUpdate
[in] Handle used in a resource update. This handle is returned by the BeginUpdateResource function.
fDiscard
[in] 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.

For an example, see Updating Resources.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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,  // resource type
  LPCTSTR lpszName,  // resource name
  WORD wIDLanguage,  // language identifier
  LONG_PTR lParam    // application-defined parameter
);

Parameters

hModule
[in] 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
[in] Pointer to a null-terminated string specifying the type name of the resource for which the language is being enumerated. For standard resource types, see Resource Types.
lpszName
[in] Pointer to a null-terminated string specifying the name of the resource for which the language is being enumerated.
wIDLanguage
[in] 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
[in] 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

If IS_INTRESOURCE(x) is TRUE for lpszName or lpszType, x specifies the integer identifier of the given resource. Otherwise, it is a pointer to a null-terminated string. 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. For example, the string "#258" represents the identifier 258.

An application must register this function by passing its address to the EnumResourceLanguages function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Unicode: Declared as Unicode and ANSI prototypes.

See Also

Resources Overview, Resource Functions, EnumResourceLanguages, IS_INTRESOURCE, 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(
  HMODULE hModule,   // module handle
  LPCTSTR lpszType,  // resource type
  LPTSTR lpszName,   // resource name
  LONG_PTR lParam    // application-defined parameter
);

Parameters

hModule
[in] Handle to the module whose executable file contains the resources that are being enumerated. If this parameter is NULL, the function enumerates the resource names in the module used to create the current process.
lpszType
[in] Pointer to a null-terminated string specifying the type of resource that is being enumerated. For standard resource types, see Resource Types.
lpszName
[in] Specifies the name of a resource of the type being enumerated. For more information, see the Remarks section.
lParam
[in] 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

If IS_INTRESOURCE(x) is TRUE for lpszName or lpszType, x specifies the integer identifier of the given resource. Otherwise, it is a pointer to a null-terminated string. 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. For example, the string "#258" represents the identifier 258.

An application must register this function by passing its address to the EnumResourceNames function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Unicode: Declared as Unicode and ANSI prototypes.

See Also

Resources Overview, Resource Functions, EnumResourceNames, IS_INTRESOURCE


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,             // module handle
  LPCTSTR lpType,              // resource type
  LPCTSTR lpName,              // resource name
  ENUMRESLANGPROC lpEnumFunc,  // callback function
  LONG_PTR lParam              // application-defined parameter
);

Parameters

hModule
[in] 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
[in] Pointer to a null-terminated string specifying the type of the resource for which the language is being enumerated. For standard resource types, see Resource Types.
lpName
[in] Pointer to a null-terminated string specifying the name of the resource for which the language is being enumerated.
lpEnumFunc
[in] Pointer to the callback function to be called for each enumerated resource language. For more information, see EnumResLangProc.
lParam
[in] 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

If a resource has an ID, the ID is returned to the callback function; otherwise the resource name is returned to the callback function. For more information, see EnumResLangProc.

The EnumResourceLanguages function continues to enumerate resource languages until the callback function returns FALSE or all resource languages have been enumerated.

For an example, see Creating a Resource List.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on all platforms.

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 either the name or the ID of each resource it locates to an application-defined callback function.

BOOL EnumResourceNames(
  HMODULE hModule,             // module handle
  LPCTSTR lpszType,            // resource type
  ENUMRESNAMEPROC lpEnumFunc,  // callback function
  LONG_PTR lParam              // application-defined parameter
);

Parameters

hModule
[in] Handle to the module whose executable file contains the resources that are to be enumerated. If this parameter is NULL, the function enumerates the resources in the module used to create the current process.
lpszType
[in] Pointer to a null-terminated string specifying the type of resource to be enumerated. For standard resource types, see Resource Types.
lpEnumFunc
[in] Pointer to the callback function to be called for each enumerated resource name. For more information, see EnumResNameProc.
lParam
[in] 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 does not find a resource of the type specified, or if the function fails for another reason, the return value is zero. To get extended error information, call GetLastError.

GetLastError value | Meaning
NO_ERROR | Windows 95/98/Me: No resource of the specified type was found.
ERROR_RESOURCE_TYPE_NOT_FOUND | Windows NT/2000 or later: No resource of the specified type was found.
any other return value | Some other type of error occurred.

Remarks

If a resource has an ID, the ID is returned to the callback function; otherwise the resource name is returned to the callback function. For more information, see EnumResNameProc.

The EnumResourceNames function continues to enumerate resources until the callback function returns FALSE or all resources have been enumerated.

For an example, see Creating a Resource List.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on all platforms.

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,             // module handle
  ENUMRESTYPEPROC lpEnumFunc,  // callback function
  LONG_PTR lParam              // application-defined parameter
);

Parameters

hModule
[in] 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
[in] Pointer to the callback function to be called for each enumerated resource type. For more information, see the EnumResTypeProc function.
lParam
[in] 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.

For an example, see Creating a Resource List.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on all platforms.

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(
  HMODULE hModule,  // module handle
  LPTSTR lpszType,  // resource type
  LONG_PTR lParam   // application-defined parameter
);

Parameters

hModule
[in] 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
[in] Pointer to a null-terminated string specifying the type name of the resource for which the type is being enumerated. For standard resource types, see Resource Types.
lParam
[in] 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

If IS_INTRESOURCE(lpszType) is TRUE lpszType specifies the integer identifier of the given resource. Otherwise, it is a pointer to a null-terminated string. 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. For example, the string "#258" represents the identifier 258.

An application must register this function by passing its address to the EnumResourceTypes function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Unicode: Declared as Unicode and ANSI prototypes.

See Also

Resources Overview, Resource Functions, EnumResourceTypes, IS_INTRESOURCE


FindResource

The FindResource function determines the location of a resource with the specified type and name in the specified module.

To specify a language, use the FindResourceEx function.

HRSRC FindResource(
  HMODULE hModule, // module handle
  LPCTSTR lpName,  // resource name
  LPCTSTR lpType   // resource type
);

Parameters

hModule
[in] 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
[in] Specifies the name of the resource. For more information, see the Remarks section.
lpType
[in] Specifies the resource type. For more information, see the Remarks section. For standard resource types, see Resource Types.

Return Values

If the function succeeds, the return value is a handle to the specified resource's information 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 IS_INTRESOURCE(x) is TRUE for x = lpName or lpType, x 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.

To reduce the amount of memory required for a resource, an application should refer to it by integer identifier instead of by name.

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

For an example, see Updating Resources.

Windows 95/98/Me: The lpType and lpName parameters to FindResourceW may not be string buffers allocated from the heap. If necessary, copy them to stack buffers and pass the stack buffers.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on all platforms.

See Also

Resources Overview, Resource Functions, FindResourceEx, FormatMessage, IS_INTRESOURCE, 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, // module handle
  LPCTSTR lpType,  // resource type
  LPCTSTR lpName,  // resource name
  WORD wLanguage   // resource language
);

Parameters

hModule
[in] 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
[in] Pointer to a null-terminated string specifying the type name of the resource. For more information, see the Remarks section. For standard resource types, see Resource Types.lpName
[in] Pointer to a null-terminated string specifying the name of the resource. For more information, see the Remarks section.
wLanguage
[in] 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 information 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 IS_INTRESOURCE(x) is TRUE for x = lpType or lpName, x specifies the integer identifier of the type or name 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.

To reduce the amount of memory required for a resource, an application should refer to it by integer identifier instead of by name.

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

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.

For an example, see Creating a Resource List.

Windows 95/98/Me: The lpType and lpName parameters to FindResourceExW may not be string buffers allocated from the heap. If necessary, copy them to stack buffers and pass the stack buffers.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on all platforms.

See Also

Resources Overview, Resource Functions, FindResource, FormatMessage, IS_INTRESOURCE, LoadAccelerators, LoadBitmap, LoadCursor, LoadIcon, LoadMenu, LoadString, LoadResource, MAKELANGID


LoadImage

The LoadImage function loads an icon, cursor, animated cursor, or bitmap.

HANDLE LoadImage(
  HINSTANCE hinst,   // handle to instance
  LPCTSTR lpszName,  // image to load
  UINT uType,        // image type
  int cxDesired,     // desired width
  int cyDesired,     // desired height
  UINT fuLoad        // load options
);

Parameters

hinst
[in] 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
[in] Specifies the image to load. If the hinst parameter is non-NULL and the fuLoad parameter omits LR_LOADFROMFILE, lpszName specifies the image resource in the hinst module. If the image resource is to be loaded by name, the lpszName parameter is a pointer to a null-terminated string that contains the name of the image resource. If the image resource is to be loaded by ordinal, use the MAKEINTRESOURCE macro to convert the image ordinal into a form that can be passed to the LoadImage function.

If the hinst parameter is NULL and the fuLoad parameter omits the LR_LOADFROMFILE value, the lpszName specifies 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

To pass these constants to the LoadImage function, use the MAKEINTRESOURCE macro. For example, to load the OCR_NORMAL cursor, pass MAKEINTRESOURCE(OCR_NORMAL) as the lpszName parameter and NULL as the hinst parameter.

If the fuLoad parameter includes the LR_LOADFROMFILE value, lpszName is the name of the file that contains the image.

uType
[in] 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
[in] 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
[in] 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
[in] This parameter can be one or more 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 3-D 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
Do not use this option if you are loading a bitmap with a color depth greater than 8bpp.
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.

Do not use this option if you are loading a bitmap with a color depth greater than 8bpp.

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.

When you use this flag, the system will destroy the resource when it is no longer needed.

Do not use LR_SHARED for images that have non-standard sizes, that may change after loading, or that are loaded from a file.

When loading a system icon or cursor, you must use LR_SHARED or the function will fail to load the resource.

Windows 95/98/Me: 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 a bitmap, cursor, or icon you loaded without specifying the LR_SHARED flag, 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.

For an example, see Icon Creation.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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, // module handle
  HRSRC hResInfo   // resource handle
);

Parameters

hModule
[in] 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
[in] Handle to the resource to be loaded. This handle is returned by 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.

To use a resource immediately, an application should use the following resource-specific functions to find and load the resource in one call.

Function | Action | To remove resource
FormatMessage | Loads and formats a message-table entry | No action needed
LoadAccelerators | Loads an accelerator table | DestroyAcceleratorTable
LoadBitmap | Loads a bitmap resource | DeleteObject
LoadCursor | Loads a cursor resource | DestroyCursor
LoadIcon | Loads an icon resource | DestroyIcon
LoadMenu | Loads a menu resource | DestroyMenu
LoadString | Loads a string resource | No action needed

For example, an application can use the LoadIcon function to load an icon for display on the screen, followed by DestroyIcon when done.

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.

For an example, see Updating Resources.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
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
);

Parameters

hResData
[in] Handle to the resource to be locked. The LoadResource function returns this handle. Note that this parameter is listed as an HGLOBAL variable only for backwards compatibility. Do not pass any value as a parameter other than a successful return value from the LoadResource function.

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

The pointer returned by LockResource is valid until the module containing the resource is unloaded. It is not necessary to unlock resources because the system automatically deletes them when the process that created them terminates.

Do not try to lock a resource by using the handle returned by the FindResource or FindResourceEx function. Such a handle points to random data.

For an example, see Updating Resources.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
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, // module handle
  HRSRC hResInfo   // resource handle
);

Parameters

hModule
[in] Handle to the module whose executable file contains the resource.
hResInfo
[in] 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.

For an example, see Updating Resources.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Resources Overview, Resource Functions, FindResource, FindResourceEx


UpdateResource

The UpdateResource function adds, deletes, or replaces a resource in an executable file.

BOOL UpdateResource(
  HANDLE hUpdate, // update-file handle
  LPCTSTR lpType, // resource type
  LPCTSTR lpName, // resource name
  WORD wLanguage, // language identifier
  LPVOID lpData,  // resource data
  DWORD cbData    // length of resource data
);

Parameters

hUpdate
[in] Specifies an update-file handle. This handle is returned by the BeginUpdateResource function.
lpType
[in] 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 a predefined resource type. For a list of predefined resource types, see Resource Types.
lpName
[in] 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
[in] 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
[in] 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
[in] 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.

For an example, see Updating Resources.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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.

Resource File Header

RESOURCEHEADER

Accelerator Table Resources

ACCELTABLEENTRY

Cursor and Icon Resources

CURSORDIR
CURSORSHAPE
ICONRESDIR
LOCALHEADER
NEWHEADER
RESDIR

Dialog Box Resources

DLGTEMPLATE
DLGTEMPLATEEX
DLGITEMTEMPLATE

DLGITEMTEMPLATEEX

Font and Font Directory Resources

DIRENTRY
FONTDIRENTRY
FONTGROUPHDR

Menu Resources

MENUEX_TEMPLATE_HEADER
MENUEX_TEMPLATE_ITEM
MENUHEADER
MENUHELPID
NORMALMENUITEM
POPUPMENUITEM

Message Table Resources

MESSAGE_RESOURCE_BLOCK
MESSAGE_RESOURCE_DATA
MESSAGE_RESOURCE_ENTRY

Version Resources

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.

See Also

Resources Overview, Resource Structures, RESDIR


CURSORSHAPE

The CURSORSHAPE structure contains information about a cursor.

typedef struct tagCURSORSHAPE {
    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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.

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
Specifies a DIRENTRY structure that contains a unique ordinal identifier for each font in the resource. The DE 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.

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 structure.
HighId
Specifies the highest message identifier contained within this structure.
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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winnt.h; include Windows.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 {
    DWORD NumberOfBlocks;
    MESSAGE_RESOURCE_BLOCK Blocks[ 1 ];
} MESSAGE_RESOURCE_DATA, *PMESSAGE_RESOURCE_DATA;

Members

NumberOfBlocks
Specifies the number of MESSAGE_RESOURCE_BLOCK structures.
Blocks
Pointer to an array that contains the number of MESSAGE_RESOURCE_BLOCK structures indicated by the NumberOfBlocks member.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winnt.h; include Windows.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 {
    WORD Length;
    WORD Flags;
    BYTE 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
Pointer to an array that contains the error message or message box display text.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winnt.h; include Windows.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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.

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 those shown in the following table.
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 fType 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.

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. For a list of the predefined Win32 resource types, see Resource Types.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.

See Also

Resources Overview, Resource Structures, CHARACTERISTICS Statement, LANGUAGE Statement, VERSION Statement


Resource Macros

The following macros are used with resources.

IS_INTRESOURCE
MAKEINTRESOURCE


IS_INTRESOURCE

The IS_INTRESOURCE macro determines whether a value is an integer identifier for a resource.

BOOL IS_INTRESOURCE(
  WORD wInteger
);

Parameters

wInteger
Specifies the integer value to be tested.

Return Values

If the value is a resource identifier, the return value is TRUE. Otherwise, the return value is FALSE.

Remarks

This macro checks whether all bits except the least 16 bits are zero. When true, wInteger is an integer identifier for a resource. Otherwise it is typically a pointer to a string.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Resources Overview, Resource Macros


MAKEINTRESOURCE

The MAKEINTRESOURCE macro converts an integer value to a resource type compatible with the resource-management functions. This macro is used in place of a string containing the name of the resource.

LPTSTR MAKEINTRESOURCE(
  WORD wInteger
);

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 functions which explicitly indicate that they accept MAKEINTRESOURCE as a parameter. For example, the resource management functions allow the return value of MAKEINTRESOURCE to be passed as the lpType or lpName parameters.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Unicode: Declared as Unicode and ANSI macros.

See Also

Resources Overview, Resource Macros


Resource Types

The following are the predefined Win32 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_DLGINCLUDE |
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
RT_ICON | Hardware-dependent icon resource
RT_MANIFEST | Whistler: Fusion XML Manifest
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


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
  • Using Carets
  • Caret Reference


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.

The discussion on carets covers the following topics:

  • Caret Visibility
  • Caret Blink Time
  • Caret Position
  • Removing a Caret


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/Windows 2000, 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;                         // coordinates for 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.

Function | Description
CreateCaret | Creates a new shape for the system caret and assigns ownership of the caret to the specified window.
DestroyCaret | Destroys the caret's current shape, frees the caret from the window, and removes the caret from the screen.
GetCaretBlinkTime | Retrieves the time required to invert the caret's pixels.
GetCaretPos | Copies the caret's position to the specified POINT structure.
HideCaret | Removes the caret from the screen.
SetCaretBlinkTime | Sets the caret blink time to the specified number of milliseconds.
SetCaretPos | Moves the caret to the specified coordinates.
ShowCaret | Makes the caret visible on the screen at the caret's current position.


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
[in] Handle to the window that owns the caret.
hBitmap
[in] Handle to 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
[in] 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
[in] 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.

For an example, see Creating and Displaying a Caret.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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.

For an example, see Destroying a Caret.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Carets Overview, Caret Functions, CreateCaret, HideCaret, ShowCaret


GetCaretBlinkTime

The GetCaretBlinkTime function returns the time required to invert the caret's pixels. The user can set this value.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Carets Overview, Caret Functions, SetCaretBlinkTime


GetCaretPos

The GetCaretPos function copies the caret's position to the specified POINT structure.

BOOL GetCaretPos(
  LPPOINT lpPoint   // client coordinates
);

Parameters

lpPoint
[out] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 window with caret
);

Parameters

hWnd
[in] Handle to 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.

For an example, see Hiding a Caret.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
);

Parameters

uMSeconds
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
[in] Specifies the new x-coordinate of the caret.
Y
[in] 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.

For an example, see Creating and Displaying a Caret.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 to window with caret
);

Parameters

hWnd
[in] Handle to 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.

For an example, see Creating and Displaying a Caret.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 cursor functions in the Microsoft® Win32® application programming interface (API) enable applications to create, load, display, animate, move, confine, and destroy cursors.

  • About Cursors
  • Using Cursors
  • Cursor Reference


About Cursors

The Microsoft® 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. New displays, whose display drivers use the device-independent bitmap (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.

This overview provides information on the following topics:

The Hot Spot

The Mouse and the Cursor

Cursor Creation

Cursor Location and Appearance

Cursor Confinement

Cursor Destruction

Cursor Duplication

The Window Class Cursor


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 is not 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 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 mask 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 GetCursorInfo function gets the following information for the global cursor: whether the cursor is hidden or shown, the handle to the cursor, and the coordinates of the cursor.


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 can still use the cursor design.

For information on how to add, remove, or replace cursor resources in executable files, see Resources.


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 has 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 specified class. For more information, see Class Cursor.


Using Cursors

This section discusses the following topics:

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

HINSTANCE hinst;            // handle to current instance
HCURSOR hCurs1, hCurs2;     // cursor handles

HCURSOR hCurs3;             // cursor handle

// Yin-shaped cursor AND mask

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-shaped cursor XOR mask

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 mask
             XORmaskCursor );   // XOR mask

To create the cursor, CreateCursor applies the following truth table to the AND and XOR masks.

AND mask | XOR mask | 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 is 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 specified 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 masks are defined in a code
// example that appears earlier in this section.

// Yin-shaped cursor AND and XOR masks

BYTE ANDmaskCursor[] = ...
BYTE XORmaskCursor[] = ...

// Yang-shaped icon AND mask

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-shaped icon XOR mask

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 mask
             XORmaskIcon); // XOR mask

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 mask
             XORmaskCursor);           // XOR mask

// 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 Structures
  • Cursor Messages


Cursor Functions

The following functions are used with cursors.

Function | Description
ClipCursor | Confines the cursor to a rectangular area on the screen.
CopyCursor | Copies the specified cursor.
CreateCursor | Creates a cursor having the specified size, bit patterns, and hot spot.
DestroyCursor | Destroys a cursor.
GetClipCursor | Retrieves the screen coordinates of the rectangular area to which the cursor is confined.
GetCursor | Retrieves a handle to the current cursor.
GetCursorInfo | Retrieves information about the global cursor.
GetCursorPos | Retrieves the cursor's position.
LoadCursor | Loads a cursor resource from an executable file.
LoadCursorFromFile | Creates a cursor based on data contained in a file.
SetCursor | Sets the cursor shape.
SetCursorPos | Moves the cursor to the specified screen coordinates.
SetSystemCursor | Enables an application to customize the system cursors.
ShowCursor | Displays or hides the cursor.


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  // screen coordinates
);

Parameters

lpRect
[in] 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.

For an example, see Confining a Cursor.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Cursors Overview, Cursor Functions, GetClipCursor, GetCursorPos, RECT, SetCursorPos


CopyCursor

The CopyCursor function copies the specified cursor.

HCURSOR CopyCursor(
  HCURSOR pcur   // handle to cursor
);

Parameters

pcur
[in] 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 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.

Do not use the CopyCursor function for animated cursors. Instead, use the CopyImage function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Cursors Overview, Cursor Functions, CopyIcon, CopyImage, 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,            // x coordinate of hot spot
  int yHotSpot,            // y coordinate of hot spot
  int nWidth,              // cursor width
  int nHeight,             // cursor height
  CONST VOID *pvANDPlane,  // AND mask array
  CONST VOID *pvXORPlane   // XOR mask array
);

Parameters

hInst
[in] Handle to the current instance of the application creating the cursor.
xHotSpot
[in] Specifies the horizontal position of the cursor's hot spot.
yHotSpot
[in] Specifies the vertical position of the cursor's hot spot.
nWidth
[in] Specifies the width, in pixels, of the cursor.
nHeight
[in] Specifies the height, in pixels, of the cursor.
pvANDPlane
[in] Pointer to an array of bytes that contains the bit values for the AND mask of the cursor, as in a device-dependent monochrome bitmap.
pvXORPlane
[in] Pointer to an array of bytes that contains the bit values for the XOR mask of the cursor, as in a device-dependent monochrome bitmap.

Return Values

If the function succeeds, the return value is a handle to 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.

For an example, see Creating a Cursor.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
[in] 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 nonshared 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)

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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   // screen coordinates
);

Parameters

lpRect
[out] 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.

For an example, see Confining a Cursor.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Cursors Overview, Cursor Functions, ClipCursor, GetCursorPos, RECT


GetCursor

The GetCursor function retrieves a 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.

Windows 98 and Windows NT 4.0 SP3 and later: To get information on the global cursor, even if it is not owned by the current thread, use GetCursorInfo.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Cursors Overview, Cursor Functions, GetCursorInfo, SetCursor


GetCursorInfo

The GetCursorInfo function retrieves information about the global cursor.

BOOL GetCursorInfo(
  PCURSORINFO pci  // cursor information
);

Parameters

pci
[out] Pointer to a CURSORINFO structure that receives the 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP6 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Cursors Overview, Cursor Functions, CURSORINFO , GetGUIThreadInfo


GetCursorPos

The GetCursorPos function retrieves the cursor's position, in screen coordinates.

BOOL GetCursorPos(
  LPPOINT lpPoint   // cursor position
);

Parameters

lpPoint
[out] 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 specified 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.

For an example, see Using the Keyboard to Move the Cursor.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Cursors Overview, Cursor Functions, ClipCursor, GetCursorInfo, POINT, SetCursor, SetCursorPos, ShowCursor


LoadCursor

The LoadCursor function loads the specified cursor resource from the executable (.EXE) file associated with an application instance.

Note This function has been superseded by the LoadImage function.

HCURSOR LoadCursor(
  HINSTANCE hInstance,  // handle to application instance
  LPCTSTR lpCursorName  // name or resource identifier
);

Parameters

hInstance
[in] Handle to an instance of the module whose executable file contains the cursor to be loaded.
lpCursorName
[in] 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 cursors predefined in the Microsoft® Win32® API, the application must set the hInstance parameter to NULL and the lpCursorName parameter to one the following values:
Value | Meaning
IDC_APPSTARTING | Standard arrow and small hourglass
IDC_ARROW | Standard arrow
IDC_CROSS | Crosshair
IDC_HAND | Windows 2000: 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 is a pointer to a cursor resource. If lpCursorName is a pointer 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.

For an example, see Creating a Cursor.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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  // file or identifier
);

Parameters

lpFileName
[in] Specifies 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] section in the WIN.INI file for the file associated with the name of that system cursor. For a list of cursor identifiers, see Remarks.

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 cannot be found.

Remarks

The following is a list of system cursor names and identifiers.

Cursor Name | Cursor Identifier
"AppStarting" | OCR_APPSTARTING
"Arrow" | OCR_NORMAL
"Crosshair" | OCR_CROSS
"Hand" | Windows 2000 or 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 following call causes LoadCursorFromFile to obtain cursor data from the file ARROW.ANI.

LoadCursorFromFile((LPWSTR)OCR_NORMAL)

If the WIN.INI file does not contain an entry for the specified system cursor, the function fails and returns NULL.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Cursors Overview, Cursor Functions, LoadCursor, SetCursor, SetSystemCursor


SetCursor

The SetCursor function sets the cursor shape.

HCURSOR SetCursor(
  HCURSOR hCursor   // handle to cursor
);

Parameters

hCursor
[in] Handle to the cursor. The cursor must have been created by the CreateCursor function 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, either 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.

For an example, see Displaying a Cursor.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 call, 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
[in] Specifies the new x-coordinate of the cursor, in screen coordinates.
Y
[in] Specifies the new y-coordinate of the cursor, 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, 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.

For an example, see Using the Keyboard to Move the Cursor.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 the id parameter with the contents of the cursor specified by the hcur parameter and then destroys hcur.

BOOL SetSystemCursor (
  HCURSOR hcur,  // handle to cursor
  DWORD id       // system cursor identifier
);

Parameters

hcur
[in] 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
[in] Specifies the system cursor to replace with the contents of hcur. This parameter can be one of the following values.
Value | Meaning
OCR_APPSTARTING | Standard arrow and small hourglass
OCR_NORMAL | Standard arrow
OCR_CROSS | Crosshair
OCR_HAND | Windows 2000 or 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
);

Parameters

bShow
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Cursors Overview, Cursor Functions, ClipCursor, GetCursorPos, SetCursor, SetCursorPos


Cursor Structures

The following structure is used with cursors.

CURSORINFO


CURSORINFO

The CURSORINFO structure contains global cursor information.

typedef struct tagCURSORINFO {
  DWORD   cbSize;
  DWORD   flags;
  HCURSOR hCursor;
  POINT   ptScreenPos;
} CURSORINFO, *PCURSORINFO, *LPCURSORINFO;

Members

cbSize
Specifies the size, in bytes, of the structure.
flags
Specifies the cursor state. This parameter can be one of the following values.
Value | Meaning
0 | The cursor is hidden.
CURSOR_SHOWING | The cursor is showing.

hCursor
Handle to the cursor.
ptScreenPos
A POINT structure that receives the screen coordinates of the cursor.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP6 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Cursors Overview, Cursor Structures, GetCursorInfo, POINT


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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_SETCURSOR
  WPARAM wParam,   // handle to window (HWND)
  LPARAM lParam    // hit-test code and mouse message
);

Parameters

wParam
Handle to the window that contains the cursor.
lParam
The low-order word of lParam specifies the hit-test code.

The high-order word of lParam specifies the identifier of the mouse message.

Return Values

If an application processes this message, it should return TRUE to halt further processing or FALSE to continue.

Remarks

The high-order word of lParam is zero when the window enters menu mode.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Cursors Overview, Cursor Messages, DefWindowProc, HIWORD, LOWORD, 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
  • Using Icons
  • Icon Reference


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, animate, and destroy icons. This overview provides information on the following topics:

  • Icon Hot Spot
  • Icon Types
  • Icon Sizes
  • Icon Creation
  • Icon Display
  • Icon Destruction
  • Icon Duplication

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
  • Shell large

The system small icon is displayed in the window caption.

To change the size of the system small icon

  1. From Control Panel, click Display, then click the Appearance tab.
  2. Select Caption Buttons from the Item list, then set the Size field.

To retrieve the size of the system small icon

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

To retrieve the size of the system large icon

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

  1. Use the SHGetFileInfo function with SHGFI_SHELLICONSIZE | SHGFI_SMALLICON to retrieve a handle to the system image list.
  2. Then call 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

  1. From Control Panel , click Display, then click the Appearance tab,
  2. 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).
  3. Click the Plus! tab and then select the Use Large Icons check box.

To retrieve the size of the shell large icon

  1. Use the SHGetFileInfo function with SHGFI_SHELLICONSIZE to retrieve a handle to the system image list.
  2. Then call 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 of 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®/Windows® 2000 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.

To display an animated icon, use a static control as shown in the following code fragment.

hIcon = LoadImage(NULL, "ico.ani", IMAGE_ICON, 0, 0, LR_LOADFROMFILE);
SendMessage( hStatic, STM_SETIMAGE, IMAGE_ICON, (LPARAM)(UINT)hIcon);


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.

The DuplicateIcon function makes an actual copy of the icon.


Using Icons

The 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;   // pointer to 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.

Function | Description
CopyIcon | Copies an icon from another module.
CreateIcon | Creates an icon with a specified size, color, and bit pattern.
CreateIconFromResource | Creates an icon or cursor from resource bits.
CreateIconFromResourceEx | Creates an icon or cursor from resource bits.
CreateIconIndirect | Creates an icon or cursor from an ICONINFO structure.
DestroyIcon | Destroys an icon.
DrawIcon | Draws an icon.
DrawIconEx | Draws an icon or cursor, performing raster operations, and stretching or compressing the icon or cursor.
DuplicateIcon | Creates a duplicate of a specified icon.
ExtractAssociatedIcon | Gets a handle to an indexed icon in a file or an icon found in an executable file.
ExtractIcon | Gets a handle to an icon from an executable file, dynamic-link library (DLL), or icon file.
ExtractIconEx | Gets an array of handles to large or small icons extracted from an executable file, dynamic-link library (DLL), or icon file.
GetIconInfo | Gets information about an icon or cursor.
LoadIcon | Loads an icon from the executable file associated with an application.
LookupIconIdFromDirectory | Searches for an icon or cursor that best fits the current display device.
LookupIconIdFromDirectoryEx | Searches for an icon or cursor that best fits the current display device.


CopyIcon

The CopyIcon function copies the specified icon from another module to the current module.

HICON CopyIcon(
  HICON hIcon   // handle to icon
);

Parameters

hIcon
[in] 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.

Before closing, an application must call the DestroyIcon function to free any system resources associated with the icon.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Icons Overview, Icon Functions, CopyCursor, DestroyIcon , 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 BPP in XOR bitmask
  CONST BYTE *lpbANDbits, // AND bitmask
  CONST BYTE *lpbXORbits  // XOR bitmask
);

Parameters

hInstance
[in] Handle to the instance of the module creating the icon.
nWidth
[in] Specifies the width, in pixels, of the icon.
nHeight
[in] Specifies the height, in pixels, of the icon.
cPlanes
[in] Specifies the number of planes in the XOR bitmask of the icon.
cBitsPixel
[in] Specifies the number of bits-per-pixel in the XOR bitmask of the icon.
lpbANDbits
[in] 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
[in] 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

For an example, see Creating an Icon.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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.

To specify a desired height or width, use the CreateIconFromResourceEx function.

HICON CreateIconFromResource(
  PBYTE presbits,  // icon or cursor bits
  DWORD dwResSize, // number of bytes in bit buffer
  BOOL fIcon,      // icon or cursor
  DWORD dwVer      // format version
);

Parameters

presbits
[in] 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
[in] Specifies the size, in bytes, of the set of bits pointed to by the presbits parameter.
fIcon
[in] 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
[in] 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 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 throughout the system.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Icons Overview, Icon Functions, 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, // icon or cursor bits
  DWORD cbIconBits, // number of bytes in bit buffer
  BOOL fIcon,       // icon or cursor
  DWORD dwVersion,  // format version
  int cxDesired,    // desired width of icon or cursor
  int cyDesired,    // desired height of icon or cursor
  UINT uFlags       // load resource options
);

Parameters

pbIconBits
[in] 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
[in] Specifies the size, in bytes, of the set of bits pointed to by the pbIconBits parameter.
fIcon
[in] 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
[in] 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
[in] 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
[in] 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
[in] 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 CreateIconFromResource, CreateIconFromResourceEx, CreateIconIndirect, GetIconInfo, and LookupIconIdFromDirectoryEx functions allow shell applications and icon browsers to examine and use resources throughout the system.

For an example, see Sharing Icon Resources.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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   // icon information
);

Parameters

piconinfo
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
);

Parameters

hIcon
[in] 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 and the CopyIcon functions. 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)

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Icons Overview, Icon Functions, CopyIcon, CreateIconIndirect


DrawIcon

The DrawIcon function draws an icon or cursor into the specified device context.

To specify additional drawing options, use the DrawIconEx function.

BOOL DrawIcon(
  HDC hDC,      // handle to DC
  int X,        // x-coordinate of upper-left corner
  int Y,        // y-coordinate of upper-left corner
  HICON hIcon   // handle to icon
);

Parameters

hDC
[in] Handle to the device context into which the icon or cursor will be drawn.
X
[in] Specifies the logical x-coordinate of the upper-left corner of the icon.
Y
[in] Specifies the logical y-coordinate of the upper-left corner of the icon.
hIcon
[in] Handle to the icon to be drawn.

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.

For an example, see Displaying an Icon.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Icons Overview, Icon Functions, CreateIcon, DrawIconEx, LoadIcon


DrawIconEx

The DrawIconEx function draws an icon or cursor into 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-coord of upper left corner
  int yTop,                  // y-coord of upper left corner
  HICON hIcon,               // handle to icon
  int cxWidth,               // icon width
  int cyWidth,               // icon height
  UINT istepIfAniCur,        // frame index, animated cursor
  HBRUSH hbrFlickerFreeDraw, // handle to background brush
  UINT diFlags               // icon-drawing flags
);

Parameters

hdc
[in] Handle to the device context into which the icon or cursor will be drawn.
xLeft
[in] Specifies the logical x-coordinate of the upper-left corner of the icon or cursor.
yTop
[in] Specifies the logical y-coordinate of the upper-left corner of the icon or cursor.
hIcon
[in] Handle to the icon or cursor to be drawn. This parameter can identify an animated cursor.
cxWidth
[in] 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
[in] 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
[in] 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
[in] 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
[in] 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_NOMIRROR | Whistler: Draws the icon as an unmirrored icon. By default, the icon is drawn as a mirrored icon if hdc is mirrored.
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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Icons Overview, Icon Functions, CopyImage, LoadImage


DuplicateIcon

The DuplicateIcon function creates a duplicate of a specified icon.

HICON DuplicateIcon(
  HINSTANCE hInst,      // not used
  HICON hIcon,          // handle to icon
);

Parameters

hInst
[in] This parameter is not used; it can be NULL.
hIcon
[in] Handle to the icon to be duplicated.

Return Values

If successful, the function returns the handle to the new icon that was created. If unsuccessful, it returns NULL.

Remarks

You must destroy the icon handle returned by DuplicateIcon by calling the DestroyIcon function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Shellapi.h.
Library: Use Shell32.lib.

See Also

Icons Overview, Icon Functions, DestroyIcon


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,  // file name
  LPWORD lpiIcon      // icon index
);

Parameters

hInst
[in] Specifies the instance of the application calling the function.
lpIconPath
[in] Pointer to a string that specifies the full path and file name of the file that contains the icon. 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 file name of that executable in the string pointed to by lpIconPath.

lpiIcon
[in] 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 file name 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 file name extensions, are stored in the per-user part of the registry, and can be defined using File Manager's Associate command.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Shellapi.h.
Library: Use Shell32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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,  // file name
  UINT nIconIndex           // icon index
);

Parameters

hInst
[in] Handle to the instance of the application calling the function.
lpszExeFileName
[in] Pointer to a null-terminated string specifying the name of an executable file, DLL, or icon file.
nIconIndex
[in] 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/98, Windows NT 4.0, and Windows 2000 or 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Shellapi.h.
Library: Use Shell32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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,        // file name
  int nIconIndex,          // icon index
  HICON *phiconLarge,      // large icon array
  HICON *phiconSmall,      // small icon array
  UINT nIcons              // number of icons to extract
);

Parameters

lpszFile
[in] Pointer to a null-terminated string specifying the name of an executable file, DLL, or icon file from which icons will be extracted.
nIconIndex
[in] 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/98, Windows NT 4.0, and Windows 2000 or 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
[out] Pointer to an array of icon handles that receives handles to the large icons extracted from the file. If this parameter is NULL, no large icons are extracted from the file.
phiconSmall
[out] Pointer to an array of icon handles that receives handles to the small icons extracted from the file. If this parameter is NULL, no small icons are extracted from the file.
nIcons
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Shellapi.h.
Library: Use Shell32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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   // icon structure
);

Parameters

hIcon
[in] 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 2000 or 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
[out] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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.

Note This function has been superseded by the LoadImage function.

HICON LoadIcon(
  HINSTANCE hInstance, // handle to application instance
  LPCTSTR lpIconName   // name string or resource identifier
);

Parameters

hInstance
[in] 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
[in] 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.

For an example, see Creating an Icon.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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.

To specify a desired height or width, use the LookupIconIdFromDirectoryEx function.

int LookupIconIdFromDirectory(
  PBYTE presbits,  // resource data
  BOOL fIcon       // icon or cursor
);

Parameters

presbits
[in] 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
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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, // resource data
  BOOL fIcon,     // icon or cursor
  int cxDesired,  // width of icon or cursor
  int cyDesired,  // height of icon or cursor
  UINT Flags      // resource options
);

Parameters

presbits
[in] 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
[in] 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
[in] 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
[in] 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
[in] 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.

For an example, see Sharing Icon Resources.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 {
   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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Unicode: Declared 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

The WM_ERASEBKGND message is sent 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_ERASEBKGND
  WPARAM wParam,   // handle to device context (HDC)
  LPARAM lParam    // not used
);

Parameters

wParam
Handle to the device context.
lParam
This parameter is not used.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Icons Overview, Icon Messages, BeginPaint, DefWindowProc, PAINTSTRUCT, WM_ICONERASEBKGND, WNDCLASS


WM_ICONERASEBKGND

On Windows versions prior to Windows 95 and Windows NT 4.0, 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. This message is not sent by newer versions of Windows.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_ICONERASEBKGND
  WPARAM wParam,   // handle to device context (HDC)
  LPARAM lParam    // not used
);

Parameters

wParam
Handle to the device context of the icon.
lParam
This parameter is not used.

Return Values

An application should return nonzero if it processes this message.

Remarks

On Windows versions prior to Windows 95 and Windows NT 4.0, the DefWindowProc function fills the icon background with the class background brush of the parent window. On newer versions of Windows, the DefWindowProc function ignores the message.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Icons Overview, Icon Messages, DefWindowProc, WM_ERASEBKGND


WM_PAINTICON

On Windows versions prior to Windows 95 and Windows NT 4.0, the WM_PAINTICON message is sent to a minimized window when the icon is to be painted. This message is not sent by newer versions of Windows, except in unusual circumstances explained in the Remarks.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_PAINTICON
  WPARAM wParam,   // not used
  LPARAM lParam    // not used
);

Parameters

This message has no parameters.

Return Values

An application should return zero if it processes this message.

Remarks

On Windows 95 and higher and Windows NT 4.0 and higher, this message is sent only to 16-bit windows (note that this is with a lowercase "W"), and only for compatibility reasons. Under such conditions, the value of wParam is TRUE (the value carries no significance).

On Windows versions prior to Windows 95 and Windows NT 4.0, or on newer versions of Windows when the unusual circumstances above are met, the window receives this message only if a class icon is defined for the window; otherwise, WM_PAINT is sent instead.

On Windows versions prior to Windows 95 and Windows NT 4.0, the DefWindowProc function draws the class icon. On newer versions of Windows, the DefWindowProc function ignores the message.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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
  • Using Menus
  • Menu Reference


About Menus

A menu is a list of items that specify options or groups of options (a submenu) for an application . Clicking a menu item opens a submenu or causes the application to carry out a command. This overview provides information on the following topics:

  • 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; which contains a list of menus, which in turn can contain 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 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. To get information about a menu bar, call GetMenuBarInfo.

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

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 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 a handle to a menu bar when you create the menu or load a menu resource. For more information, see Menu Creation.

To retrieve a handle to the menu bar for a menu that has been created or loaded, use the GetMenu function. To retrieve a handle to the submenu associated with a menu item, use the GetSubMenu or GetMenuItemInfo function. To retrieve a 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
  • Selected and Clear 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 a 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 a 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.

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.


Selected and Clear Menu Items

A menu item can be either selected or clear. The system displays a bitmap next to selected menu items to indicate their selected state. The system does not display a bitmap next to clear items, unless an application-defined "clear" bitmap is specified. Only menu items in a menu can be selected; items in a menu bar cannot be selected.

Applications typically check or clear 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 clear. 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 selected. 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 selected or cleared.

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 selected radio menu item (analogous to a radio button control). Selected 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 selected menu items and no bitmap next to cleared menu items. However, you can use the SetMenuItemBitmaps function to associate application-defined selected and cleared bitmaps with a menu item. The system then uses the specified bitmaps to indicate the menu item's selected or cleared 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), selected, and cleared 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 a handle to the menu, which you can then assign to a window by using the SetMenu function. You can assign a menu to any window that is not a child window.

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. You can save certain settings information for a menu by using the MENUINFO structure. To get or retrieve the settings of a menu, use GetMenuInfo or SetMenuInfo . 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 a 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.

You can assign a menu to any window that is not a child window.

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. To end the calling thread's active menu, use EndMenu. If a platform does not support EndMenu, send the owner of the active menu a WM_CANCELMODE message.


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.

You can save information for a menu using the MENUINFO structure. If the menu is defined with a MENUINFO.dwStyle value of MNS_NOTIFYBYPOS, the system sends WM_MENUCOMMAND instead of the WM_COMMAND when an item is selected. This allows you to access the information in the MENUINFO structure and also provides the index of the selected item directly.

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.

The WM_MENURBUTTONUP message is sent when the user releases the right mouse button while the cursor is on a menu item. This message is provided so that applications can display a context-sensitive or shortcut menu for a menu item.

There are a few messages that only involve drag-and-drop menus. The WM_MENUGETOBJECT is sent to the owner of a drag-and-drop menu when the mouse cursor enters a menu item or moves from the center of an item to the top or the bottom of an item. The WM_MENUDRAG message is sent when the user actually drags a menu item.

When a drop-down menu or a submenu has been destroyed, the system sends a WM_UNINITMENUPOPUP message.


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 is a pointer 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, selected, or cleared.

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, selected, or cleared. 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 is a pointer 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 Microsoft® 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 a 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 specified class, the system automatically assigns the specified menu to the window.

You cannot assign a menu to a window that is a child 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 a pointer to 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) != 0 && GetMessage(&msg, (HWND) NULL, 0, 0) != -1)
    {
        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 a 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 words 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 a 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
    // a 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 MIIM_BITMAP flag for the menu item and specify a handle to the bitmap that the system should display for the menu item in the hbmpItem member of the MENUITEMINFO structure. This section describes how to set the MIIM_BITMAP flag and retrieve a 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 MIIM_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 MIIM_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 MIIM_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 MIIM_BITMAP or MF_BITMAP type flag for a menu item, you must also specify a 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_BITMAP | MIIM_DATA;
        mii.wID = uID + i;
        mii.hbmpItem = &paHbm[i];
        InsertMenuItem(hmenuPopup, i, TRUE, &mii);
    }

    // Add a menu name to the menu bar.

    mii.fMask = MIIM_STRING | 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

• Owner-Drawn Menus and the WM_MEASUREITEM Message

• Owner-Drawn Menus and the WM_DRAWITEM Message

• Owner-Drawn Menus and the WM_MENUCHAR Message

• Setting Fonts for Menu-Item Text Strings

• Example of Owner-Drawn Menu Items


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 a pointer to a MENUITEMINFO structure, which specifies 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_FTYPE 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 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 a handle to the logical font 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 selected) 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:

  • Determine the type of drawing that is necessary. To do so, check the itemAction member of the DRAWITEMSTRUCT structure.
  • 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.
  • 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 pressing ALT and pressing 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 one 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 specified font attribute and returns a 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:

  • Allocates an application-defined MYITEM structure.
  • Gets the text of the menu item and saves it in the application-defined MYITEM structure.
  • Creates the font used to display the menu item and saves its handle in the application-defined MYITEM structure.
  • 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.

The 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

The 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 a 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_STRING;
        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_FTYPE | 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 a 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

Platform SDK: Windows User Interface

Using Custom Check-Mark Bitmaps

The system provides a default check-mark bitmap for displaying next to a menu item that is selected. 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 selected and the other when it is clear. This section describes the steps involved in creating and using custom check-mark bitmaps.


Creating Custom Check Mark Bitmaps

Platform SDK: Windows User Interface

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

    Note 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 clear bitmap, and the hBitmapChecked parameter identifies the selected 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 selected or cleared. You can specify the MF_CHECKED value to set the check-mark attribute to selected and the MF_UNCHECKED value to set it to clear.

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 selected check box and the bitmap with an empty box. The selected 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 clear 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 selected and empty check boxes, copies them to two separate bitmaps, and then uses them as the selected and cleared bitmaps for items in the Character menu.

To retrieve a 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 selected and, by default, the check-mark attribute of the remaining items is set to clear.

#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
                    // checkmarks 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 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 a 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 checkmarks 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 selected or cleared. For these menu items, the example uses check-mark bitmaps that resemble the selected and cleared 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 selected at any time. For these menu items, the example uses check-mark bitmaps that resemble the selected and clear 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 a 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 selected and cleared 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);

The 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 a 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 a 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 a 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 check-mark bitmaps for each menu item.

    for (uID = IDM_BOLD; uID <= IDM_UNDERLINE; uID++)
    {
        SetMenuItemBitmaps(hmenuPopup, uID, MF_BYCOMMAND,
                hbmUnchecked, hbmChecked);
    }

    // Get a 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 check-mark 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 a 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 a 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 Information

GetMenuInfo
SetMenuInfo
MENUGETOBJECTINFO
MENUINFO

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 EndMenu
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_MENUCOMMAND
WM_MENUDRAG
WM_MENUGETOBJECT
WM_MENURBUTTONUP
WM_MENUSELECT
WM_SYSCOMMAND
WM_UNINITMENUPOPUP


Menu Functions

The following functions are used with menus.

Function | Description
AppendMenu | Appends an item to various menus and submenus.
CheckMenuItem | Checks or clears a menu item.
CheckMenuRadioItem | Checks a specified menu item and makes it a radio item.
CreateMenu | Creates a menu.
CreatePopupMenu | Creates a drop-down menu, submenu, or shortcut menu.
DeleteMenu | Deletes a menu item.
DestroyMenu | Deletes a menu.
DrawMenuBar | Redraws a menu bar.
EnableMenuItem | Enables, disables, or grays a menu item.
EndMenu | Ends the calling thread's active menu.
GetMenu | Gets a handle to the menu.
GetMenuBarInfo | Gets information about a menu bar.
GetMenuCheckMarkDimensions | Returns the dimensions of the default check-mark bitmap.
GetMenuDefaultItem | Gets the default menu item on a menu.
GetMenuInfo | Gets information about a menu.
GetMenuItemCount | Gets the number of items in a menu.
GetMenuItemID | Gets the identifier of a menu item.
GetMenuItemInfo | Gets information about a menu item.
GetMenuItemRect | Gets the bounding rectangle for a menu item.
GetMenuState | Gets the menu flags associated with a menu item.
GetMenuString | Copies the text string of a menu item into a buffer.
GetSubMenu | Gets a handle to the drop-down menu or submenu activated by a menu item.
GetSystemMenu | Allows copying or modifying of a window menu.
HiliteMenuItem | Highlights or removes the highlighting from an item in a menu bar.
InsertMenu | Inserts a new menu item into a menu.
InsertMenuItem | Inserts a new menu item in a menu.
IsMenu | Determines when a handle is a menu handle.
LoadMenu | Loads a menu resource.
LoadMenuIndirect | Loads a specified menu template.
MenuItemFromPoint | Determines which menu item is at a specified location.
ModifyMenu | Changes an existing menu item.
RemoveMenu | Deletes a menu item or detaches a submenu from a menu.
SetMenu | Assigns a new menu to a window.
SetMenuDefaultItem | Sets the default menu item for a menu.
SetMenuInfo | Sets information for a menu.
SetMenuItemBitmaps | Associates a bitmap with a menu item.
SetMenuItemInfo | Changes information about a menu item.
TrackPopupMenu | Displays a shortcut menu at a location and tracks item selection on a menu.
TrackPopupMenuEx | Displays a shortcut menu at a location and tracks item selection on a shortcut menu.


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.

Note 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
  UINT uFlags,         // menu-item options
  UINT_PTR uIDNewItem, // identifier, menu, or submenu
  LPCTSTR lpNewItem    // menu-item content
);

Parameters

hMenu
[in] Handle to the menu bar, drop-down menu, submenu, or shortcut menu to be changed.
uFlags
[in] 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
[in] Specifies either the identifier of the new menu item or, if the uFlags parameter is set to MF_POPUP, a handle to the drop-down menu or submenu.
lpNewItem
[in] 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 shown in the following table.
Value | Description
MF_BITMAP | Contains a bitmap handle.
MF_OWNERDRAW | Contains an application-supplied value 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 a 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 the 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 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 a 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 is a pointer 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 clear bitmap next to the menu item.

The following groups of flags cannot be used together:

  • MF_BITMAP, MF_STRING, and MF_OWNERDRAW
  • MF_CHECKED and MF_UNCHECKED
  • MF_DISABLED, MF_ENABLED, and MF_GRAYED
  • MF_MENUBARBREAK and MF_MENUBREAK

For an example, see Adding Lines and Graphs to a Menu.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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 selected or clear.

Note 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 options
);

Parameters

hmenu
[in] Handle to the menu of interest.
uIDCheckItem
[in] Specifies the menu item whose check-mark attribute is to be set, as determined by the uCheck parameter.
uCheck
[in] 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 selected state.
MF_UNCHECKED | Sets the check-mark attribute to the clear 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 -1.

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.

For an example, see Simulating Check Boxes in a Menu.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

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 clears all other menu items in the associated group and clears the radio-item type flag for those items.

BOOL CheckMenuRadioItem(
  HMENU hmenu,   // handle to menu
  UINT idFirst,  // identifier or position of first item
  UINT idLast,   // identifier or position of last item
  UINT idCheck,  // identifier or position of menu item
  UINT uFlags    // function options
);

Parameters

hmenu
[in] Handle to the menu that contains the group of menu items.
idFirst
[in] Identifier or position of the first menu item in the group.
idLast
[in] Identifier or position of the last menu item in the group.
idCheck
[in] Identifier or position of the menu item to check.
uFlags
[in] 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 selected 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.

For an example, see Example of Using Custom Check-mark Bitmaps.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 a 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 a 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.

For an example, see Adding Lines and Graphs to a Menu.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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      // option
);

Parameters

hMenu
[in] Handle to the menu to be changed.
uPosition
[in] Specifies the menu item to be deleted, as determined by the uFlags parameter.
uFlags
[in] 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.

For an example, see Example of a Clipboard Viewer.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
);

Parameters

hMenu
[in] 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.

DestroyMenu is recursive, that is, it will destroy the menu and all its submenus.

For an example, see Displaying a Shortcut Menu.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Menus Overview, Menu Functions, CreateMenu, DeleteMenu, RemoveMenu, SetMenuItemInfo


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
);

Parameters

hWnd
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 update
  UINT uEnable         // options
);

Parameters

hMenu
[in] Handle to the menu.
uIDEnableItem
[in] 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
[in] Controls 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 -1.

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

When you change a window menu, the menu bar is not immediately updated. To force the update, call DrawMenuBar.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Menus Overview, Menu Functions, DrawMenuBar, GetMenuItemID, InsertMenu, InsertMenuItem, LoadMenuIndirect, ModifyMenu, SetMenuItemInfo, WM_SYSCOMMAND


EndMenu

The EndMenu function ends the calling thread's active menu.

BOOL EndMenu(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

If a platform does not support EndMenu, send the owner of the active menu a WM_CANCELMODE message.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Menus Overview, Menu Functions, , WM_CANCELMODE


GetMenu

The GetMenu function retrieves a handle to the menu assigned to the specified window.

HMENU GetMenu(
  HWND hWnd  // handle to window
);

Parameters

hWnd
[in] Handle to the window whose menu handle is to be retrieved.

Return Values

The return value is a handle to the menu. If the specified window has no menu, the return value is NULL. If the window is a child window, the return value is undefined.

Remarks

GetMenu does not work on floating menu bars. Floating menu bars are custom controls that mimic standard menus; they are not menus. To get the handle for a floating menu bar, use the Active Accessibility APIs.

For an example, see Adding Lines and Graphs to a Menu.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Menus Overview, Menu Functions, GetSubMenu, SetMenu


GetMenuBarInfo

The GetMenuBarInfo function retrieves information about the specified menu bar.

BOOL GetMenuBarInfo(
  HWND hwnd,         // handle to window
  LONG idObject,     // menu object
  LONG idItem,       // item identifier
  PMENUBARINFO pmbi  // information
);

Parameters

hwnd
[in] Handle to the window (menu bar) whose information is to be retrieved.
idObject
[in] Specifies the menu object. This parameter can be one of the following values.
Value | Meaning
OBJID_CLIENT | The popup menu associated with the window.
OBJID_MENU | The menu bar associated with the window (see the GetMenu function).
OBJID_SYSMENU | The system menu associated with the window (see the GetSystemMenu function).

idItem
[in] Specifies the item for which to retrieve information. If this parameter is zero, the function retrieves information about the menu itself. If this parameter is 1, the function retrieves information about the first item on the menu, and so on.
pmbi
[out] Pointer to a MENUBARINFO structure that receives the 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP6 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Menus Overview, Menu Functions, GetMenu, GetSystemMenu, MENUBARINFO


GetMenuCheckMarkDimensions

The GetMenuCheckMarkDimensions function returns the dimensions of the default check-mark bitmap. The system displays this bitmap next to selected 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.

Note The GetMenuCheckMarkDimensions function is included only for compatibility with 16-bit versions of Windows. For Win32-based applications, use the GetSystemMetrics function with the CXMENUCHECK and CYMENUCHECK values to retrieve the bitmap dimensions.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Menus Overview, Menu Functions, SetMenuItemBitmaps


GetMenuDefaultItem

The GetMenuDefaultItem function determines the default menu item on the specified menu.

UINT GetMenuDefaultItem(
  HMENU hMenu,    // handle to menu
  UINT fByPos,    // retrieval option
  UINT gmdiFlags  // function search option
);

Parameters

hMenu
[in] Handle to the menu for which to retrieve the default menu item.
fByPos
[in] Specifies 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
[in] Specifies 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Menus Overview, Menu Functions, SetMenuDefaultItem


GetMenuInfo

The GetMenuInfo function gets information about a specified menu.

BOOL GetMenuInfo(
  HMENU hmenu,            // handle to menu
  LPCMENUINFO lpcmi       // menu information
);

Parameters

hmenu
[in] Handle for a menu.
lpcmi
[out] Pointer to a MENUINFO structure containing information for the 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.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Menus Overview, Menu Functions


GetMenuItemCount

The GetMenuItemCount function determines the number of items in the specified menu.

int GetMenuItemCount(
  HMENU hMenu  // handle to menu
);

Parameters

hMenu
[in] 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.

For an example, see Example of Menu-Item Bitmaps.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
[in] Handle to the menu that contains the item whose identifier is to be retrieved.
nPos
[in] Specifies the zero-based relative position of the menu item whose identifier is to be retrieved.

Return Values

The return value is the identifier of the specified menu item. If the menu item identifier is NULL or if the specified item opens a submenu, the return value is -1.

For an example, see Example of a Clipboard Viewer.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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,          // handle to menu
  UINT uItem,           // menu item
  BOOL fByPosition,     // meaning of uItem
  LPMENUITEMINFO lpmii  // menu item information
);

Parameters

hMenu
[in] Handle to the menu that contains the menu item.
uItem
[in] Identifier or position of the menu item to get information about. The meaning of this parameter depends on the value of fByPosition.
fByPosition
[in] Specifies the meaning of uItem. If this parameter is FALSE, uItem is a menu item identifier. Otherwise, it is a menu item position.
lpmii
[in/out] 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

To retrieve a menu item of type MFT_STRING, first find the size of the string by setting the dwTypeData member of MENUITEMINFO to NULL and then calling GetMenuItemInfo. The value of cch is the size needed. Then allocate a buffer of this size, place the pointer to the buffer in dwTypeData, and call GetMenuItemInfo once again to fill the buffer with the string.

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 and sets cch to 0.

Windows 2000 and Windows 98: dwTypeData and cch are used with MIIM_STRING.

For an example, see Example of Owner-Drawn Menu Items.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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,       // handle to window
  HMENU hMenu,     // handle to menu
  UINT uItem,      // menu item position
  LPRECT lprcItem  // bounding rectangle
);

Parameters

hWnd
[in] Handle to the window containing the menu.

Windows 98 and Windows 2000 or later: If this value is NULL and the hMenu parameter represents a popup menu, the function will find the menu window.

hMenu
[in] Handle to a menu.
uItem
[in] Zero-based position of the menu item.
lprcItem
[out] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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.

Note 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  // options
);

Parameters

hMenu
[in] Handle to the menu that contains the menu item whose flags are to be retrieved.
uId
[in] Specifies the menu item for which the menu flags are to be retrieved, as determined by the uFlags parameter.
uFlags
[in] 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 -1.

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 | Meaning
MF_CHECKED | A check mark is placed next to the item (for drop-down menus, submenus, and shortcut menus only).
MF_DISABLED | The item is disabled.
MF_GRAYED | The item is disabled and grayed.
MF_HILITE | The item is highlighted.
MF_MENUBARBREAK | This is 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 | The item is placed on a new line (for menu bars) or in a new column (for drop-down menus, submenus, and shortcut menus) without separating columns.
MF_OWNERDRAW | The item is owner-drawn.
MF_POPUP | Menu item is a submenu.
MF_SEPARATOR | There is a horizontal dividing line (for drop-down menus, submenus, and shortcut menus only).

Remarks

In addition, it is possible to test an item for a flag value of MF_ENABLED, MF_STRING, MF_UNCHECKED, or MF_UNHILITE. However, since these values equate to zero you must use an expression to test for them.

Flag | Expression to test for the flag
MF_ENABLED | ! (Flag~(MF_DISABLED | MF_GRAYED))
MF_STRING | ! (Flag~(MF_BITMAP | MF_OWNERDRAW))
MF_UNCHECKED | ! (Flag~MF_CHECKED)
MF_UNHILITE | ! (Flag~HILITE)

For an example, see Simulating Check Boxes in a Menu.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

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.

Note The GetMenuString 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,  // buffer for the string
  int nMaxCount,    // maximum length of string
  UINT uFlag        // options
);

Parameters

hMenu
[in] Handle to the menu.
uIDItem
[in] Specifies the menu item to be changed, as determined by the uFlag parameter.
lpString
[out] Pointer to the buffer that receives the null-terminated string.

If lpString is NULL, the function returns the length of the menu string.

nMaxCount
[in] 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
[in] 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.

If the specified item is not of type MFT_STRING, then the return value is zero.

Windows 98 and Windows 2000 or later: MIIM_STRING supersedes MFT_STRING.

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.

For an example, see Creating User-Editable Accelerators.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Menus Overview, Menu Functions, GetMenuItemID


GetSubMenu

The GetSubMenu function retrieves a 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
[in] Handle to the menu.
nPos
[in] Specifies the zero-based relative position in the specified menu of an item that activates a drop-down menu or submenu.

Return Values

If the function succeeds, the return value is a 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.

For an example, see Displaying a Shortcut Menu.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
  BOOL bRevert  // reset option
);

Parameters

hWnd
[in] Handle to the window that will own a copy of the window menu.
bRevert
[in] Specifies the action to be taken. If this parameter is FALSE, GetSystemMenu returns a 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 a 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Menus Overview, Menu Functions, GetMenu, InsertMenuItem, SetMenuItemInfo, 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 window
  HMENU hmenu,       // handle to menu
  UINT uItemHilite,  // menu item
  UINT uHilite       // highlight options
);

Parameters

hwnd
[in] Handle to the window that contains the menu.
hmenu
[in] Handle to the menu bar that contains the item to be highlighted.
uItemHilite
[in] 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
[in] Controls 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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.

Note 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,       // item that new item precedes
  UINT uFlags,          // options
  UINT_PTR uIDNewItem,  // identifier, menu, or submenu
  LPCTSTR lpNewItem     // menu item content
);

Parameters

hMenu
[in] Handle to the menu to be changed.
uPosition
[in] Specifies the menu item before which the new menu item is to be inserted, as determined by the uFlags parameter.
uFlags
[in] 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 -1, the new menu item is appended to the end of the menu.

uIDNewItem
[in] Specifies either the identifier of the new menu item or, if the uFlags parameter has the MF_POPUP flag set, a handle to the drop-down menu or submenu.
lpNewItem
[in] 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 an application-supplied value 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 a 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 a 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 is a pointer 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 clear 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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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 InsertMenuItem(
  HMENU hMenu,           // handle to menu
  UINT uItem,            // identifier or position
  BOOL fByPosition,      // meaning of uItem
  LPCMENUITEMINFO lpmii  // menu item information
);

Parameters

hMenu
[in] Handle to the menu in which the new menu item is inserted.
uItem
[in] 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
[in] 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
[in] 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

The application must call the DrawMenuBar function whenever a menu changes, whether or not the menu is in a displayed window.

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.

For an example, see Example of Menu-Item Bitmaps.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Menus Overview, Menu Functions, DrawMenuBar, MENUITEMINFO


IsMenu

The IsMenu function determines whether a handle is a menu handle.

BOOL IsMenu(
  HMENU hMenu  // handle to test
);

Parameters

hMenu
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 module
  LPCTSTR lpMenuName    // menu name or resource identifier
);

Parameters

hInstance
[in] Handle to the module containing the menu resource to be loaded.
lpMenuName
[in] 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 a 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.

For an example, see Displaying a Shortcut Menu.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Menus Overview, Menu Functions, LoadMenuIndirect, MAKEINTRESOURCE


LoadMenuIndirect

The LoadMenuIndirect function loads the specified menu template in memory.

HMENU LoadMenuIndirect(
  CONST MENUTEMPLATE *lpMenuTemplate  // menu template
);

Parameters

lpMenuTemplate
[in] 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 a 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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.

int MenuItemFromPoint(
  HWND hWnd,      // handle to window
  HMENU hMenu,    // handle to menu
  POINT ptScreen  // location to test
);

Parameters

hWnd
[in] Handle to the window containing the menu.

Windows 98 and Windows 2000 or later: If this value is NULL and the hMenu parameter represents a popup menu, the function will find the menu window.

hMenu
[in] Handle to the menu containing the menu items to hit test.
ptScreen
[in] A POINT structure that specifies 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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.

Note 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,          // options
  UINT_PTR uIDNewItem,  // identifier, menu, or submenu
  LPCTSTR lpNewItem     // menu item content
);

Parameters

hMnu
[in] Handle to the menu to be changed.
uPosition
[in] Specifies the menu item to be changed, as determined by the uFlags parameter.
uFlags
[in] 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
[in] Specifies either the identifier of the modified menu item or, if the uFlags parameter has the MF_POPUP flag set, a handle to the drop-down menu or submenu.
lpNewItem
[in] 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 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 a 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 selected 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 a 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 is a pointer 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 a clear 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

For an example, see Setting Fonts for Menu-Item Text Strings.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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 a handle to the drop-down menu or submenu.

BOOL RemoveMenu(
  HMENU hMenu,     // handle to menu
  UINT uPosition,  // menu item identifier or position
  UINT uFlags      // options
);

Parameters

hMenu
[in] Handle to the menu to be changed.
uPosition
[in] Specifies the menu item to be deleted, as determined by the uFlags parameter.
uFlags
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
[in] Handle to the window to which the menu is to be assigned.
hMenu
[in] 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. A menu can be assigned to any window that is not a child window.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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,  // handle to menu
  UINT uItem,   // identifier or position
  UINT fByPos   // meaning of uItem
);

Parameters

hMenu
[in] Handle to the menu to set the default item for.
uItem
[in] 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
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Menus Overview, Menu Functions, GetMenuDefaultItem


SetMenuInfo

The SetMenuInfo function sets information for a specified menu.

BOOL SetMenuInfo(
  HMENU hmenu,       // handle to menu
  LPCMENUINFO lpcmi  // menu information
);

Parameters

hmenu
[in] Handle to a menu.
lpcmi
[in] Pointer to a MENUINFO structure for the 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.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Menus Overview, Menu Functions


SetMenuItemBitmaps

The SetMenuItemBitmaps function associates the specified bitmap with a menu item. Whether the menu item is selected or clear, the system displays the appropriate bitmap next to the menu item.

BOOL SetMenuItemBitmaps(
  HMENU hMenu,               // handle to menu
  UINT uPosition,            // menu item
  UINT uFlags,               // options
  HBITMAP hBitmapUnchecked,  // handle to unchecked bitmap
  HBITMAP hBitmapChecked     // handle to checked bitmap
);

Parameters

hMenu
[in] Handle to the menu containing the item to receive new check-mark bitmaps.
uPosition
[in] Specifies the menu item to be changed, as determined by the uFlags parameter.
uFlags
[in] 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
[in] Handle to the bitmap displayed when the menu item is not selected.
hBitmapChecked
[in] Handle to the bitmap displayed when the menu item is selected.

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 selected, and removes the bitmap when the item is not selected.

When the menu is destroyed, these bitmaps are not destroyed; it is up to the application to destroy them.

The selected and clear 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.

For an example, see Simulating Check Boxes in a Menu.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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,          // handle to menu
  UINT uItem,           // identifier or position
  BOOL fByPosition,     // meaning of uItem
  LPMENUITEMINFO lpmii  // menu item information
);

Parameters

hMenu
[in] Handle to the menu that contains the menu item.
uItem
[in] Identifier or position of the menu item to change. The meaning of this parameter depends on the value of fByPosition.
fByPosition
[in] 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
[in] 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

The application must call the DrawMenuBar function whenever a menu changes, whether or not the menu is in a displayed window.

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.

For an example, see Example of Owner-Drawn Menu Items.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Menus Overview, Menu Functions, DrawMenuBar, 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.

To specify an area of the screen the menu should not overlap, use the TrackPopupMenuEx function.

BOOL TrackPopupMenu(
  HMENU hMenu,         // handle to shortcut menu
  UINT uFlags,         // options
  int x,               // horizontal position
  int y,               // vertical position
  int nReserved,       // reserved, must be zero
  HWND hWnd,           // handle to owner window
  CONST RECT *prcRect  // ignored
);

Parameters

hMenu
[in] 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 a handle to a submenu associated with an existing menu item.
uFlags
[in] Use zero of more of these flags to specify function options.

Use one of the following flags 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 flags 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 flags 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 flags 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.

Windows 98/Me, Windows 2000 or later: Use any reasonable combination of the following flags to modify the animation of a menu. For example, by selecting a horizontal and a vertical flag you can achieve diagonal animation.
Value | Meaning
TPM_HORNEGANIMATION | Animates the menu from right to left.
TPM_HORPOSANIMATION | Animates the menu from left to right.
TPM_NOANIMATION | Displays menu without animation.
TPM_VERNEGANIMATION | Animates the menu from bottom to top.
TPM_VERPOSANIMATION | Animates the menu from top to bottom.

For any animation to occur, the SystemParametersInfo function must set SPI_SETMENUANIMATION. Also, all the TPM_*ANIMATION flags, except TPM_NOANIMATION, are ignored if menu fade animation is on, See the SPI_GETMENUFADE flag in SystemParametersInfo.

Windows 98/Me, Windows 2000 or later: Use the TPM_RECURSE flag to display a menu when another menu is already displayed. This is intended to support context menus within a menu.

Whistler: To have text layout from right-to-left, use TPM_LAYOUTRTL. By default, the text layout is left-to-right.

x
[in] Specifies the horizontal location of the shortcut menu, in screen coordinates.
y
[in] Specifies the vertical location of the shortcut menu, in screen coordinates.
nReserved
Reserved; must be zero.
hWnd
[in] 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

To display a context menu for a notification icon, the current window must be the foreground window before the application calls TrackPopupMenu or TrackPopupMenuEx. Otherwise, the menu will not disappear when the user clicks outside of the menu or the window that created the menu (if it is visible). However, when the current window is the foreground window, the second time this menu is displayed, it displays and then immediately disappears. To correct this, you must force a task switch to the application that called TrackPopupMenu at some time in the near future. This is done by posting a benign message to the window or thread, as shown in the following code sample:

   SetForegroundWindow(hDlg);

   // Display the menu
   TrackPopupMenu(   hSubMenu,
                     TPM_RIGHTBUTTON,
                     pt.x,
                     pt.y,
                     0,
                     hDlg,
                     NULL);

   PostMessage(hDlg, WM_NULL, 0, 0);

For an example, see Displaying a Shortcut Menu.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Menus Overview, Menu Functions, CreatePopupMenu, GetSubMenu, RECT, SystemParametersInfo, TrackPopupMenuEx, 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,       // handle to shortcut menu
  UINT fuFlags,      // options
  int x,             // horizontal position
  int y,             // vertical position
  HWND hwnd,         // handle to window
  LPTPMPARAMS lptpm  // area not to overlap
);

Parameters

hmenu
[in] 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 a handle to a submenu associated with an existing menu item.
fuFlags
[in] Specifies function options.

Use one of the following flags 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 flags 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 flags 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 flags 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.

Windows 98/Me, Windows 2000 or later: Use any reasonable combination of the following flags to modify the animation of a menu. For example, by selecting a horizontal and a vertical flag you can achieve diagonal animation.
Value | Meaning
TPM_HORNEGANIMATION | Animates the menu from left to right.
TPM_HORPOSANIMATION | Animates the menu from right to left.
TPM_NOANIMATION | Displays menu without animation.
TPM_VERNEGANIMATION | Animates the menu from bottom to top.
TPM_VERPOSANIMATION | Animates the menu from top to bottom.

For any animation to occur, the SystemParametersInfo function must set SPI_SETMENUANIMATION. Also, all the TPM_*ANIMATION flags, except TPM_NOANIMATION, are ignored if menu fade animation is on, See the SPI_GETMENUFADE flag in SystemParametersInfo.

Windows 98/Me, Windows 2000 or later: Use the TPM_RECURSE flag to display a menu when another menu is already displayed. This is intended to support context menus within a menu.

Use one of the following flags to specify whether to accommodate horizontal or vertical alignment.
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.

Whistler: To have text layout from right-to-left, use TPM_LAYOUTRTL. By default, the text layout is left-to-right.

x
[in] Horizontal location of the shortcut menu, in screen coordinates.
y
[in] Vertical location of the shortcut menu, in screen coordinates.
hwnd
[in] 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
[in] 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

To display a context menu for a notification icon, the current window must be the foreground window before the application calls TrackPopupMenu or TrackPopupMenuEx. Otherwise, the menu will not disappear when the user clicks outside of the menu or the window that created the menu (if it is visible).

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Menus Overview, Menu Functions, CreatePopupMenu, GetSubMenu, SystemParametersInfo, TPMPARAMS, WM_COMMAND


Menu Structures

The following structures are used with menus.

MDINEXTMENU
MENUBARINFO
MENUEX_TEMPLATE_HEADER
MENUEX_TEMPLATE_ITEM
MENUGETOBJECTINFO
MENUINFO
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;

Members

hmenuIn
Receives a 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Menus Overview, Menu Structures, WM_NEXTMENU


MENUBARINFO

The MENUBARINFO structure contains menu bar information.

typedef struct tagMENUBARINFO {
  DWORD cbSize;
  RECT  rcBar;
  HMENU hMenu;
  HWND  hwndMenu;
  BOOL  fBarFocused:1;
  BOOL  fFocused:1;
} MENUBARINFO, *PMENUBARINFO;

Members

cbSize
Specifies the size, in bytes, of the structure.
rcBar
Pointer to a RECT structure that specifies the coordinates of the menu bar, popup menu, or menu item.
hMenu
Handle to the menu bar or popup menu.
hwndMenu
Handle to the submenu.
fBarFocused
If the menu bar or popup menu has the focus, this parameter is TRUE. Otherwise, the parameter is FALSE.
fFocused
If the menu item has the focus, this parameter is TRUE. Otherwise, the parameter is FALSE.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP6 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Menus Overview, Menu Structures, GetMenuBarInfo, RECT


MENUEX_TEMPLATE_HEADER

The MENUEX_TEMPLATE_HEADER structure defines the header for an extended menu template. This structure definition 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 DWORD boundaries. To create a menu from an extended menu template in memory, use the LoadMenuIndirect function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.

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. This structure definition is for explanation only; it is not present in any standard header file.

typedef struct {
  DWORD  dwHelpId;
  DWORD  dwType;
  DWORD  dwState;
  DWORD   menuId;
  WORD   bResInfo;
  WCHAR  szText[1];

} MENUEX_TEMPLATE_ITEM;

Members

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 DWORD boundary following the variable-length szText member.
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.
menuId
Menu item identifier. This is an application-defined value that identifies 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.

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 DWORD boundaries. To create a menu from an extended menu template in memory, use the LoadMenuIndirect function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.

See Also

Menus Overview, Menu Structures, LoadMenuIndirect, MENUEX_TEMPLATE_HEADER, MENUITEMINFO


MENUGETOBJECTINFO

The MENUGETOBJECTINFO structure contains information about the menu that the mouse cursor is on.

typedef struct tagMENUGETOBJECTINFO {
  DWORD  dwFlags;
  UINT  uPos;
  HMENU  hmenu;
  PVOID  riid;
  PVOID  pvObj;
} MENUGETOBJECTINFO, *PMENUGETOBJECTINFO;

Members

dwFlags
Position of the mouse cursor with respect to the item indicated by uPos. It can be one of the following values.
Value | Meaning
MNGOF_BOTTOMGAP | Mouse is on the bottom of the item indicated by uPos.
MNGOF_TOPGAP | Mouse is on the top of the item indicated by uPos.

uPos
Position of the item the mouse cursor is on.
hmenu
Handle to the menu the mouse cursor is on.
riid
Identifier of the requested interface. Currently it can only be IDropTarget.
pvObj
Pointer to the interface corresponding to the riid member. This pointer is to be returned by the application when processing the message.

Remarks

The MENUGETOBJECTINFO structure is used only in drag-and-drop menus. When the WM_MENUGETOBJECT message is sent, lParam is a pointer to this structure.

To create a drag-and-drop menu, call SetMenuInfo with MNS_DRAGDROP set.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Menus Overview, Menu Structures, , SetMenuInfo


MENUINFO

The MENUINFO structure contains information about a menu.

typedef struct tagMENUINFO {
  DWORD   cbSize;
  DWORD   fMask;
  DWORD   dwStyle;
  UINT    cyMax;
  HBRUSH  hbrBack;
  DWORD   dwContextHelpID;
  ULONG_PTR  dwMenuData;
} MENUINFO, FAR *LPMENUINFO;
typedef MENUINFO CONST FAR *LPCMENUINFO;

Members

cbSize
Size of the structure, in bytes
fMask
Members to retrieve or set (except for MIM_APPLYTOSUBMENUS). This member can be one or more of the following values.
Value | Meaning
MIM_APPLYTOSUBMENUS | Settings apply to the menu and all of its submenus. SetMenuInfo uses this flag and GetMenuInfo ignores this flag
MIM_BACKGROUND | Retrieves or sets the hbrBack member.
MIM_HELPID | Retrieves or sets the dwContextHelpID member.
MIM_MAXHEIGHT | Retrieves or sets the cyMax member.
MIM_MENUDATA | Retrieves or sets the dwMenuData member.
MIM_STYLE | Retrieves or sets the dwStyle member.

dwStyle
Style of the menu. It can be one or more of the following values.
Value | Meaning
MNS_AUTODISMISS | Menu automatically ends when mouse is outside the menu for approximately 10 seconds.
MNS_CHECKORBMP | The same space is reserved for the check mark and the bitmap. If the check mark is drawn, the bitmap is not. All checkmarks and bitmaps are aligned. Used for menus where some items use checkmarks and some use bitmaps.
MNS_DRAGDROP | Menu items are OLE drop targets or drag sources. Menu owner receives WM_MENUDRAG and WM_MENUGETOBJECT messages.
MNS_MODELESS | Menu is modeless; that is, there is no menu modal message loop while the menu is active.
MNS_NOCHECK | No space is reserved to the left of an item for a check mark. The item can still be selected, but the check mark will not appear next to the item.
MNS_NOTIFYBYPOS | Menu owner receives a WM_MENUCOMMAND message instead of a WM_COMMAND message when the user makes a selection.

cyMax
Maximum height of the menu in pixels. When the menu items exceed the space available, scroll bars are automatically used. The default (0) is the screen height.
hbrBack
Brush to use for the menu's background.
dwContextHelpID
The context help identifier. This is the same value used in GetMenuContextHelpId and SetMenuContextHelpId.
dwMenuData
An application-defined value.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Menus Overview, Menu Structures


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;
  ULONG_PTR dwItemData;
  LPTSTR  dwTypeData;
  UINT    cch;
  HBITMAP hbmpItem;
} MENUITEMINFO, *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_BITMAP | Windows 98/Me, Windows 2000 or later: Retrieves or sets the hbmpItem member.
MIIM_CHECKMARKS | Retrieves or sets the hbmpChecked and hbmpUnchecked members.
MIIM_DATA | Retrieves or sets the dwItemData member.
MIIM_FTYPE | Windows 98/Me, Windows 2000 or later: Retrieves or sets the fType member.
MIIM_ID | Retrieves or sets the wID member.
MIIM_STATE | Retrieves or sets the fState member.
MIIM_STRING | Windows 98/Me, Windows 2000 or later: Retrieves or sets the dwTypeData member.
MIIM_SUBMENU | Retrieves or sets the hSubMenu member.
MIIM_TYPE Retrieves or sets the fType and dwTypeData members.

Windows 98/Me, Windows 2000 or later: MIIM_TYPE is replaced by MIIM_BITMAP, MIIM_FTYPE and MIIM_STRING.

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.

Windows 98/Me, Windows 2000 or later: MFT_BITMAP is replaced by MIIM_BITMAP and hbmpItem
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 value.
MFT_RADIOCHECK | Displays selected 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/98, Windows 2000 or 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.

Windows 98/Me, Windows 2000 or later: MFT_STRING is replaced by MIIM_STRING

The MFT_BITMAP, MFT_SEPARATOR, and MFT_STRING values cannot be combined with one another. Set fMask to MIIM_TYPE to use fType.

Windows 98 and Windows 2000 or later: fType is used only if fMask has a value of MIIM_FTYPE.

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 selected 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 and grays it so that it cannot be selected. This is equivalent to MFS_GRAYED.
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. This is equivalent to MFS_DISABLED.
MFS_HILITE | Highlights the menu item.
MFS_UNCHECKED | Unchecks the menu item. For more information about clear menu items, see the hbmpUnchecked member.
MFS_UNHILITE | Removes the highlight from the menu item. This is the default state.

Set fMask to MIIM_STATE to use fState.

wID
Application-defined 16-bit value that identifies the menu item. Set fMask to MIIM_ID to use wID.
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. Set fMask to MIIM_SUBMENU to use hSubMenu.
hbmpChecked
Handle to the bitmap to display next to the item if it is selected. 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. Set fMask to MIIM_CHECKMARKS to use hbmpChecked.
hbmpUnchecked
Handle to the bitmap to display next to the item if it is not selected. If this member is NULL, no bitmap is used. Set fMask to MIIM_CHECKMARKS to use hbmpUnchecked.
dwItemData
Application-defined value associated with the menu item. Set fMask to MIIM_DATA to use dwItemData.
dwTypeData
Content of the menu item. The meaning of this member depends on the value of fType and is used only if the MIIM_TYPE flag is set in the fMask member.

To retrieve a menu item of type MFT_STRING, first find the size of the string by setting the dwTypeData member of MENUITEMINFO to NULL and then calling GetMenuItemInfo. The value of cch is the size needed. Then allocate a buffer of this size, place the pointer to the buffer in dwTypeData, and call GetMenuItemInfo once again to fill the buffer with the string. 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 contain a value whose type is specified by the fType member.

Windows 98 and Windows 2000 or later: dwTypeData is used only if the MIIM_STRING flag is set in the fMask member.

cch
Length of the menu item text, in TCHARs, 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.

Windows 98/Me, Windows 2000 or later: The cch member is used when the MIIM_STRING flag is set in the fMask member.

hbmpItem
Windows 98/Me, Windows 2000 or later: Handle to the bitmap to be displayed, or it can be one of the values in the following table. It is used when the MIIM_BITMAP flag is set in the fMask member.
Value | Bitmap to be displayed
HBMMENU_CALLBACK | A bitmap that is drawn by the window that owns the menu. The application must process the WM_MEASUREITEM and WM_DRAWITEM messages.
HBMMENU_MBAR_CLOSE | Close button for the menu bar.
HBMMENU_MBAR_CLOSE_D | Disabled close button for the menu bar.
HBMMENU_MBAR_MINIMIZE | Minimize button for the menu bar.
HBMMENU_MBAR_MINIMIZE_D | Disabled minimize button for the menu bar.
HBMMENU_MBAR_RESTORE | Restore button for the menu bar.
HBMMENU_POPUP_CLOSE | Close button for the submenu.
HBMMENU_POPUP_MAXIMIZE | Maximize button for the submenu.
HBMMENU_POPUP_MINIMIZE | Minimize button for the submenu.
HBMMENU_POPUP_RESTORE | Restore button for the submenu.
HBMMENU_SYSTEM | Windows icon or the icon of the window specified in dwItemData.

Remarks

A menu can display items using text or bitmaps, but not both.

The MENUITEMINFO structure is used with the GetMenuItemInfo, InsertMenuItem, and SetMenuItemInfo functions.

Windows 98 and Windows 2000 or later: The menu can display items using text, bitmaps, or both.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Unicode: Declared 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;
  WORD mtID;
  WCHAR mtString[1];
} MENUITEMTEMPLATE, *PMENUITEMTEMPLATE;

Members

mtOption
Specifies one or more of the following predefined menu options that control the appearance of the menu item as shown in the following table.
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, selected, 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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 {
  WORD versionNumber;
  WORD offset;
} MENUITEMTEMPLATEHEADER, *PMENUITEMTEMPLATEHEADER;

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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, *LPTPMPARAMS;

Members

cbSize
Size of structure, in bytes.
rcExclude
Rectangle to exclude when positioning the window, in screen coordinates.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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_MENUCOMMAND
WM_MENUDRAG
WM_MENUGETOBJECT
WM_MENURBUTTONUP
WM_MENUSELECT
WM_NEXTMENU
WM_SYSCOMMAND
WM_UNINITMENUPOPUP


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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  WM_COMMAND,      // the message to send
  WPARAM wParam,   // notification code and identifier
  LPARAM lParam    // handle to control (HWND)
);

Parameters

wParam
The high-order word specifies the notification code if the message is from a control. If the message is from an accelerator, this value is 1. If the message is from a menu, this value is zero.

The low-order word specifies the identifier of the menu item, control, or accelerator.

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.

Windows 98/Me, Windows 2000 or later: If a menu is defined with a MENUINFO.dwStyle value of MNS_NOTIFYBYPOS, WM_MENUCOMMAND is sent instead of WM_COMMAND.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Menus Overview, Menu Messages, HIWORD, LOWORD, MENUINFO, WM_MENUCOMMAND, WM_SYSCOMMAND


WM_CONTEXTMENU

The WM_CONTEXTMENU message notifies a window that the user clicked the right mouse button (right clicked) in the window.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  WM_CONTEXTMENU,  // the message to send
  WPARAM wParam,   // handle to window (HWND)
  LPARAM lParam    // horizontal and vertical position
);

Parameters

wParam
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.
lParam
The low-order word specifies the horizontal position of the cursor, in screen coordinates, at the time of the mouse click.

The high-order word specifies the 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. To obtain the horizontal and vertical positions, use the following code:

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

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 or when the user types SHIFT+F10. The WM_CONTEXTMENU message is also generated when the user presses and releases the VK_APPS key.

If the context menu is generated from the keyboard—for example, if the user types SHIFT+F10--then the x- and y-coordinates are –1 and the application should display the context menu at the location of the current selection rather than at (xPos, yPos).

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Menus Overview, Menu Messages, DefWindowProc, GET_X_LPARAM, GET_Y_LPARAM, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  WM_ENTERMENULOOP,  // message to send
  WPARAM wParam,   // track popup menu indicator
  LPARAM lParam    // not used
);

Parameters

wParam
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.
lParam
This parameter is not used.

Return Values

An application should return zero if it processes this message.

Remarks

The DefWindowProc function returns zero.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  WM_EXITLOOP,     // message to send
  WPARAM wParam,   // menu status
  LPARAM lParam    // not used
);

Parameters

wParam
Specifies whether the menu is a shortcut menu. This parameter has a value of TRUE if it is a shortcut menu, FALSE if it is not.
lParam
This parameter is not used.

Return Values

An application should return zero if it processes this message.

Remarks

The DefWindowProc function returns zero.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Menus Overview, Menu Messages, DefWindowProc, WM_ENTERMENULOOP


WM_MENUCOMMAND

The WM_MENUCOMMAND message is sent when the user makes a selection from a menu.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  WM_MENUCOMMAND,    // message to send
  WPARAM wParam,   // item index
  LPARAM lParam    // handle to menu (HMENU)
);

Parameters

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

Windows 98/Me: The high word is the zero-based index of the item selected. The low word is the item ID.

lParam
Handle to the menu for the item selected.

Remarks

The WM_MENUCOMMAND message gives you a handle to the menu--so you can access the menu data in the MENUINFO structure—and also gives you the index of the selected item, which is typically what applications need. In contrast, the WM_COMMAND message gives you the menu item identifier.

The WM_MENUCOMMAND message is sent only for menus that are defined with the MNS_NOTIFYBYPOS flag set in the dwStyle member of the MENUINFO structure.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Menus Overview, Menu Messages


WM_MENUDRAG

The WM_MENUDRAG message is sent to the owner of a drag-and-drop menu when the user drags a menu item.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  WM_MENUDRAG,     // message to send
  WPARAM wParam,   // starting position
  LPARAM lParam    // handle to menu (HMENU)
);

Parameters

wParam
Specifies the position of the item where the drag operation began.
lParam
Handle to the menu containing the item.

Return Values

The application should return one of the following values.

Value | Meaning
MND_CONTINUE | Menu should remain active. If the mouse is released, it should be ignored.
MND_ENDMENU | Menu should be ended.

Remarks

The application can call the DoDragDrop function in response to this message.

To create a drag-and-drop menu, call SetMenuInfo with MNS_DRAGDROP.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Menus Overview, Menu Messages, , SetMenuInfo


WM_MENUGETOBJECT

The WM_MENUGETOBJECT message is sent to the owner of a drag-and-drop menu when the mouse cursor enters a menu item or moves from the center of the item to the top or bottom of the item.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  WM_MENUGETOBJECT,   // message to send
  WPARAM wParam,   // not used
  LPARAM lParam    // menu information (PMENUGETOBJECTINFO)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to a MENUGETOBJECTINFO structure.

Return Values

The application should return one of the following values.

Values | Meaning
MNGO_NOERROR | An interface pointer was returned in the pvObj member of MENUGETOBJECTINFO
MNGO_NOINTERFACE | The interface is not supported.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Menus Overview, Menu Messages


WM_MENURBUTTONUP

The WM_MENURBUTTONUP message is sent when the user releases the right mouse button while the cursor is on a menu item.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  WM_MENURBUTTONUP,   // message to send
  WPARAM wParam,   // mouse release position
  LPARAM lParam    // handle to menu (HMENU)
);

Parameters

wParam
Specifies the position of the item when the mouse was released.
lParam
Handle to the menu containing the item.

Remarks

The WM_MENURBUTTONUP message allows applications to provide a context-sensitive menu—also known as a shortcut menu—for the menu item specified in this message. To display a context-sensitive menu for a menu item, call the TrackPopupMenuEx function with TPM_RECURSE.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Menus Overview, Menu Messages


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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  WM_NEXTMENU,     // message to send
  WPARAM wParam,   // virtual-key code
  LPARAM lParam    // menu information (LPMDINEXTMENU)
);

Parameters

wParam
Specifies the virtual-key code of the key.
lParam
Pointer to a 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).

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Menus Overview, Menu Messages, MDINEXTMENU


WM_UNINITMENUPOPUP

The WM_UNINITMENUPOPUP message is sent when a drop-down menu or submenu has been destroyed.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  WM_UNINITMENUPOPUP,   // message to send
  WPARAM wParam,   // handle to menu (HMENU)
  LPARAM lParam    // menu identifier
);

Parameters

wParam
Handle to the menu
lParam
The high-order word identifies the menu that was destroyed. Currently, it can only be MF_SYSMENU (the window menu).

Remarks

If an application receives a WM_INITMENUPOPUP message, it will receive a WM_UNINITMENUPOPUP message.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Menus Overview, Menu Messages, , HIWORD


Strings

This overview describes the string functions and explains how to use them in your applications.

  • About Strings
  • String Reference


About Strings

The string functions give applications the means to copy, compare, sort, format, and convert character strings as well as the means to determine the character type of each character in a string. All the string functions support the single-byte, double-byte, and Unicode character sets if these character sets are supported by the operating system on which the application is run.

• Comparison with C Run-time String Functions

• String Resources


Comparison with C Run-time String Functions

Many string functions duplicate or enhance familiar string functions from the standard C run-time (CRT) library. Many of the enhancements enable the string functions to work with Unicode or extended character sets. For example, the functions in the following table are identical to standard C functions except that they are enhanced for use with Unicode.

String Function | Standard CRT function
lstrcat | strcat
lstrcmp | strcmp
lstrcmpi | strcmpi
lstrcpy | strcpy
lstrlen | strlen

The strlen function, for example, always returns the number of bytes in a string, but the lstrlen function returns the number of TCHARs, which refers to bytes for ANSI versions of the function or WCHARs for Unicode versions.

The following string functions differ from standard C functions such as tolower and toupper in that they operate on any character in a character set. By using the CharLower function, for example, an application can convert an uppercase U with an umlaut (Ü) to lowercase (ü). For more information about character sets, see Single-byte Character Sets.

Function | Description
CharLower | Converts a character or string to lowercase.
CharLowerBuff | Converts a character string to lowercase.
CharNext | Moves to the next character in a string.
CharPrev | Moves to the preceding character in a string.
CharUpper | Converts a character or string to uppercase.
CharUpperBuff | Converts a string to uppercase.

The following string functions make determinations about a character based on the semantics of the language selected by the user. These functions are Unicode enabled.

Function | Description
IsCharAlpha | Determines whether a character is alphabetic.
IsCharAlphaNumeric | Determines whether a character is alphanumeric.
IsCharLower | Determines whether a character is lowercase.
IsCharUpper | Determines whether a character is uppercase.

The wsprintf and wvsprintf functions are extensions to the standard C functions sprintf and vsprintf. These versions support format specifications unique to Unicode.


String Resources

An application that maintains character strings in resources can be translated into new languages with minimum effort. Instead of searching for strings in the source modules, you can simply translate the strings in the resource file and relink the application. In addition, using string resources simplifies creation of Unicode and non-Unicode versions of the application from the same source files.

The LoadString function loads a string resource from an application's executable file. The FormatMessage function loads a string resource and interprets formatting options that may be embedded in the string.

Resources in binary form are stored in Unicode format. When loading resources, applications can use the Unicode version of the resource functions (LoadStringW, for example) to obtain resources as Unicode data.

For 16-bit string resources, 255 characters is the maximum length. For 32-bit string resources, 65535 characters is the maximum length.


String Reference

The following element is used with strings.

  • String Functions


String Functions

The following functions are used with strings.

Function | Description
CharLower | Converts a character string or a single character to lowercase.
CharLowerBuff | Converts uppercase characters in a buffer to lowercase characters.
CharNext | Retrieves a pointer to the next character in a string.
CharNextExA | Retrieves the pointer to the next character in a string.
CharPrev | Retrieves a pointer to the preceding character in a string.
CharPrevExA | Retrieves the pointer to the preceding character in a string.
CharToOem | Translates a string into the OEM-defined character set.
CharToOemBuff | Translates a specified number of characters in a string into the OEM-defined character set.
CharUpper | Converts a character string or a single character to uppercase.
CharUpperBuff | Converts lowercase characters in a buffer to uppercase characters.
CompareString | Compares two character strings, using the specified locale.
FoldString | Maps one string to another, performing a specified transformation option.
GetStringTypeA | Retrieves character-type information for the characters in the specified source string.
GetStringTypeEx | Retrieves character-type information for the characters in the specified source string.
GetStringTypeW | Retrieves character-type information for the characters in the specified source string.
IsCharAlpha | Determines whether a character is an alphabetic character.
IsCharAlphaNumeric | Determines whether a character is either an alphabetic or a numeric character.
IsCharLower | Determines whether a character is lowercase.
IsCharUpper | Determines whether a character is uppercase.
LoadString | Loads a string resource from the executable file associated with a specified module.
lstrcat | Appends one string to another.
lstrcmp | Compares two character strings.
lstrcmpi | Compares two character strings.
lstrcpy | Copies a string to a buffer.
lstrcpyn | Copies a specified number of characters from a source string into a buffer.
lstrlen | Retrieves the length of the specified string (not including the terminating null character).
MultiByteToWideChar | Maps a character string to a wide-character (Unicode) string.
OemToChar | Translates a string from the OEM-defined character set into either an ANSI or a wide-character string.
OemToCharBuff | Translates a specified number of characters in a string from the OEM-defined character set into either an ANSI or a wide-character string.
WideCharToMultiByte | Maps a wide-character string to a new character string.
wsprintf | Formats and stores a series of characters and values in a buffer.
wvsprintf | Formats and stores a series of characters and values in a buffer.


CharLower

The CharLower function converts a character string or a single character to lowercase. If the operand is a character string, the function converts the characters in place.

LPTSTR CharLower(
  LPTSTR lpsz   // single character or string
);

Parameters

lpsz
[in/out] Pointer to a null-terminated string or specifies a single character. If the high-order word of this parameter is zero, the low-order word must contain a single character to be converted.

Return Values

If the operand is a character string, the function returns a pointer to the converted string. Since the string is converted in place, the return value is equal to lpsz.

If the operand is a single character, the return value is a 32-bit value whose high-order word is zero, and low-order word contains the converted character.

There is no indication of success or failure. Failure is rare. There is no extended error information for this function; do not call GetLastError.

Remarks

Windows NT/2000 or later: To make the conversion, the function uses the language driver for the current language selected by the user at setup or by using Control Panel. If no language has been selected, the system completes the conversion by using internal default mapping. The conversion is made based on the code page associated with the process locale.

Windows 95/98/Me: The function makes the conversion based on the information associated with the user's default locale, which is the locale selected by the user at setup or by using Control Panel. The system does not have language drivers.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Strings Overview, String Functions, CharLowerBuff, CharUpper, CharUpperBuff


CharLowerBuff

The CharLowerBuff function converts uppercase characters in a buffer to lowercase characters. The function converts the characters in place.

DWORD CharLowerBuff(
  LPTSTR lpsz,      // characters
  DWORD cchLength   // number of TCHARs to process
);

Parameters

lpsz
[in/out] Pointer to a buffer containing one or more characters to process.
cchLength
[in] Specifies the size, in TCHARs, of the buffer pointed to by lpsz. This refers to bytes for ANSI versions of the function or WCHARs for Unicode versions. The function examines each character, and converts uppercase characters to lowercase characters. The function examines the number of TCHARs indicated by cchLength, even if one or more characters are null characters.

Return Values

The return value is the number of TCHARs processed. For example, if CharLowerBuff("Acme of Operating Systems", 10) succeeds, the return value is 10.

Remarks

Windows NT/2000 or later: To make the conversion, the function uses the language driver for the current language selected by the user at setup or by using Control Panel. If no language has been selected, the system completes the conversion by using internal default mapping. The conversion is made based on the code page associated with the process locale.

Windows 95/98/Me: The function makes the conversion based on the information associated with the user's default locale, which is the locale selected by the user at setup or by using Control Panel. The system does not have language drivers.

For an example, see Creating a Spell Dialog Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Strings Overview, String Functions, CharLower, CharUpper, CharUpperBuff


CharNext

The CharNext function retrieves a pointer to the next character in a string.

LPTSTR CharNext(
  LPCTSTR lpsz   // current character
);

Parameters

lpsz
[in] Pointer to a character in a null-terminated string.

Return Values

The return value is a pointer to the next character in the string, or to the terminating null character if at the end of the string. This refers to bytes for ANSI versions of the function or WCHARs for Unicode versions.

If lpsz points to the terminating null character, the return value is equal to lpsz.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Strings Overview, String Functions, CharNextExA, CharPrev


CharNextExA

The CharNextExA function retrieves the pointer to the next character in a string. This function can handle strings consisting of either single- or multi-byte characters.

LPSTR CharNextExA(
  WORD CodePage,          // code page identifier
  LPCSTR lpCurrentChar,   // current character
  DWORD dwFlags           // reserved; must be zero
);

Parameters

CodePage
[in] Identifier of the code page to use to check lead-byte ranges. Can be one of the code-page values provided in the "Code-Page Identifiers" table in Unicode and Character Set Constants or one of the following predefined values.
Value | Meaning
0 | Use system default ANSI code page.
CP_ACP | Use system default ANSI code page.
CP_OEMCP | Use system default OEM code page.

lpCurrentChar
[in] Pointer to a character in a null-terminated string.
dwFlags
Reserved; must be zero.

Return Values

The return value is a pointer to the next character in the string, or to the terminating null character if at the end of the string.

If lpCurrentChar points to the terminating null character, the return value is equal to lpCurrentChar.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Strings Overview, String Functions, CharNext, CharPrevExA


CharPrev

The CharPrev function retrieves a pointer to the preceding character in a string.

LPTSTR CharPrev(
  LPCTSTR lpszStart,    // first character
  LPCTSTR lpszCurrent   // current character
);

Parameters

lpszStart
[in] Pointer to the beginning of the string.
lpszCurrent
[in] Pointer to a character in a null-terminated string.

Return Values

The return value is a pointer to the preceding character in the string, or to the first character in the string if the lpszCurrent parameter equals the lpszStart parameter. This refers to bytes for ANSI versions of the function or WCHARs for Unicode versions.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Strings Overview, String Functions, CharNext, CharPrevExA


CharPrevExA

The CharPrevExA function retrieves the pointer to the preceding character in a string. This function can handle strings consisting of either single- or multi-byte characters.

LPSTR CharPrevExA(
  WORD CodePage,          // identifier of code page
  LPCSTR lpStart,         // first character
  LPCSTR lpCurrentChar,   // current character
  DWORD dwFlags           // reserved; must be zero
);

Parameters

CodePage
[in] Identifier of the code page to use to check lead-byte ranges. Can be one of the code-page values provided in the "Code-Page Identifiers" table in Unicode and Character Set Constants or one of the following predefined values.
Value | Meaning
0 | Use system default ANSI code page.
CP_ACP | Use system default ANSI code page.
CP_OEMCP | Use system default OEM code page.

lpStart
[in] Pointer to the beginning of the string.
lpCurrentChar
[in] Pointer to a character in a null-terminated string.
dwFlags
Reserved; must be zero.

Return Values

The return value is a pointer to the preceding character in the string, or to the first character in the string if the lpCurrentChar parameter equals the lpStart parameter.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Strings Overview, String Functions, CharNextExA, CharPrev


CharToOem

The CharToOem function translates a string into the OEM-defined character set.

BOOL CharToOem(
  LPCTSTR lpszSrc,  // string to translate
  LPSTR lpszDst     // translated string
);

Parameters

lpszSrc
[in] Pointer to the null-terminated string to translate.
lpszDst
[out] Pointer to the buffer for the translated string. If the CharToOem function is being used as an ANSI function, the string can be translated in place by setting the lpszDst parameter to the same address as the lpszSrc parameter. This cannot be done if CharToOem is being used as a wide-character function.

Return Values

The return value is always nonzero except when you pass the same address to lpszSrc and lpszDst in the wide-character version of the function. In this case the function returns zero and GetLastError returns ERROR_INVALID_ADDRESS.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Strings Overview, String Functions, CharToOemBuff, OemToChar, OemToCharBuff


CharToOemBuff

The CharToOemBuff function translates a specified number of characters in a string into the OEM-defined character set.

BOOL CharToOemBuff(
  LPCTSTR lpszSrc,    // string to translate
  LPSTR lpszDst,      // translated string
  DWORD cchDstLength  // length of string to translate
);

Parameters

lpszSrc
[in] Pointer to the null-terminated string to translate.
lpszDst
[out] Pointer to the buffer for the translated string. If the CharToOemBuff function is being used as an ANSI function, the string can be translated in place by setting the lpszDst parameter to the same address as the lpszSrc parameter. This cannot be done if CharToOemBuff is being used as a wide-character function.
cchDstLength
[in] Specifies the number of TCHARs to translate in the string identified by the lpszSrc parameter. This refers to bytes for ANSI versions of the function or WCHARs for Unicode versions.

Return Values

The return value is always nonzero except when you pass the same address to lpszSrc and lpszDst in the wide-character version of the function. In this case the function returns zero and GetLastError returns ERROR_INVALID_ADDRESS.

Remarks

Unlike the CharToOem function, the CharToOemBuff function does not stop converting characters when it encounters a null character in the buffer pointed to by lpszSrc. The CharToOemBuff function converts all cchDstLength characters.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Strings Overview, String Functions, CharToOem, OemToChar, OemToCharBuff


CharUpper

The CharUpper function converts a character string or a single character to uppercase. If the operand is a character string, the function converts the characters in place.

LPTSTR CharUpper(
  LPTSTR lpsz   // single character or string
);

Parameters

lpsz
[in/out] Pointer to a null-terminated string or specifies a single character. If the high-order word of this parameter is zero, the low-order word must contain a single character to be converted.

Return Values

If the operand is a character string, the function returns a pointer to the converted string. Since the string is converted in place, the return value is equal to lpsz.

If the operand is a single character, the return value is a 32-bit value whose high-order word is zero, and low-order word contains the converted character.

There is no indication of success or failure. Failure is rare. There is no extended error information for this function; do no call GetLastError.

Remarks

Windows NT/2000 or later: To make the conversion, the function uses the language driver for the current language selected by the user at setup or by using Control Panel. If no language has been selected, the system completes the conversion by using internal default mapping. The conversion is made based on the code page associated with the process locale.

Windows 95/98/Me: The function makes the conversion based on the information associated with the user's default locale, which is the locale selected by the user at setup or by using Control Panel. The system does not have language drivers.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Strings Overview, String Functions, CharLower, CharLowerBuff, CharUpperBuff


CharUpperBuff

The CharUpperBuff function converts lowercase characters in a buffer to uppercase characters. The function converts the characters in place.

DWORD CharUpperBuff(
  LPTSTR lpsz,      // characters
  DWORD cchLength   // number of characters to process
);

Parameters

lpsz
[in] Pointer to a buffer containing one or more characters to process.
cchLength
[in] Specifies the size, in TCHARs, of the buffer pointed to by lpsz. This refers to bytes for ANSI versions of the function or WCHARs for Unicode versions.

The function examines each character, and converts lowercase characters to uppercase characters. The function examines the number of characters indicated by cchLength, even if one or more characters are null characters.

Return Values

The return value is the number of TCHARs processed.

For example, if CharUpperBuff("Zenith of API Sets", 10) succeeds, the return value is 10.

Remarks

Windows NT/2000 or later: To make the conversion, the function uses the language driver for the current language selected by the user at setup or by using Control Panel. If no language has been selected, the system completes the conversion by using internal default mapping. The conversion is made based on the code page associated with the process locale.

Windows 95/98/Me: The function makes the conversion based on the information associated with the user's default locale, which is the locale selected by the user at setup or by using Control Panel. The system does not have language drivers.

For an example, see Creating and Using a Temporary File.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Strings Overview, String Functions, CharLower, CharLowerBuff, CharUpper


CompareString

The CompareString function compares two character strings, using the specified locale.

int CompareString(
  LCID Locale,       // locale identifier
  DWORD dwCmpFlags,  // comparison-style options
  LPCTSTR lpString1, // first string
  int cchCount1,     // size of first string
  LPCTSTR lpString2, // second string
  int cchCount2      // size of second string
);

Parameters

Locale
[in] Specifies the locale used for the comparison. This parameter can be one of the following predefined locale identifiers.
Value | Meaning
LOCALE_SYSTEM_DEFAULT | The system's default locale.
LOCALE_USER_DEFAULT | The current user's default locale.

This parameter can also be a locale identifier created by the MAKELCID macro.

dwCmpFlags
[in] A set of flags that indicate how the function compares the two strings. By default, these flags are not set. This parameter can specify zero to get the default behavior, or it can be any combination of the following values.
Value | Meaning
NORM_IGNORECASE | Ignore case.
NORM_IGNOREKANATYPE | Do not differentiate between Hiragana and Katakana characters. Corresponding Hiragana and Katakana characters compare as equal.
NORM_IGNORENONSPACE | Ignore nonspacing characters.
NORM_IGNORESYMBOLS | Ignore symbols.
NORM_IGNOREWIDTH | Do not differentiate between a single-byte character and the same character as a double-byte character.
SORT_STRINGSORT | Treat punctuation the same as symbols.

lpString1
[in] Pointer to the first string to be compared.
cchCount1
[in] Specifies the number of TCHARs in the string pointed to by the lpString1 parameter. This refers to bytes for ANSI versions of the function or WCHARs for Unicode versions. The count does not include the null-terminator. If this parameter is –1, the string is assumed to be null terminated and the length is calculated automatically.
lpString2
[in] Pointer to the second string to be compared.
cchCount2
[in] Specifies the number of TCHARs in the string pointed to by the lpString2 parameter. The count does not include the null-terminator. If this parameter is –1, the string is assumed to be null terminated and the length is calculated automatically.

Return Values

If the function succeeds, the return value is one of the following values.

Value | Meaning
CSTR_LESS_THAN | The string pointed to by the lpString1 parameter is less in lexical value than the string pointed to by the lpString2 parameter.
CSTR_EQUAL | The string pointed to by lpString1 is equal in lexical value to the string pointed to by lpString2.
CSTR_GREATER_THAN | The string pointed to by lpString1 is greater in lexical value than the string pointed to by lpString2.

If the function fails, the return value is zero. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

ERROR_INVALID_FLAGS
ERROR_INVALID_PARAMETER

Remarks

Notice that if the return value is CSTR_EQUAL, the two strings are "equal" in the collation sense, though not necessarily identical.

To maintain the C run-time convention of comparing strings, the value 2 can be subtracted from a nonzero return value. The meaning of < 0, ==0 and > 0 is then consistent with the C run times.

If the two strings are of different lengths, they are compared up to the length of the shortest one. If they are equal to that point, then the return value will indicate that the longer string is greater. For more information about locale identifiers, see Locales.

Typically, strings are compared using what is called a "word sort" technique. In a word sort, all punctuation marks and other nonalphanumeric characters, except for the hyphen and the apostrophe, come before any alphanumeric character. The hyphen and the apostrophe are treated differently than the other nonalphanumeric symbols, in order to ensure that words such as "coop" and "co-op" stay together within a sorted list.

If the SORT_STRINGSORT flag is specified, strings are compared using what is called a "string sort" technique. In a string sort, the hyphen and apostrophe are treated just like any other nonalphanumeric symbols: they come before the alphanumeric symbols.

The following table shows a list of words sorted both ways.

Word Sort | String Sort | Word Sort | String Sort
billet | bill's | t-ant | t-ant
bills | billet | tanya | t-aria
bill's | bills | t-aria | tanya
cannot | can't | sued | sue's
cant | cannot | sues | sued
can't | cant | sue's | sues
con | co-op | went | we're
coop | con | were | went
co-op | coop | we're | were

The lstrcmp and lstrcmpi functions use a word sort. The CompareString and LCMapString functions default to using a word sort, but use a string sort if their caller sets the SORT_STRINGSORT flag.

The CompareString function is optimized to run at the highest speed when dwCmpFlags is set to 0 or NORM_IGNORECASE, and cchCount1 and cchCount2 have the value -1.

The CompareString function ignores Arabic Kashidas during the comparison. Thus, if two strings are identical save for the presence of Kashidas, CompareString returns a value of 2; the strings are considered "equal" in the collation sense, though they are not necessarily identical.

For DBCS locales, the flag NORM_IGNORECASE has an effect on all the wide (two-byte) characters as well as the narrow (one-byte) characters. This includes the wide Greek and Cyrillic characters.

In Chinese Simplified, the sorting order used to compare the strings is based on the following sequence: symbols, digit numbers, English letters, and Chinese Simplified characters. The characters within each group sort in character-code order.

In Chinese Traditional, the sorting order used to compare strings is based on the number of strokes in the charaters. Symbols, digit numbers, and English characters are considered to have zero strokes. The sort sequence is symbols, digit numbers, English letters, and Chinese Traditional characters. The characters within each stroke-number group sort in character-code order.

In Japanese, the sorting order used to compare the strings is based on the Japanese 50-on sorting sequence. The Kanji ideographic characters sort in character-code order.

In Japanese, the flag NORM-IGNORENONSPACE has an effect on the daku-on, handaku-on, chou-on, you-on, and soku-on modifiers, and on the repeat kana/kanji characters.

In Korean, the sort order is based on the sequence: symbols, digit numbers, Jaso and Hangeul, Hanja, and English. Within the Jaso-Hangeul group, each Jaso character is followed by the Hangeuls that start with that Jaso. Hanja characters are sorted in Hangeul pronunciation order. Where multiple Hanja have the same Hangeul pronunciation, they are sorted in character-code order.

The NORM_IGNORENONSPACE flag only has an effect for the locales in which accented characters are sorted in a second pass from main characters. All characters in the string are first compared without regard to accents and (if the strings are equal) a second pass over the strings is performed to compare accents. In this case, this flag causes the second pass to not be performed. For locales that sort accented characters in the first pass, this flag has no effect.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winnls.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Strings Overview, String Functions, FoldString, GetSystemDefaultLCID, GetUserDefaultLCID, LCMapString, lstrcmp, lstrcmpi, MAKELCID


FoldString

The FoldString function maps one string to another, performing a specified transformation option.

int FoldString(
  DWORD dwMapFlags,  // mapping transformation options
  LPCTSTR lpSrcStr,  // source string
  int cchSrc,        // size of source string
  LPTSTR lpDestStr,  // destination buffer
  int cchDest        // size of destination buffer
);

Parameters

dwMapFlags
[in] A set of bit flags that indicate the type of transformation to be used during mapping. This value can be a combination of the following values.
Value | Meaning
MAP_FOLDCZONE | Fold compatibility zone characters into standard Unicode equivalents. For information about compatibility zone characters, see the following Remarks section.
MAP_FOLDDIGITS | Map all digits to Unicode characters 0 through 9.
MAP_PRECOMPOSED | Map accented characters to precomposed characters, in which the accent and base character are combined into a single character value. This value cannot be combined with MAP_COMPOSITE.
MAP_COMPOSITE | Map accented characters to composite characters, in which the accent and base character are represented by two character values. This value cannot be combined with MAP_PRECOMPOSED.
MAP_EXPAND_LIGATURES | Expand all ligature characters so that they are represented by their two-character equivalent. For example, the ligature 'æ' expands to the two characters 'a' and 'e'. This value cannot be combined with MAP_PRECOMPOSED or MAP_COMPOSITE.

lpSrcStr
[in] Pointer to the string to be mapped.
cchSrc
[in] Specifies the size, in TCHARs, of the lpSrcStr buffer. This refers to bytes for ANSI versions of the function or WCHARs for Unicode versions. If cchSrc is –1, lpSrcStr is assumed to be null-terminated, and the length is calculated automatically.
lpDestStr
[out] Pointer to the buffer to store the mapped string.
cchDest
[in] Specifies the size, in TCHARs, of the lpDestStr buffer. If cchDest is zero, the function returns the number of characters required to hold the mapped string, and the buffer pointed to by lpDestStr is not used.

Return Values

If the function succeeds, the return value is the number of TCHARs written to the destination buffer, or if the cchDest parameter is zero, the number of characters required to hold the mapped string. This refers to bytes for ANSI versions of the function or WCHARs for Unicode versions.

If the function fails, the return value is zero. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

ERROR_INSUFFICIENT_BUFFER
ERROR_INVALID_FLAGS
ERROR_INVALID_PARAMETER

Remarks

The mapped string is null-terminated if the source string is null-terminated.

The lpSrcStr and lpDestStr pointers must not be the same. If they are the same, the function fails and GetLastError returns ERROR_INVALID_PARAMETER.

The compatibility zone in Unicode consists of characters in the range 0xF900 through 0xFFEF that are assigned to characters from other character-encoding standards but are actually variants of characters that are already in Unicode. The compatibility zone is used to support round-trip mapping to these standards. Applications can use the MAP_FOLDCZONE flag to avoid supporting the duplication of characters in the compatibility zone.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winnls.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Strings Overview, String Functions, LCMapString, CompareString


GetStringTypeA

The GetStringTypeA function retrieves character-type information for the characters in the specified source string. For each character in the string, the function sets one or more bits in the corresponding 16-bit element of the output array. Each bit identifies a given character type, such as whether the character is a letter, a digit, or neither.

BOOL GetStringTypeA(
  LCID Locale,       // locale identifer
  DWORD dwInfoType,  // information-type options
  LPCSTR lpSrcStr,   // source string
  int cchSrc,        // size of source string
  LPWORD lpCharType  // output buffer
);

Parameters

Locale
[in] Specifies the locale identifier. This value uniquely defines the ANSI code page to use to translate the string pointed to by lpSrcStr from ANSI to Unicode. The function then analyzes each Unicode character for character type information.

This parameter can be a locale identifier created by the MAKELCID macro, or one of the following predefined values.
Value | Meaning
LOCALE_SYSTEM_DEFAULT | Default system locale
LOCALE_USER_DEFAULT | Default user locale

Note that the Locale parameter does not exist in the GetStringTypeW function. Because of that parameter difference, an application cannot automatically invoke the proper A or W version of GetStringType* through the use of the #define UNICODE switch. An application can circumvent this limitation by using GetStringTypeEx, which is the recommended function.

dwInfoType
[in] Specifies the type of character information the user wants to retrieve. The various types are divided into different levels (see the following Remarks section for a list of the information included in each type). This parameter can specify one of the following character type flags.
Flag | Meaning
CT_CTYPE1 | Retrieve character type information.
CT_CTYPE2 | Retrieve bidirectional layout information.
CT_CTYPE3 | Retrieve text processing information.

lpSrcStr
[in] Pointer to the string for which character types are requested. If cchSrc is –1, the string is assumed to be null terminated. This must be an ANSI string. Note that this can be a double-byte character set (DBCS) string if the locale is appropriate for DBCS.
cchSrc
[in] Specifies the size, in characters, of the string pointed to by the lpSrcStr parameter. If this count includes a null terminator, the function returns character type information for the null terminator. If this value is –1, the string is assumed to be null terminated and the length is calculated automatically.
lpCharType
[out] Pointer to an array of 16-bit values. The length of this array must be large enough to receive one 16-bit value for each character in the source string. When the function returns, this array contains one word corresponding to each character in the source 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. GetLastError may return one of the following error codes:

ERROR_INVALID_FLAGS
ERROR_INVALID_PARAMETER

Remarks

The lpSrcStr and lpCharType pointers must not be the same. If they are the same, the function fails and GetLastError returns ERROR_INVALID_PARAMETER.

The Locale parameter is only used to perform string conversion to Unicode. It has nothing to do with the CTYPEs the function returns. The CTYPEs are solely determined by Unicode code points, and do not vary on a locale basis. For example, Greek letters are C1_ALPHA for any Locale value.

The character-type bits are divided into several levels. The information for one level can be retrieved by a single call to this function. Each level is limited to 16 bits of information so that the other mapping routines, which are limited to 16 bits of representation per character, can also return character-type information.

The character types supported by this function include the following.

Ctype 1
These types support ANSI C and POSIX (LC_CTYPE) character-typing functions. A bitwise-OR of these values is returned in the array pointed to by the lpCharType parameter when the dwInfoType parameter is set to CT_CTYPE1. For DBCS locales, the Ctype 1 attributes apply to both narrow characters and wide characters. The Japanese hiragana and katakana characters, and the kanji ideograph characters all have the C1_ALPHA attribute.
Name | Value | Meaning
C1_UPPER | 0x0001 | Uppercase
C1_LOWER | 0x0002 | Lowercase
C1_DIGIT | 0x0004 | Decimal digits
C1_SPACE | 0x0008 | Space characters
C1_PUNCT | 0x0010 | Punctuation
C1_CNTRL | 0x0020 | Control characters
C1_BLANK | 0x0040 | Blank characters
C1_XDIGIT | 0x0080 | Hexadecimal digits
C1_ALPHA | 0x0100 | Any linguistic character: alphabetic, syllabary, or ideographic

The following character types are either constant or computable from basic types and do not need to be supported by this function.
Type | Description
Alphanumeric | Alphabetic characters and digits (C1_ALPHA and C1_DIGIT).
Printable | Graphic characters and blanks (all C1_* types except C1_CNTRL).

The Windows version 3.1 functions IsCharUpper and IsCharLower do not always produce correct results for characters in the range 0x80-0x9f, so they may produce different results than this function for characters in that range. (For example, the German Windows version 3.1 language driver incorrectly reports 0x9a, lowercase s hacek, as uppercase).

Ctype 2
These types support proper layout of Unicode text. For DBCS locales, Ctype 2 applies to both narrow and wide characters. The direction attributes are assigned so that the bidirectional layout algorithm standardized by Unicode produces accurate results. These types are mutually exclusive. For more information about the use of these attributes, see The Unicode Standard: Worldwide Character Encoding, Volumes 1 and 2, Addison Wesley Publishing Company: 1991, 1992, ISBN 0201567881.
Name | Value | Meaning
Strong
C2_LEFTTORIGHT | 0x0001 | Left to right
C2_RIGHTTOLEFT | 0x0002 | Right to left
Weak
C2_EUROPENUMBER | 0x0003 | European number, European digit
C2_EUROPESEPARATOR | 0x0004 | European numeric separator
C2_EUROPETERMINATOR | 0x0005 | European numeric terminator
C2_ARABICNUMBER | 0x0006 | Arabic number
C2_COMMONSEPARATOR | 0x0007 | Common numeric separator
Neutral
C2_BLOCKSEPARATOR | 0x0008 | Block separator
C2_SEGMENTSEPARATOR | 0x0009 | Segment separator
C2_WHITESPACE | 0x000A | White space
C2_OTHERNEUTRAL | 0x000B | Other neutrals
Not applicable
C2_NOTAPPLICABLE | 0x0000 | No implicit directionality (for example, control codes)

Ctype 3
These types are intended to be placeholders for extensions to the POSIX types required for general text processing or for the standard C library functions. A bitwise-OR of these values is returned when dwInfoType is set to CT_CTYPE3. For DBCS locales, the Cypte 3 attributes apply to both narrow characters and wide characters. The Japanese hiragana and katakana characters, and the kanji ideograph characters all have the C3_ALPHA attribute.
Name | Value | Meaning
C3_NONSPACING | 0x0001 | Nonspacing mark.
C3_DIACRITIC | 0x0002 | Diacritic nonspacing mark.
C3_VOWELMARK | 0x0004 | Vowel nonspacing mark.
C3_SYMBOL | 0x0008 | Symbol.
C3_KATAKANA | 0x0010 | Katakana character.
C3_HIRAGANA | 0x0020 | Hiragana character.
C3_HALFWIDTH | 0x0040 | Half-width (narrow) character.
C3_FULLWIDTH | 0x0080 | Full-width (wide) character.
C3_IDEOGRAPH | 0x0100 | Ideographic character.
C3_KASHIDA | 0x0200 | Arabic Kashida character.
C3_LEXICAL | 0x0400 | Punctuation which is counted as part of the word (Kashida, hyphen, feminine/masculine ordinal indicators, equal sign, and so forth).
C3_ALPHA | 0x8000 | All linguistic characters (alphabetic, syllabary, and ideographic).
Not applicable
C3_NOTAPPLICABLE | 0x0000 | Not applicable.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winnls.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Strings Overview, String Functions, GetLocaleInfo, GetStringTypeEx, GetStringTypeW


GetStringTypeEx

The GetStringTypeEx function retrieves character-type information for the characters in the specified source string. For each character in the string, the function sets one or more bits in the corresponding 16-bit element of the output array. Each bit identifies a given character type, such as whether the character is a letter, a digit, or neither.

Unlike its close relatives GetStringTypeA and GetStringTypeW, GetStringTypeEx exhibits appropriate A or W behavior through the use of the #define UNICODE switch. It is the recommended function.

BOOL GetStringTypeEx(
  LCID Locale,       // locale identifer
  DWORD dwInfoType,  // information-type options
  LPCTSTR lpSrcStr,  // source string
  int cchSrc,        // size of source string
  LPWORD lpCharType  // output buffer
);

Parameters

Locale
[in] Specifies the locale identifier. This value uniquely defines the ANSI code page to use to translate the string pointed to by lpSrcStr from ANSI to Unicode. The function then analyzes each Unicode character for character type information. Note that the W version of this function ignores this parameter.

This parameter can be a locale identifier created by the MAKELCID macro, or one of the following predefined values.
Value | Meaning
LOCALE_SYSTEM_DEFAULT | Default system locale
LOCALE_USER_DEFAULT | Default user locale

dwInfoType
[in] Specifies the type of character information the user wants to retrieve. The various types are divided into different levels (see the following Remarks section for a list of the information included in each type). This parameter can specify one of the following character type values.
Value | Meaning
CT_CTYPE1 | Retrieve character type information.
CT_CTYPE2 | Retrieve bidirectional layout information.
CT_CTYPE3 | Retrieve text processing information.

lpSrcStr
[in] Pointer to the string for which character types are requested. If cchSrc is –1, the string is assumed to be null terminated.
cchSrc
[in] Specifies the size, in TCHARs, of the string pointed to by the lpSrcStr parameter. This refers to bytes for ANSI versions of the function or WCHARs for Unicode versions. If this count includes a null terminator, the function returns character type information for the null terminator. If this value is –1, the string is assumed to be null terminated and the length is calculated automatically.
lpCharType
[out] Pointer to an array of 16-bit values. The length of this array must be large enough to receive one 16-bit value for each character in the source string. When the function returns, this array contains one word corresponding to each character in the source 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. GetLastError may return one of the following error codes:

ERROR_INVALID_FLAGS
ERROR_INVALID_PARAMETER

Remarks

The GetStringTypeEx function exists to circumvent a limitation caused by the difference in parameters of GetStringTypeA and GetStringTypeW. That parameter difference prevents an application from automatically invoking the proper A or W version of GetStringType* through the use of the #define UNICODE switch. GetStringTypeEx, on the other hand, behaves properly as regards that switch. Thus, it is the recommended function.

The Locale parameter is only used to perform string conversion to Unicode. It has nothing to do with the CTYPEs the function returns. The CTYPEs are solely determined by Unicode code points, and do not vary on a locale basis. For example, Greek letters are C1_ALPHA for any Locale value.

The lpSrcStr and lpCharType pointers must not be the same. If they are the same, the function fails and GetLastError returns ERROR_INVALID_PARAMETER.

The character-type bits are divided into several levels. The information for one level can be retrieved by a single call to this function. Each level is limited to 16 bits of information so that the other mapping routines, which are limited to 16 bits of representation per character, can also return character-type information.

The character types supported by this function include the following.

Ctype 1
These types support ANSI C and POSIX (LC_CTYPE) character-typing functions. A combination of these values is returned in the array pointed to by the lpCharType parameter when the dwInfoType parameter is set to CT_CTYPE1.
Name | Value | Meaning
C1_UPPER | 0x0001 | Uppercase
C1_LOWER | 0x0002 | Lowercase
C1_DIGIT | 0x0004 | Decimal digits
C1_SPACE | 0x0008 | Space characters
C1_PUNCT | 0x0010 | Punctuation
C1_CNTRL | 0x0020 | Control characters
C1_BLANK | 0x0040 | Blank characters
C1_XDIGIT | 0x0080 | Hexadecimal digits
C1_ALPHA | 0x0100 | Any linguistic character: alphabetic, syllabary, or ideographic

The following character types are either constant or computable from basic types and do not need to be supported by this function.

Type | Description
Alphanumeric | Alphabetic characters and digits (C1_ALPHA and C1_DIGIT).
Printable | Graphic characters and blank (all C1_* types except C1_CNTRL).

Ctype 2
These types support proper layout of Unicode text. The direction attributes are assigned so that the bidirectional layout algorithm standardized by Unicode produces accurate results. These types are mutually exclusive. For more information about the use of these attributes, see The Unicode Standard: Worldwide Character Encoding, Volumes 1 and 2, Addison Wesley Publishing Company: 1991, 1992, ISBN 0201567881.
Name | Value | Meaning
Strong
C2_LEFTTORIGHT | 0x0001 | Left to right
C2_RIGHTTOLEFT | 0x0002 | Right to left
Weak
C2_EUROPENUMBER | 0x0003 | European number, European digit
C2_EUROPESEPARATOR | 0x0004 | European numeric separator
C2_EUROPETERMINATOR | 0x0005 | European numeric terminator
C2_ARABICNUMBER | 0x0006 | Arabic number
C2_COMMONSEPARATOR | 0x0007 | Common numeric separator
Neutral
C2_BLOCKSEPARATOR | 0x0008 | Block separator
C2_SEGMENTSEPARATOR | 0x0009 | Segment separator
C2_WHITESPACE | 0x000A | White space
C2_OTHERNEUTRAL | 0x000B | Other neutrals
Not applicable
C2_NOTAPPLICABLE | 0x0000 | No implicit directionality (for example, control codes)

Ctype 3
These types are intended to be placeholders for extensions to the POSIX types required for general text processing or for the standard C library functions. A combination of these values is returned when dwInfoType is set to CT_CTYPE3.
Name | Value | Meaning
C3_NONSPACING | 0x0001 | Nonspacing mark
C3_DIACRITIC | 0x0002 | Diacritic nonspacing mark
C3_VOWELMARK | 0x0004 | Vowel nonspacing mark
C3_SYMBOL | 0x0008 | Symbol
C3_KATAKANA | 0x0010 | Katakana character
C3_HIRAGANA | 0x0020 | Hiragana character
C3_HALFWIDTH | 0x0040 | Half-width character
C3_FULLWIDTH | 0x0080 | Full-width character
C3_IDEOGRAPH | 0x0100 | Ideographic character
C3_KASHIDA | 0x0200 | Arabic Kashida character
C3_LEXICAL | 0x0400 | Punctuation which is counted as part of the word (Kashida, hyphen, feminine/masculine ordinal indicators, equal sign, and so forth)
C3_ALPHA | 0x8000 | All linguistic characters (alphabetic, syllabary, and ideographic)
Not applicable
C3_NOTAPPLICABLE | 0x0000 | Not applicable

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winnls.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Strings Overview, String Functions, GetLocaleInfo, GetStringTypeA, GetStringTypeW


GetStringTypeW

The GetStringTypeW function retrieves character-type information for the characters in the specified source string. For each character in the string, the function sets one or more bits in the corresponding 16-bit element of the output array. Each bit identifies a given character type, such as whether the character is a letter, a digit, or neither.

BOOL GetStringTypeW(
  DWORD dwInfoType,  // information-type options
  LPCWSTR lpSrcStr,  // source string
  int cchSrc,        // number of characters in string
  LPWORD lpCharType  // output buffer
);

Parameters

dwInfoType
[in] Specifies the type of character information the user wants to retrieve. The various types are divided into different levels (see the following Remarks section for a list of the information included in each type). This parameter can specify one of the following character type values.
Value | Meaning
CT_CTYPE1 | Retrieve character type information.
CT_CTYPE2 | Retrieve bidirectional layout information.
CT_CTYPE3 | Retrieve text processing information.

lpSrcStr
[in] Pointer to the string for which character types are requested. If cchSrc is –1, the string is assumed to be null terminated. This must be a Unicode string.
cchSrc
[in] Specifies the size, in wide characters, of the string pointed to by the lpSrcStr parameter. If this count includes a null terminator, the function returns character type information for the null terminator. If this value is –1, the string is assumed to be null terminated and the length is calculated automatically.
lpCharType
[out] Pointer to an array of 16-bit values. The length of this array must be large enough to receive one 16-bit value for the number of wide characters specified in the cchSrc parameter. When the function returns, this array contains one word corresponding to each Unicode wide character in the source 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. GetLastError may return one of the following error codes:

ERROR_INVALID_FLAGS
ERROR_INVALID_PARAMETER

Remarks

Note that the GetStringTypeA function has one more parameter than the GetStringTypeW function: GetStringTypeA has a first parameter that is an LCID named Locale. This parameter does not exist in the GetStringTypeW function. Because of that parameter difference, an application cannot automatically invoke the proper A or W version of GetStringType* through the use of the #define UNICODE switch. An application can circumvent this limitation by using GetStringTypeEx; it is the recommended function.

The lpSrcStr and lpCharType pointers must not be the same. If they are the same, the function fails and GetLastError returns ERROR_INVALID_PARAMETER.

The character-type bits are divided into several levels. The information for one level can be retrieved by a single call to this function. Each level is limited to 16 bits of information so that the other mapping routines, which are limited to 16 bits of representation per character, can also return character-type information.

The character types supported by this function include the following.

Ctype 1
These types support ANSI C and POSIX (LC_CTYPE) character-typing functions. A combination of these values is returned in the array pointed to by the lpCharType parameter when the dwInfoType parameter is set to CT_CTYPE1.
Name | Value | Meaning
C1_UPPER | 0x0001 | Uppercase
C1_LOWER | 0x0002 | Lowercase
C1_DIGIT | 0x0004 | Decimal digits
C1_SPACE | 0x0008 | Space characters
C1_PUNCT | 0x0010 | Punctuation
C1_CNTRL | 0x0020 | Control characters
C1_BLANK | 0x0040 | Blank characters
C1_XDIGIT | 0x0080 | Hexadecimal digits
C1_ALPHA | 0x0100 | Any linguistic character: alphabetic, syllabary, or ideographic

The following character types are either constant or computable from basic types and do not need to be supported by this function.

Type | Description
Alphanumeric | Alphabetic characters and digits (C1_ALPHA and C1_DIGIT)
Printable | Graphic characters and blanks (all C1_* types except C1_CNTRL)

Ctype 2
These types support proper layout of Unicode text. The direction attributes are assigned so that the bidirectional layout algorithm standardized by Unicode produces accurate results. These types are mutually exclusive. For more information about the use of these attributes, see The Unicode Standard: Worldwide Character Encoding, Volumes 1 and 2, Addison Wesley Publishing Company: 1991, 1992, ISBN 0201567881.
Name | Value | Meaning
Strong
C2_LEFTTORIGHT | 0x0001 | Left to right
C2_RIGHTTOLEFT | 0x0002 | Right to left
Weak
C2_EUROPENUMBER | 0x0003 | European number, European digit
C2_EUROPESEPARATOR | 0x0004 | European numeric separator
C2_EUROPETERMINATOR | 0x0005 | European numeric terminator
C2_ARABICNUMBER | 0x0006 | Arabic number
C2_COMMONSEPARATOR | 0x0007 | Common numeric separator
Neutral
C2_BLOCKSEPARATOR | 0x0008 | Block separator
C2_SEGMENTSEPARATOR | 0x0009 | Segment separator
C2_WHITESPACE | 0x000A | White space
C2_OTHERNEUTRAL | 0x000B | Other neutrals
Not applicable
C2_NOTAPPLICABLE | 0x0000 | No implicit directionality (for example, control codes)

Ctype 3
These types are intended to be placeholders for extensions to the POSIX types required for general text processing or for the standard C library functions. A combination of these values is returned when dwInfoType is set to CT_CTYPE3.
Name | Value | Meaning
C3_NONSPACING | 0x0001 | Nonspacing mark
C3_DIACRITIC | 0x0002 | Diacritic nonspacing mark
C3_VOWELMARK | 0x0004 | Vowel nonspacing mark
C3_SYMBOL | 0x0008 | Symbol
C3_KATAKANA | 0x0010 | Katakana character
C3_HIRAGANA | 0x0020 | Hiragana character
C3_HALFWIDTH | 0x0040 | Half-width character
C3_FULLWIDTH | 0x0080 | Full-width character
C3_IDEOGRAPH | 0x0100 | Ideographic character
C3_KASHIDA | 0x0200 | Arabic Kashida character
C3_LEXICAL | 0x0400 | Punctuation which is counted as part of the word (Kashida, hyphen, feminine/masculine ordinal indicators, equal sign, and so forth)
C3_ALPHA | 0x8000 | All linguistic characters (alphabetic, syllabary, and ideographic)
Not applicable
C3_NOTAPPLICABLE | 0x0000 | Not applicable

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winnls.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Strings Overview, String Functions, GetLocaleInfo, GetStringTypeA, GetStringTypeEx


IsCharAlpha

The IsCharAlpha function determines whether a character is an alphabetic character. This determination is based on the semantics of the language selected by the user during setup or through Control Panel.

BOOL IsCharAlpha(
  TCHAR ch   // character to test
);

Parameters

ch
[in] Specifies the character to be tested.

Return Values

If the character is alphabetic, the return value is nonzero.

If the character is not alphabetic, the return value is zero. To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Strings Overview, String Functions, IsCharAlphaNumeric


IsCharAlphaNumeric

The IsCharAlphaNumeric function determines whether a character is either an alphabetic or a numeric character. This determination is based on the semantics of the language selected by the user during setup or through Control Panel.

BOOL IsCharAlphaNumeric(
  TCHAR ch   // character to test
);

Parameters

ch
[in] Specifies the character to be tested.

Return Values

If the character is alphanumeric, the return value is nonzero.

If the character is not alphanumeric, the return value is zero. To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Strings Overview, String Functions, IsCharAlpha


IsCharLower

The IsCharLower function determines whether a character is lowercase. This determination is based on the semantics of the language selected by the user during setup or through Control Panel.

BOOL IsCharLower(
  TCHAR ch   // character to test
);

Parameters

ch
[in] Specifies the character to be tested.

Return Values

If the character is lowercase, the return value is nonzero.

If the character is not lowercase, the return value is zero. To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Strings Overview, String Functions, IsCharUpper


IsCharUpper

The IsCharUpper function determines whether a character is uppercase. This determination is based on the semantics of the language selected by the user during setup or through Control Panel.

BOOL IsCharUpper(
  TCHAR ch   // character to test
);

Parameters

ch
[in] Specifies the character to be tested.

Return Values

If the character is uppercase, the return value is nonzero.

If the character is not uppercase, the return value is zero. To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Strings Overview, String Functions, IsCharLower


LoadString

The LoadString function loads a string resource from the executable file associated with a specified module, copies the string into a buffer, and appends a terminating null character.

int LoadString(
  HINSTANCE hInstance,  // handle to resource module
  UINT uID,             // resource identifier
  LPTSTR lpBuffer,      // resource buffer
  int nBufferMax        // size of buffer
);

Parameters

hInstance
[in] Handle to an instance of the module whose executable file contains the string resource.
uID
[in] Specifies the integer identifier of the string to be loaded.
lpBuffer
[out] Pointer to the buffer to receive the string.
nBufferMax
[in] Specifies the size of the buffer, in TCHARs. This refers to bytes for ANSI versions of the function or WCHARs for Unicode versions. The string is truncated and null terminated if it is longer than the number of characters specified.

Return Values

If the function succeeds, the return value is the number of TCHARs copied into the buffer, not including the null-terminating character, or zero if the string resource does not exist. To get extended error information, call GetLastError.

For an example, see Creating a Child Window.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Strings Overview, String Functions, FormatMessage, LoadAccelerators, LoadBitmap, LoadCursor, LoadIcon, LoadMenu, LoadMenuIndirect


lstrcat

The lstrcat function appends one string to another.

LPTSTR lstrcat(
  LPTSTR lpString1,  // first string
  LPCTSTR lpString2  // second string
);

Parameters

lpString1
[in/out] Pointer to a null-terminated string. The buffer must be large enough to contain both strings.
lpString2
[in] Pointer to the null-terminated string to be appended to the string specified in the lpString1 parameter.

Return Values

If the function succeeds, the return value is a pointer to the buffer.

If the function fails, the return value is NULL.

For an example, see Reading from a Mailslot.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000 and Windows 98.

See Also

Strings Overview, String Functions, lstrcmp, lstrcmpi, lstrcpy, lstrlen


lstrcmp

The lstrcmp function compares two character strings. The comparison is case sensitive.

To perform a comparison that is not case sensitive, use the lstrcmpi function.

int lstrcmp(
  LPCTSTR lpString1,  // first string
  LPCTSTR lpString2   // second string
);

Parameters

lpString1
[in] Pointer to the first null-terminated string to be compared.
lpString2
[in] Pointer to the second null-terminated string to be compared.

Return Values

If the string pointed to by lpString1 is less than the string pointed to by lpString2, the return value is negative. If the string pointed to by lpString1 is greater than the string pointed to by lpString2, the return value is positive. If the strings are equal, the return value is zero.

Remarks

The lstrcmp function compares two strings by checking the first characters against each other, the second characters against each other, and so on until it finds an inequality or reaches the ends of the strings.

The function returns the difference of the values of the first unequal characters it encounters. For example, lstrcmp determines that "abcz" is greater than "abcdefg" and returns the difference of z and d.

The language (locale) selected by the user at setup time, or through Control Panel, determines which string is greater (or whether the strings are the same). If no language (locale) is selected, the system performs the comparison by using default values.

With a double-byte character set (DBCS) version of the system, this function can compare two DBCS strings.

The lstrcmp function uses a word sort, rather than a string sort. A word sort treats hyphens and apostrophes differently than it treats other symbols that are not alphanumeric, in order to ensure that words such as "coop" and "co-op" stay together within a sorted list. Note that in 16-bit versions of Windows, lstrcmp uses a string sort. For a detailed discussion of word sorts and string sorts, see the Remarks section of the reference page for the CompareString function .

For an example, see Determining the Location of a Share.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Strings Overview, String Functions, CompareString, lstrcat, lstrcmpi, lstrcpy, lstrlen


lstrcmpi

The lstrcmpi function compares two character strings. The comparison is not case sensitive.

To perform a comparison that is case sensitive, use the lstrcmp function.

int lstrcmpi(
  LPCTSTR lpString1,  // first string
  LPCTSTR lpString2   // second string
);

Parameters

lpString1
[in] Pointer to the first null-terminated string to be compared.
lpString2
[in] Pointer to the second null-terminated string to be compared.

Return Values

If the string pointed to by lpString1 is less than the string pointed to by lpString2, the return value is negative. If the string pointed to by lpString1 is greater than the string pointed to by lpString2, the return value is positive. If the strings are equal, the return value is zero.

Remarks

The lstrcmpi function compares two strings by checking the first characters against each other, the second characters against each other, and so on until it finds an inequality or reaches the ends of the strings.

The function returns the difference of the values of the first unequal characters it encounters. For example, lstrcmpi determines that "abcz" is greater than "abcdefg" and returns the difference of z and d.

The language (locale) selected by the user at setup time, or through Control Panel, determines which string is greater (or whether the strings are the same). If no language (locale) is selected, the system performs the comparison by using default values.

For some locales, the lstrcmpi function may be insufficient. If this occurs, use CompareString to ensure proper comparison. For example, in Japan call CompareString with the IGNORE_CASE, IGNORE_KANATYPE, and IGNORE_WIDTH values to achieve the most appropriate non-exact string comparison. The IGNORE_KANATYPE and IGNORE_WIDTH values are ignored in non-Asian locales, so you can set these values for all locales and be guaranteed to have a culturally correct "insensitive" sorting regardless of the locale. Note that specifying these values slows performance, so use them only when necessary.

With a double-byte character set (DBCS) version of the system, this function can compare two DBCS strings.

The lstrcmpi function uses a word sort, rather than a string sort. A word sort treats hyphens and apostrophes differently than it treats other symbols that are not alphanumeric, in order to ensure that words such as "coop" and "co-op" stay together within a sorted list. Note that in 16-bit versions of Windows, lstrcmpi uses a string sort. For a detailed discussion of word sorts and string sorts, see the Remarks section of the reference page for the CompareString function .

For an example, see Getting the System Version.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Strings Overview, String Functions, CompareString, lstrcat, lstrcmp, lstrcpy, lstrlen


lstrcpy

The lstrcpy function copies a string to a buffer.

To copy a specified number of characters, use the lstrcpyn function.

LPTSTR lstrcpy(
  LPTSTR lpString1,  // destination buffer
  LPCTSTR lpString2  // string
);

Parameters

lpString1
[out] Pointer to a buffer to receive the contents of the string pointed to by the lpString2 parameter. The buffer must be large enough to contain the string, including the terminating null character.
lpString2
[in] Pointer to the null-terminated string to be copied.

Return Values

If the function succeeds, the return value is a pointer to the buffer.

If the function fails, the return value is NULL.

Remarks

With a double-byte character set (DBCS) version of the system, this function can be used to copy a DBCS string.

The lstrcpy function has an undefined behavior if source and destination buffers overlap.

For an example, see Changing Environment Variables.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000 and Windows 98.

See Also

Strings Overview, String Functions, lstrcat, lstrcmp, lstrcmpi, lstrlen


lstrcpyn

The lstrcpyn function copies a specified number of characters from a source string into a buffer.

LPTSTR lstrcpyn(
  LPTSTR lpString1,  // destination buffer
  LPCTSTR lpString2, // string
  int iMaxLength     // number of characters to copy
);

Parameters

lpString1
[out] Pointer to a buffer into which the function copies characters. The buffer must be large enough to contain the number of TCHARs specified by iMaxLength, including room for a terminating null character.
lpString2
[in] Pointer to a null-terminated string from which the function copies characters.
iMaxLength
[in] Specifies the number of TCHARs to be copied from the string pointed to by lpString2 into the buffer pointed to by lpString1, including a terminating null character. This refers to bytes for ANSI versions of the function or WCHARs for Unicode versions.

Return Values

If the function succeeds, the return value is a pointer to the buffer.

If the function fails, the return value is NULL.

Remarks

Note that the buffer pointed to by lpString1 must be large enough to include a terminating null character, and the string length value specified by iMaxLength includes room for a terminating null character. Thus, the following code

TCHAR chBuffer[512] ;
lstrcpyn(chBuffer, "abcdefghijklmnop", 4) ;

copies the string "abc", followed by a terminating null character, to chBuffer.

The lstrcpyn function has an undefined behavior if source and destination buffers overlap.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Strings Overview, String Functions, lstrcat, lstrcmp, lstrcmpi, lstrcpy, lstrlen


lstrlen

The lstrlen function returns the length in bytes (ANSI version) or WCHARs (Unicode version) of the specified string (not including the terminating null character).

int lstrlen(
  LPCTSTR lpString   // string to count
);

Parameters

lpString
[in] Pointer to a null-terminated string.

Return Values

The return value specifies the length of the string, in TCHARs. This refers to bytes for ANSI versions of the function or WCHARs for Unicode versions.

For an example, see Displaying Keyboard Input.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on all platforms.

See Also

Strings Overview, String Functions, lstrcat, lstrcmp, lstrcmpi, lstrcpy


OemToChar

The OemToChar function translates a string from the OEM-defined character set into either an ANSI or a wide-character string.

BOOL OemToChar(
  LPCSTR lpszSrc,  // string to translate
  LPTSTR lpszDst   // translated string
);

Parameters

lpszSrc
[in] Pointer to a null-terminated string of characters from the OEM-defined character set.
lpszDst
[out] Pointer to the buffer for the translated string. If the OemToChar function is being used as an ANSI function, the string can be translated in place by setting the lpszDst parameter to the same address as the lpszSrc parameter. This cannot be done if OemToChar is being used as a wide-character function.

Return Values

The return value is always nonzero except when you pass the same address to lpszSrc and lpszDst in the wide-character version of the function. In this case the function returns zero and GetLastError returns ERROR_INVALID_ADDRESS.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Strings Overview, String Functions, CharToOem, CharToOemBuff, OemToCharBuff


OemToCharBuff

The OemToCharBuff function translates a specified number of characters in a string from the OEM-defined character set into either an ANSI or a wide-character string.

BOOL OemToCharBuff(
  LPCTSTR lpszSrc,      // string to translate
  LPTSTR lpszDst,       // translated string buffer
  DWORD cchDstLength    // TCHARs to translate
);

Parameters

lpszSrc
[in] Pointer to a buffer containing one or more characters from the OEM-defined character set.
lpszDst
[out] Pointer to the buffer for the translated string. If the OemToCharBuff function is being used as an ANSI function, the string can be translated in place by setting the lpszDst parameter to the same address as the lpszSrc parameter. This cannot be done if the OemToCharBuff function is being used as a wide-character function.
cchDstLength
[in] Specifies the number of TCHARs to translate in the buffer identified by the lpszSrc parameter. This refers to bytes for ANSI versions of the function or WCHARs for Unicode versions.

Return Values

The return value is always nonzero except when you pass the same address to lpszSrc and lpszDst in the wide-character version of the function. In this case the function returns zero and GetLastError returns ERROR_INVALID_ADDRESS.

Remarks

Unlike the OemToChar function, the OemToCharBuff function does not stop converting characters when it encounters a null character in the buffer pointed to by lpszSrc. The OemToCharBuff function converts all cchDstLength characters.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Strings Overview, String Functions, CharToOem, CharToOemBuff, OemToChar


wsprintf

The wsprintf function formats and stores a series of characters and values in a buffer. Any arguments are converted and copied to the output buffer according to the corresponding format specification in the format string. The function appends a terminating null character to the characters it writes, but the return value does not include the terminating null character in its character count.

int wsprintf(
  LPTSTR lpOut,    // output buffer
  LPCTSTR lpFmt,   // format-control string
  ...              // optional arguments
);

Parameters

lpOut
[out] Pointer to a buffer to receive the formatted output. The maximum size of the buffer is 1024 bytes.
lpFmt
[in] Pointer to a null-terminated string that contains the format-control specifications. In addition to ordinary ASCII characters, a format specification for each argument appears in this string. For more information about the format specification, see the Remarks section.
...
[in] Specifies one or more optional arguments. The number and type of argument parameters depend on the corresponding format-control specifications in the lpFmt parameter.

Return Values

If the function succeeds, the return value is the number of characters stored in the output buffer, not counting the terminating null character.

If the function fails, the return value is less than the length of the expected output. To get extended error information, call GetLastError.

Remarks

The format-control string contains format specifications that determine the output format for the arguments following the lpFmt parameter. Format specifications, discussed below, always begin with a percent sign (%). If a percent sign is followed by a character that has no meaning as a format field, the character is not formatted (for example, %% produces a single percent-sign character).

The format-control string is read from left to right. When the first format specification (if any) is encountered, it causes the value of the first argument after the format-control string to be converted and copied to the output buffer according to the format specification. The second format specification causes the second argument to be converted and copied, and so on. If there are more arguments than format specifications, the extra arguments are ignored. If there are not enough arguments for all of the format specifications, the results are undefined.

A format specification has the following form:

%[-][#][0][width][.precision]type

Each field is a single character or a number signifying a particular format option. The type characters that appear after the last optional format field determine whether the associated argument is interpreted as a character, a string, or a number. The simplest format specification contains only the percent sign and a type character (for example, %s). The optional fields control other aspects of the formatting. Following are the optional and required fields and their meanings.

Field | Meaning
– | Pad the output with blanks or zeros to the right to fill the field width, justifying output to the left. If this field is omitted, the output is padded to the left, justifying it to the right.
# | Prefix hexadecimal values with 0x (lowercase) or 0X (uppercase).
0 | Pad the output value with zeros to fill the field width. If this field is omitted, the output value is padded with blank spaces.
width | Copy the specified minimum number of characters to the output buffer. The width field is a nonnegative integer. The width specification never causes a value to be truncated; if the number of characters in the output value is greater than the specified width, or if the width field is not present, all characters of the value are printed, subject to the precision specification.
.precision | For numbers, copy the specified minimum number of digits to the output buffer. If the number of digits in the argument is less than the specified precision, the output value is padded on the left with zeros. The value is not truncated when the number of digits exceeds the specified precision. If the specified precision is 0 or omitted entirely, or if the period (.) appears without a number following it, the precision is set to 1.
 | For strings, copy the specified maximum number of characters to the output buffer.
type | Output the corresponding argument as a character, a string, or a number. This field can be any of the following values.
 | Value | Meaning
 | c | Single character. This value is interpreted as type WCHAR if the calling application defines UNICODE and as type CHAR otherwise.
 | C | Single character. This value is interpreted as type CHAR if the calling application defines UNICODE and as type WCHAR otherwise.
 | d | Signed decimal integer. This value is equivalent to i.
 | hc, hC | Single character. The wsprintf function ignores character arguments with a numeric value of zero. This value is always interpreted as type CHAR, even when the calling application defines UNICODE.
 | hd | Signed short integer argument.
 | hs, hS | String. This value is always interpreted as type LPSTR, even when the calling application defines UNICODE.
 | hu | Unsigned short integer.
 | i | Signed decimal integer. This value is equivalent to d.
 | lc, lC | Single character. The wsprintf function ignores character arguments with a numeric value of zero. This value is always interpreted as type WCHAR, even when the calling application does not define UNICODE.
 | ld | Long signed integer. This value is equivalent to li.
 | li | Long signed integer. This value is equivalent to ld.
 | ls, lS | String. This value is always interpreted as type LPWSTR, even when the calling application does not define UNICODE. This value is equivalent to ws.
 | lu | Long unsigned integer.
 | lx, lX | Long unsigned hexadecimal integer in lowercase or uppercase.
 | p | Windows 2000 or later: Pointer. The address is printed using hexadecimal.
 | s | String. This value is interpreted as type LPWSTR when the calling application defines UNICODE and as type LPSTR otherwise.
 | S | String. This value is interpreted as type LPSTR when the calling application defines UNICODE and as type LPWSTR otherwise.
 | u | Unsigned integer argument.
 | x, X | Unsigned hexadecimal integer in lowercase or uppercase.

Note It is important to note that wsprintf uses the C calling convention (_cdecl), rather than the standard call (_stdcall) calling convention. As a result, it is the responsibility of the calling process to pop arguments off the stack, and arguments are pushed on the stack from right to left. In C-language modules, the C compiler performs this task.

To use buffers larger than 1024 bytes, use _snwprintf. For more information, see the documentation for the C run-time library.

For an example, see Reading from a Mailslot.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Strings Overview, String Functions, wvsprintf


wvsprintf

The wvsprintf function formats and stores a series of characters and values in a buffer. The items pointed to by the argument list are converted and copied to an output buffer according to the corresponding format specification in the format-control string. The function appends a terminating null character to the characters it writes, but the return value does not include the terminating null character in its character count.

int wvsprintf(
  LPTSTR lpOutput,  // buffer for output
  LPCTSTR lpFormat, // format-control string
  va_list arglist   // variable list of format-control arguments
);

Parameters

lpOutput
[out] Pointer to a buffer to receive the formatted output. The maximum size of the buffer is 1024 bytes.
lpFormat
[in] Pointer to a null-terminated string that contains the format-control specifications. In addition to ordinary ASCII characters, a format specification for each argument appears in this string. For more information about the format specification, see wsprintf.
arglist
[in] A variable argument list; each element of the list specifies an argument for the format-control string. The number, type, and interpretation of the arguments depend on the corresponding format-control specifications in the lpFmt parameter.

Return Values

If the function succeeds, the return value is the number of TCHARs stored in the buffer, not counting the terminating null character. This refers to bytes for ANSI versions of the function or WCHARs for Unicode versions.

If the function fails, the return value is less than the length of the expected output. To get extended error information, call GetLastError.

Remarks

The function copies the format-control string into the output buffer character by character, starting with the first character in the string. When it encounters a format specification in the string, the function retrieves the value of the next available argument (starting with the first argument in the list), converts that value into the specified format, and copies the result to the output buffer. The function continues to copy characters and expand format specifications in this way until it reaches the end of the format-control string. If there are more arguments than format specifications, the extra arguments are ignored. If there are not enough arguments for all of the format specifications, the results are undefined.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Strings Overview, String Functions, wsprintf


Version Information

Version information makes it easier for applications to install files properly and enables setup programs to analyze files currently installed. The version-information resource contains the file's version number, intended operating system, and original file name.

  • About Version Information
  • Using Version Information
  • Version Information Reference


About Version Information

You can use the version information functions to determine where a file should be installed and identify conflicts with currently installed files. These functions enable you to avoid the following problems:

  • installing older versions of components over newer versions
  • changing the language in a mixed-language system without notification
  • installing multiple copies of a library in different directories
  • copying files to network directories shared by multiple users

The version information functions enable applications to query a version resource for file information and present the information in a clear format. This information includes the file's purpose, author, version number, and so on.

You can add version information to any files that can have Windows resources, such as dynamic-link libraries (DLL), executable files, or font files. To add the information, create a VERSIONINFO resource and use the resource compiler to compile the resource.


Using Version Information

An installation program typically has the following goals:

  • To place files in the correct location.
  • To notify the user if the installation program is replacing an existing file with a version that is significantly different — for example, replacing a German-language file with an English-language file, or replacing a newer file with an older file.

When writing the installation program, you must have the following information for each file:

  • The name and location of the file (referred to as the source file).
  • The name of the equivalent file on the user's hard disk (referred to as the destination file). This name is usually the same as the filename on the installation disk.
  • The sharing status of the file — that is, whether the file is private to the application being installed or could be shared by multiple applications.

The installation program can use the VerFindFile function to determine where the file should be copied on the disk. This function can also be used to specify whether the file is private to the application or can be shared. If a problem occurs in finding the file, VerFindFile returns an error value. For example, if the system is using the destination file, VerFindFile returns VFF_FILEINUSE. The installation program must notify the user of the problem and respond to the user's decision to continue or to end the installation.

The VerInstallFile function copies the source file to a temporary file in the directory specified by VerFindFile. If necessary, VerInstallFile expands the file by using the functions in the data decompression library.

VerInstallFile compares the version information of the temporary file to that of the destination file. If the two differ, VerInstallFile returns one or more error values. For example, it returns VIF_SRCOLD if the temporary file is older than the destination file and VIF_DIFFLANG if the files have different language identifiers or code-page values. The installation program must notify the user of the problem and respond to the user's decision to continue or to end the installation.

Some VerInstallFile errors are recoverable. That is, the installation program can call VerInstallFile again, specifying the VIFF_FORCEINSTALL option, to install the file regardless of the version conflict. If VerInstallFile returns VIF_TEMPFILE and the user chooses not to force the installation, the installation program should delete the temporary file.

VerInstallFile could encounter a nonrecoverable error when attempting to force installation, even though the error did not exist previously. For example, the file could be locked by another user before the installation program attempted to force installation. If an installation program attempts to force installation after a non-recoverable error, VerInstallFile fails. The installation program must contain routines to recover from this type of error.

The recommended solution is to display a dialog box with the buttons Install, Skip, and Install All. (Another solution is a dialog box with the buttons Yes, Yes to All, Skip, and Cancel.) The Install All button should prevent the installation program from prompting the user about similar errors by including the VIFF_FORCEINSTALL option in all subsequent uses of VerInstallFile. For nonrecoverable errors, the Install and Install All buttons should be disabled.

To display a useful error message to the user, the installation program usually must retrieve information from the version resources of the conflicting files. There are four functions the installation program can use for this purpose:

  • GetFileVersionInfoSize
  • GetFileVersionInfo
  • VerQueryValue
  • VerLanguageName

GetFileVersionInfoSize returns the size of the version information. GetFileVersionInfo uses information retrieved by GetFileVersionInfoSize to retrieve a structure that contains the version information. VerQueryValue retrieves a specific member from that structure.

For example, if VerInstallFile returns the VIF_DIFFTYPE error, the installation program should use the GetFileVersionInfoSize, GetFileVersionInfo, and VerQueryValue functions on the temporary and destination files to obtain the general type of each file. If the languages of the files conflict, the installation program should also use VerLanguageName to translate the binary language identifier into a text representation of the language. (For example, 0x040C translates to the string "French.")

If VerInstallFile returns a file error, such as VIF_ACCESSVIOLATION, the installation program should use the GetLastError function to retrieve the most recent error value. The program should translate this value into an informative message to display to the user. The program must not yield control between the calls to VerInstallFile and GetLastError.


Version Information Reference

The following elements are used with version information:

  • Version Information Functions
  • Version Information Structures


Version Information Functions

The following functions are used with version information. Note that on Windows NT 3.51 and earlier, the version information functions work only with Win32 file images. They do not work with 16-bit Windows file images. On Windows 95/98 and Windows NT 4.0 and later, these functions work on both 16- and 32-bit file images. On Windows 2000 and later, these functions work on 16-, 32-, and 64-bit file images.

Function | Description
GetFileVersionInfo | Retrieves version information for the specified file.
GetFileVersionInfoSize | Determines whether the operating system can retrieve version information for a specified file. If version information is available, the function returns the size, in bytes, of that information.
VerFindFile | Determines where to install a file based on whether it locates another version of the file in the system.
VerInstallFile | Attempts to install the specified file based on information returned from the VerFindFile function.
VerLanguageName | Retrieves a description string for the language associated with a specified binary Microsoft language identifier.
VerQueryValue | Retrieves specified version information from the specified version-information resource.


GetFileVersionInfo

The GetFileVersionInfo function retrieves version information for the specified file.

BOOL GetFileVersionInfo(
  LPTSTR lptstrFilename,  // file name
  DWORD dwHandle,         // ignored
  DWORD dwLen,            // size of buffer
  LPVOID lpData           // version information buffer
);

Parameters

lptstrFilename
[in] Pointer to a null-terminated string that specifies the name of the file of interest. If a full path is not specified, the function uses the search sequence specified by the LoadLibrary function.

Windows 95/98/Me: The short path form of the specified file name must be less than 126 characters.

dwHandle
This parameter is ignored.
dwLen
[in] Specifies the size, in bytes, of the buffer pointed to by the lpData parameter.

Call the GetFileVersionInfoSize function first to determine the size, in bytes, of a file's version information. The dwLen member should be equal to or greater than that value.

If the buffer pointed to by lpData is not large enough, the function truncates the file's version information to the size of the buffer.

lpData
[out] Pointer to a buffer that receives the file-version information.

You can use this value in a subsequent call to the VerQueryValue function to retrieve data from the buffer.

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 3.51 and earlier: The version information functions work only with Win32 file images. They do not work with 16-bit Windows file images.

Windows 95/98 and Windows NT 4.0 and later: This works on both 16- and 32-bit file images.

Windows 2000 and later: This works on 16-, 32-, and 64-bit file images.

Call the GetFileVersionInfoSize function before calling the GetFileVersionInfo function. To retrieve information from the file-version information buffer, use the VerQueryValue function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winver.h; include Windows.h.
Library: Use Version.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Version Information Overview, Version Information Functions, GetFileVersionInfoSize, VerQueryValue, VS_VERSIONINFO


GetFileVersionInfoSize

The GetFileVersionInfoSize function determines whether the operating system can retrieve version information for a specified file. If version information is available, GetFileVersionInfoSize returns the size, in bytes, of that information.

DWORD GetFileVersionInfoSize(
  LPTSTR lptstrFilename,  // file name
  LPDWORD lpdwHandle      // set to zero
);

Parameters

lptstrFilename
[in] Pointer to a null-terminated string that specifies the name of the file of interest. The function uses the search sequence specified by the LoadLibrary function.

Windows 95/98/Me: The short path form of the specified file name must be less than 126 characters.

lpdwHandle
[out] Pointer to a variable that the function sets to zero.

Return Values

If the function succeeds, the return value is the size, in bytes, of the file's version information.

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

Remarks

Windows NT 3.51 and earlier: The version information functions work only with Win32 file images. They do not work with 16-bit Windows file images.

Windows 95/98 and Windows NT 4.0 and later: This works on both 16- and 32-bit file images.

Windows 2000 and later: This works on 16-, 32-, and 64-bit file images.

Call the GetFileVersionInfoSize function before calling the GetFileVersionInfo function. The size returned by GetFileVersionInfoSize indicates the buffer size required for the version information returned by GetFileVersionInfo.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winver.h; include Windows.h.
Library: Use Version.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Version Information Overview, Version Information Functions, GetFileVersionInfo, VS_VERSIONINFO, VerQueryValue


VerFindFile

The VerFindFile function determines where to install a file based on whether it locates another version of the file in the system. The values VerFindFile returns in the specified buffers are used in a subsequent call to the VerInstallFile function.

DWORD VerFindFile(
  DWORD dwFlags,      // option
  LPTSTR szFileName,  // file to be installed
  LPTSTR szWinDir,    // Windows directory
  LPTSTR szAppDir,    // install directory
  LPTSTR szCurDir,    // current directory buffer
  PUINT lpuCurDirLen, // size of current directory buffer
  LPTSTR szDestDir,   // recommended destination directory buffer
  PUINT lpuDestDirLen // size of destination directory buffer
);

Parameters

dwFlags
[in] This parameter can be the following value.
Flag | Description
VFFF_ISSHAREDFILE | The source file can be shared by multiple applications. An application can use this information to determine where the file should be copied.

All other bits are reserved.

szFileName
[in] Pointer to the name of the file to be installed. The filename can include only the filename and extension, not a path.
szWinDir
[in] Pointer to a string that specifies the directory in which Windows is running or will be run. This string is returned by the GetWindowsDirectory function.
szAppDir
[in] Pointer to a string that specifies the directory where the installation program is installing a set of related files. If the installation program is installing an application, this is the directory where the application will reside. This parameter also points to the application's current directory unless otherwise specified.
szCurDir
[out] Pointer to a buffer that receives the path to a current version of the file being installed. The path is a zero-terminated string. If a current version is not installed, the buffer will contain a zero-length string. The buffer should be at least _MAX_PATH characters long, although this is not required.
lpuCurDirLen
[in] Pointer to a variable that specifies the length of the szCurDir buffer. This pointer must not be NULL.

When the function returns, lpuCurDirLen contains the size, in characters, of the data returned in szCurDir, including the terminating null character. If the buffer is too small to contain all the data, lpuCurDirLen will be the size of the buffer required to hold the path.

szDestDir
[out] Pointer to a buffer that receives the path to the installation location recommended by VerFindFile. The path is a zero-terminated string. The buffer should be at least _MAX_PATH characters long, although this is not required.
lpuDestDirLen
[in] Pointer to a variable that specifies the length of the szDestDir buffer. This pointer must not be NULL.

When the function returns, lpuDestDirLen contains the size, in characters, of the data returned in szDestDir, including the terminating null character. If the buffer is too small to contain all the data, lpuDestDirLen will be the size of the buffer needed to hold the path.

Return Values

The return value is a bitmask that indicates the status of the file. It can be one or more of the following values:

Value | Meaning
VFF_CURNEDEST | The currently installed version of the file is not in the recommended destination.
VFF_FILEINUSE | The system is using the currently installed version of the file; therefore, the file cannot be overwritten or deleted.
VFF_BUFFTOOSMALL | At least one of the buffers was too small to contain the corresponding string. An application should check the output buffers to determine which buffer was too small.

All other values are reserved.

Remarks

Windows NT 3.51 and earlier: The version information functions work only with Win32 file images. They do not work with 16-bit Windows file images.

Windows 95/98 and Windows NT 4.0 and later: This works on both 16- and 32-bit file images.

Windows 2000 and later: This works on 16-, 32-, and 64-bit file images.

VerFindFile searches for a copy of the specified file by using the OpenFile function. However, it determines the system directory from the specified Windows directory, or searches the path.

If the dwFlags parameter indicates that the file is private to this application (not VFFF_ISSHAREDFILE), VerFindFile recommends installing the file in the application's directory. Otherwise, if the system is running a shared copy of the system, the function recommends installing the file in the Windows directory. If the system is running a private copy of the system, the function recommends installing the file in the system directory.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winver.h; include Windows.h.
Library: Use Version.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Version Information Overview, Version Information Functions, GetWindowsDirectory, OpenFile, VerInstallFile


VerInstallFile

The VerInstallFile function attempts to install the specified file based on information returned from the VerFindFile function. VerInstallFile decompresses the file, if necessary, assigns a unique filename, and checks for errors, such as outdated files.

DWORD VerInstallFile(
  DWORD uFlags,          // options
  LPTSTR szSrcFileName,  // file to install
  LPTSTR szDestFileName, // name of installed file
  LPTSTR szSrcDir,       // source directory
  LPTSTR szDestDir,      // install directory
  LPTSTR szCurDir,       // current directory
  LPTSTR szTmpFile,      // temporary file name buffer
  PUINT lpuTmpFileLen    // size of temporary file name buffer
);

Parameters

uFlags
[in] This parameter can be one of the following values.
Flag | Description
VIFF_FORCEINSTALL | Installs the file regardless of mismatched version numbers. The function checks only for physical errors during installation.
VIFF_DONTDELETEOLD | Installs the file without deleting the previously installed file, if the previously installed file is not in the destination directory.

All other bits are reserved.

szSrcFileName
[in] Pointer to a string that specifies the name of the file to be installed. This is the filename in the directory pointed to by the szSrcDir parameter; the filename can include only the filename and extension, not a path.
szDestFileName
[in] Pointer to a string that specifies the name VerInstallFile will give the new file upon installation. This filename may be different from the filename in the szSrcFileName directory. The new name should include only the filename and extension, not a path.
szSrcDir
[in] Pointer to a buffer that specifies the name of the directory where the file can be found.
szDestDir
[in] Pointer to a buffer that specifies the name of the directory where the file should be installed. VerFindFile returns this value in its szDestDir parameter.
szCurDir
[in] Pointer to a buffer that specifies the name of the directory where a preexisting version of this file can be found. VerFindFile returns this value in its szCurDir parameter.
szTmpFile
[out] Pointer to a buffer that receives the name of a temporary copy of the source file. The buffer should be at least _MAX_PATH characters long, although this is not required, and should be empty on input.
lpuTmpFileLen
[in/out] Pointer to a variable that specifies the length of the szTmpFile buffer. This pointer must not be NULL.

When the function returns, lpuTmpFileLen receives the size, in characters, of the data returned in szTmpFile, including the terminating null character. If the buffer is too small to contain all the data, lpuTmpFileLen will be the size of the buffer required to hold the data.

Return Values

The return value is a bitmask that indicates exceptions. It can be one or more of the following values.

Value | Meaning
VIF_ACCESSVIOLATION | A read, create, delete, or rename operation failed due to an access violation.
VIF_BUFFTOOSMALL | The szTmpFile buffer was too small to contain the name of the temporary source file. When the function returns, lpuTmpFileLen contains the size of the buffer required to hold the filename.
VIF_CANNOTCREATE | The function cannot create the temporary file. The specific error may be described by another flag.
VIF_CANNOTDELETE | The function cannot delete the destination file, or cannot delete the existing version of the file located in another directory. If the VIF_TEMPFILE bit is set, the installation failed, and the destination file probably cannot be deleted.
VIF_CANNOTDELETECUR | The existing version of the file could not be deleted and VIFF_DONTDELETEOLD was not specified.
VIF_CANNOTLOADCABINET | The function cannot load the cabinet file.
VIF_CANNOTLOADLZ32 | The function cannot load the compressed file.
VIF_CANNOTREADDST | The function cannot read the destination (existing) files. This prevents the function from examining the file's attributes.
VIF_CANNOTREADSRC | The function cannot read the source file. This could mean that the path was not specified properly.
VIF_CANNOTRENAME | The function cannot rename the temporary file, but already deleted the destination file.
VIF_DIFFCODEPG | The new file requires a code page that cannot be displayed by the version of the system currently running. This error can be overridden by calling VerInstallFile with the VIFF_FORCEINSTALL flag set.
VIF_DIFFLANG | The new and preexisting files have different language or code-page values. This error can be overridden by calling VerInstallFile again with the VIFF_FORCEINSTALL flag set.
VIF_DIFFTYPE | The new file has a different type, subtype, or operating system from the preexisting file. This error can be overridden by calling VerInstallFile again with the VIFF_FORCEINSTALL flag set.
VIF_FILEINUSE | The preexisting file is in use by the system and cannot be deleted.
VIF_MISMATCH | The new and preexisting files differ in one or more attributes. This error can be overridden by calling VerInstallFile again with the VIFF_FORCEINSTALL flag set.
VIF_OUTOFMEMORY | The function cannot complete the requested operation due to insufficient memory. Generally, this means the application ran out of memory attempting to expand a compressed file.
VIF_OUTOFSPACE | The function cannot create the temporary file due to insufficient disk space on the destination drive.
VIF_SHARINGVIOLATION | A read, create, delete, or rename operation failed due to a sharing violation.
VIF_SRCOLD | The file to install is older than the preexisting file. This error can be overridden by calling VerInstallFile again with the VIFF_FORCEINSTALL flag set.
VIF_TEMPFILE | The temporary copy of the new file is in the destination directory. The cause of failure is reflected in other flags.
VIF_WRITEPROT | The preexisting file is write-protected. This error can be overridden by calling VerInstallFile again with the VIFF_FORCEINSTALL flag set.

All other values are reserved.

Remarks

Windows NT 3.51 and earlier: The version information functions work only with Win32 file images. They do not work with 16-bit Windows file images.

Windows 95/98 and Windows NT 4.0 and later: This works on both 16- and 32-bit file images.

Windows 2000 and later: This works on 16-, 32-, and 64-bit file images.

VerInstallFile copies the file from the source directory to the destination directory. If szCurDir indicates that a previous version of the file exists on the system, VerInstallFile compares the files' version stamp information. If the previously installed version of the file is more recent than the new version, or if the files' attributes are significantly different, for example, if they are in different languages, then VerInstallFile returns with one or more recoverable error codes.

VerInstallFile leaves the temporary file in the destination directory. The application can either override the error or delete the temporary file. If the application overrides the error, VerInstallFile deletes the previously installed version and renames the temporary file with the original filename.

Windows 95/98/Me: All file names must be in 8.3 format; long file names are not supported.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winver.h; include Windows.h.
Library: Use Version.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Version Information Overview, Version Information Functions, VerFindFile


VerLanguageName

The VerLanguageName function retrieves a description string for the language associated with a specified binary Microsoft language identifier.

DWORD VerLanguageName(
  DWORD wLang,    // Microsoft language identifier
  LPTSTR szLang,  // language description buffer
  DWORD nSize     // size of buffer
);

Parameters

wLang
[in] Specifies the binary Microsoft language identifier. For a complete list of the language identifiers supported by Win32, see Language Identifiers.

For example, the description string associated with the language identifier 0x040A is "Spanish (Traditional Sort)". If the identifier is unknown, the szLang parameter points to a default string ("Language Neutral").

szLang
[out] Pointer to the buffer that receives the null-terminated string representing the language specified by the wLang parameter.
nSize
[in] Specifies the size of the buffer, in characters, pointed to by szLang.

Return Values

If the return value is less than or equal to the buffer size, the return value is the size, in characters, of the string returned in the buffer. This value does not include the terminating null character.

If the return value is greater than the buffer size, the return value is the size of the buffer required to hold the entire string. The string is truncated to the length of the existing buffer.

If an error occurs, the return value is zero. Unknown language identifiers do not produce errors.

Remarks

Windows NT 3.51 and earlier: The version information functions work only with Win32 file images. They do not work with 16-bit Windows file images.

Windows 95/98 and Windows NT 4.0 and later: This works on both 16- and 32-bit file images.

Windows 2000 and later: This works on 16-, 32-, and 64-bit file images.

Typically, an installation program uses this function to translate a language identifier returned by the VerQueryValue function. The text string may be used in a dialog box that asks the user how to proceed in the event of a language conflict.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winver.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Version Information Overview, Version Information Functions, VerQueryValue


VerQueryValue

The VerQueryValue function retrieves specified version information from the specified version-information resource. To retrieve the appropriate resource, before you call VerQueryValue, you must first call the GetFileVersionInfoSize function, and then the GetFileVersionInfo function.

BOOL VerQueryValue(
  const LPVOID pBlock, // buffer for version resource
  LPTSTR lpSubBlock,   // value to retrieve
  LPVOID *lplpBuffer,  // buffer for version value pointer
  PUINT puLen          // version length
);

Parameters

pBlock
[in] Pointer to the buffer containing the version-information resource returned by the GetFileVersionInfo function.
lpSubBlock
[in] Pointer to a zero-terminated string specifying which version-information value to retrieve. The string must consist of names separated by backslashes (\) and it must have one of the following forms.
Form | Description
\ Specifies the root block. The function retrieves a pointer to the VS_FIXEDFILEINFO structure for the version-information resource.
\VarFileInfo\Translation | Specifies the translation array in a Var variable information structure. The function retrieves a pointer to an array of language and code page identifiers. An application can use these identifiers to access a language-specific StringTable structure in the version-information resource.
\StringFileInfo\lang-codepage\string-name | Specifies a value in a language-specific StringTable structure. The lang-codepage name is a concatenation of a language and code page identifier pair found as a DWORD in the translation array for the resource. Here the lang-codepage name must be specified as a hexadecimal string. The string-name name must be one of the predefined strings described in the following Remarks section. The function retrieves a string value specific to the language and code page indicated.

lplpBuffer
[out] Pointer to a variable that receives a pointer to the requested version information in the buffer pointed to by pBlock. The memory pointed to by *lplpBuffer is freed when the associated pBlock memory is freed.
puLen
[out] Pointer to a buffer that receives the length, in characters, of the version-information value.

Return Values

If the specified version-information structure exists, and version information is available, the return value is nonzero. If the address of the length buffer is zero, no value is available for the specified version-information name.

If the specified name does not exist or the specified resource is not valid, the return value is zero.

Remarks

Windows NT 3.51 and earlier: The version information functions work only with Win32 file images. They do not work with 16-bit Windows file images.

Windows 95/98 and Windows NT 4.0 and later: This works on both 16- and 32-bit file images.

Windows 2000 and later: This works on 16-, 32-, and 64-bit file images.

The following are predefined version information Unicode strings:

Comments | InternalName | ProductName
CompanyName | LegalCopyright | ProductVersion
FileDescription | LegalTrademarks | PrivateBuild
FileVersion | OriginalFilename | SpecialBuild

Example

The following example shows how to enumerate the available version languages and retrieve the FileDescription string-value for each language.

// Structure used to store enumerated languages and code pages.

struct LANGANDCODEPAGE {
  WORD wLanguage;
  WORD wCodePage;
} *lpTranslate;

// Read the list of languages and code pages.

VerQueryValue(pBlock,
              TEXT("\\VarFileInfo\\Translation"),
              (LPVOID*)&lpTranslate,
              &cbTranslate);

// Read the file description for each language and code page.

for( i=0; i < (cbTranslate/sizeof(struct LANGANDCODEPAGE)); i++ )
{
  wsprintf( SubBlock,
            TEXT("\\StringFileInfo\\%04x%04x\\FileDescription"),
            lpTranslate[i].wLanguage,
            lpTranslate[i].wCodePage);

  // Retrieve file description for language and code page "i".
  VerQueryValue(pBlock,
                SubBlock,
                &lpBuffer,
                &dwBytes);
}

Be sure to call the GetFileVersionInfoSize and GetFileVersionInfo functions before calling VerQueryValue to properly initialize the pBlock buffer.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winver.h; include Windows.h.
Library: Use Version.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Version Information Overview, Version Information Functions, GetFileVersionInfo, VarFileInfo, Var, StringFileInfo, StringTable, String, GetFileVersionInfoSize, VS_FIXEDFILEINFO, VS_VERSIONINFO


Version Information Structures

The following structures are used with version information.

String
StringFileInfo
StringTable
Var
VarFileInfo
VS_FIXEDFILEINFO
VS_VERSIONINFO


String

The String structure depicts the organization of data in a file-version resource. It contains a string that describes a specific aspect of a file, for example, a file's version, its copyright notices, or its trademarks.

This structure is not a true C-language structure because it contains variable-length members. This structure was created solely to depict the organization of data in a version resource and does not appear in any of the header files shipped with the Microsoft® Platform Software Development Kit (SDK).

struct String {
  WORD   wLength;
  WORD   wValueLength;
  WORD   wType;
  WCHAR  szKey[];
  WORD   Padding[];
  WORD   Value[];
};

Members

wLength
Specifies the length, in bytes, of this String structure.
wValueLength
Specifies the size, in words, of the Value member.
wType
Specifies the type of data in the version resource. This member is 1 if the version resource contains text data and 0 if the version resource contains binary data.
szKey
Specifies an arbitrary Unicode string. The szKey member can be one or more of the following values. These values are guidelines only.
String | Meaning
Comments | The Value member contains any additional information that should be displayed for diagnostic purposes. This string can be an arbitrary length.
CompanyName | The Value member identifies the company that produced the file. For example, "Microsoft Corporation" or "Standard Microsystems Corporation, Inc."
FileDescription | The Value member describes the file in such a way that it can be presented to users. This string may be presented in a list box when the user is choosing files to install. For example, "Keyboard driver for AT-style keyboards" or "Microsoft Word for Windows".
FileVersion | The Value member identifies the version of this file. For example, Value could be "3.00A" or "5.00.RC2".
InternalName | The Value member identifies the file's internal name, if one exists. For example, this string could contain the module name for a dynamic-link library (DLL), a virtual device name for a Windows virtual device, or a device name for an MS-DOS device driver.
LegalCopyright | The Value member describes all copyright notices, trademarks, and registered trademarks that apply to the file. This should include the full text of all notices, legal symbols, copyright dates, trademark numbers, and so on. In English, this string should be in the format "Copyright Microsoft Corp. 1990–1994".
LegalTrademarks | The Value member describes all trademarks and registered trademarks that apply to the file. This should include the full text of all notices, legal symbols, trademark numbers, and so on. In English, this string should be in the format "Windows is a trademark of Microsoft Corporation".
OriginalFilename | The Value member identifies the original name of the file, not including a path. This enables an application to determine whether a file has been renamed by a user. This name may not be MS-DOS 8.3-format if the file is specific to a non-FAT file system.
PrivateBuild | The Value member describes by whom, where, and why this private version of the file was built. This string should only be present if the VS_FF_PRIVATEBUILD flag is set in the dwFileFlags member of the VS_FIXEDFILEINFO structure. For example, Value could be "Built by OSCAR on \OSCAR2".
ProductName | The Value member identifies the name of the product with which this file is distributed. For example, this string could be "Microsoft Windows".
ProductVersion | The Value member identifies the version of the product with which this file is distributed. For example, Value could be "3.00A" or "5.00.RC2".
SpecialBuild | The Value member describes how this version of the file differs from the normal version. This entry should only be present if the VS_FF_SPECIALBUILD flag is set in the dwFileFlags member of the VS_FIXEDFILEINFO structure. For example, Value could be "Private build for Olivetti solving mouse problems on M250 and M250E computers".

Padding
Contains as many zero words as necessary to align the Value member on a 32-bit boundary.
Value
Specifies a zero-terminated string. See the szKey member description for more information.

Remarks

A String structure may have an szKey value of, for example, "CompanyName" and a Value of "Microsoft Corporation". Another String structure with the same szKey value could contain a Value of "Microsoft GmbH". This might occur if the second String structure were associated with a StringTable structure whose szKey value is 040704b0 — that is, German/Unicode.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.

See Also

Version Information Overview, Version Information Structures, StringTable, VS_FIXEDFILEINFO, StringFileInfo, VS_VERSIONINFO


StringFileInfo

The StringFileInfo structure depicts the organization of data in a file-version resource. It contains version information that can be displayed for a particular language and code page.

This structure is not a true C-language structure because it contains variable-length members. This structure was created solely to depict the organization of data in a version resource and does not appear in any of the header files shipped with the Microsoft Platform Software Development Kit (SDK).

struct StringFileInfo {
  WORD        wLength;
  WORD        wValueLength;
  WORD        wType;
  WCHAR       szKey[];
  WORD        Padding[];
  StringTable Children[];
};

Members

wLength
Specifies the length, in bytes, of the entire StringFileInfo block, including all structures indicated by the Children member.
wValueLength
This member is always equal to zero.
wType
Specifies the type of data in the version resource. This member is 1 if the version resource contains text data and 0 if the version resource contains binary data.
szKey
Contains the Unicode string "StringFileInfo".
Padding
Contains as many zero words as necessary to align the Children member on a 32-bit boundary.
Children
Contains an array of one or more StringTable structures. Each StringTable structure's szKey member indicates the appropriate language and code page for displaying the text in that StringTable structure.

Remarks

The Children member of the VS_VERSIONINFO structure may contain zero or more StringFileInfo structures.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.

See Also

Version Information Overview, Version Information Structures, StringTable, String, VS_VERSIONINFO


StringTable

The StringTable structure depicts the organization of data in a file-version resource. It contains language and code page formatting information for the strings specified by the Children member. A code page is an ordered character set.

This structure is not a true C-language structure because it contains variable-length members. This structure was created solely to depict the organization of data in a version resource and does not appear in any of the header files shipped with the Microsoft Platform Software Development Kit (SDK).

struct StringTable {
  WORD   wLength;
  WORD   wValueLength;
  WORD   wType;
  WCHAR  szKey[];
  WORD   Padding[];
  String Children[];
};

Members

wLength
Specifies the length, in bytes, of this StringTable structure, including all structures indicated by the Children member.
wValueLength
This member is always equal to zero.
wType
Specifies the type of data in the version resource. This member is 1 if the version resource contains text data and 0 if the version resource contains binary data.
szKey
Specifies an 8-digit hexadecimal number stored as a Unicode string. The four most significant digits represent the language identifier. The four least significant digits represent the code page for which the data is formatted.

Each Microsoft Standard Language identifier contains two parts: the low-order 10 bits specify the major language, and the high-order 6 bits specify the sublanguage. For a table of valid identifiers see Language Identifiers.

Padding
Contains as many zero words as necessary to align the Children member on a 32-bit boundary.
Children
Specifies an array of one or more String structures.

Remarks

The Children member of the StringFileInfo structure contains at least one StringTable structure.

Set the code page portion of the szKey member to the hexadecimal value 0x04b0 to indicate the Unicode code page, or to the hexadecimal value of the code page that is appropriate for the language component. After you choose the value for the code page you should continue to use the same value in later revisions to the file.

An executable file or dynamic-link library (DLL) that supports multiple languages should have a version resource for each language, rather than a single version resource that contains strings in several languages. However, if you use the Var structure to list the languages that your application supports, the number of StringTable structures in the version resource is directly related to the number of language/code page identifier pairs in the Value member of the Var structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.

See Also

Version Information Overview, Version Information Structures, String, StringFileInfo, Var, VarFileInfo, VS_VERSIONINFO


Var

The Var structure depicts the organization of data in a file-version resource. It typically contains a list of language and code page identifier pairs that the version of the application or dynamic-link library (DLL) supports.

This structure is not a true C-language structure because it contains variable-length members. This structure was created solely to depict the organization of data in a version resource and does not appear in any of the header files shipped with the Microsoft Platform Software Development Kit (SDK).

struct Var {
  WORD  wLength;
  WORD  wValueLength;
  WORD  wType;
  WCHAR szKey[];
  WORD  Padding[];
  DWORD Value[];
};

Members

wLength
Specifies the length, in bytes, of the Var structure.
wValueLength
Specifies the length, in bytes, of the Value member.
wType
Specifies the type of data in the version resource. This member is 1 if the version resource contains text data and 0 if the version resource contains binary data.
szKey
Contains the Unicode string "Translation".
Padding
Contains as many zero words as necessary to align the Value member on a 32-bit boundary.
Value
Specifies an array of one or more values that are language and code page identifier pairs. For additional information, see the following Remarks section.

Remarks

If you use the Var structure to list the languages your application or DLL supports instead of using multiple version resources, use the Value member to contain an array of DWORD values indicating the language and code page combinations supported by this file. The low-order word of each DWORD must contain a Microsoft language identifier, and the high-order word must contain the IBM® code page number. Either high-order or low-order word can be zero, indicating that the file is language or code page independent. If the Var structure is omitted, the file will be interpreted as both language and code page independent.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.

See Also

Version Information Overview, Version Information Structures, VarFileInfo, StringFileInfo, StringTable, VS_VERSIONINFO


VarFileInfo

The VarFileInfo structure depicts the organization of data in a file-version resource. It contains version information not dependent on a particular language and code page combination.

This structure is not a true C-language structure because it contains variable-length members. This structure was created solely to depict the organization of data in a version resource and does not appear in any of the header files shipped with the Microsoft Platform Software Development Kit (SDK).

struct VarFileInfo {
  WORD  wLength;
  WORD  wValueLength;
  WORD  wType;
  WCHAR szKey[];
  WORD  Padding[];
  Var   Children[];
};

Members

wLength
Specifies the length, in bytes, of the entire VarFileInfo block, including all structures indicated by the Children member.
wValueLength
This member is always equal to zero.
wType
Specifies the type of data in the version resource. This member is 1 if the version resource contains text data and 0 if the version resource contains binary data.
szKey
Contains the Unicode string "VarFileInfo".
Padding
Contains as many zero words as necessary to align the Children member on a 32-bit boundary.
Children
Specifies a Var structure that typically contains a list of languages that the application or DLL supports.

Remarks

The Children member of the VS_VERSIONINFO structure may contain zero or one VarFileInfo structures.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.

See Also

Version Information Overview, Version Information Structures, Var, VS_VERSIONINFO


VS_FIXEDFILEINFO

The VS_FIXEDFILEINFO structure contains version information about a file. This information is language and code page independent.

struct VS_FIXEDFILEINFO {
  DWORD dwSignature;
  DWORD dwStrucVersion;
  DWORD dwFileVersionMS;
  DWORD dwFileVersionLS;
  DWORD dwProductVersionMS;
  DWORD dwProductVersionLS;
  DWORD dwFileFlagsMask;
  DWORD dwFileFlags;
  DWORD dwFileOS;
  DWORD dwFileType;
  DWORD dwFileSubtype;
  DWORD dwFileDateMS;
  DWORD dwFileDateLS;
};

Members

dwSignature
Contains the value 0xFEEFO4BD. This is used with the szKey member of the VS_VERSIONINFO structure when searching a file for the VS_FIXEDFILEINFO structure.
dwStrucVersion
Specifies the binary version number of this structure. The high-order word of this member contains the major version number, and the low-order word contains the minor version number.
dwFileVersionMS
Specifies the most significant 32 bits of the file's binary version number. This member is used with dwFileVersionLS to form a 64-bit value used for numeric comparisons.
dwFileVersionLS
Specifies the least significant 32 bits of the file's binary version number. This member is used with dwFileVersionMS to form a 64-bit value used for numeric comparisons.
dwProductVersionMS
Specifies the most significant 32 bits of the binary version number of the product with which this file was distributed. This member is used with dwProductVersionLS to form a 64-bit value used for numeric comparisons.
dwProductVersionLS
Specifies the least significant 32 bits of the binary version number of the product with which this file was distributed. This member is used with dwProductVersionMS to form a 64-bit value used for numeric comparisons.
dwFileFlagsMask
Contains a bitmask that specifies the valid bits in dwFileFlags. A bit is valid only if it was defined when the file was created.
dwFileFlags
Contains a bitmask that specifies the Boolean attributes of the file. This member can include one or more of the following values.
Flag | Description
VS_FF_DEBUG | The file contains debugging information or is compiled with debugging features enabled.
VS_FF_INFOINFERRED | The file's version structure was created dynamically; therefore, some of the members in this structure may be empty or incorrect. This flag should never be set in a file's VS_VERSIONINFO data.
VS_FF_PATCHED | The file has been modified and is not identical to the original shipping file of the same version number.
VS_FF_PRERELEASE | The file is a development version, not a commercially released product.
VS_FF_PRIVATEBUILD | The file was not built using standard release procedures. If this flag is set, the StringFileInfo structure should contain a PrivateBuild entry.
VS_FF_SPECIALBUILD | The file was built by the original company using standard release procedures but is a variation of the normal file of the same version number. If this flag is set, the StringFileInfo structure should contain a SpecialBuild entry.

dwFileOS
Specifies the operating system for which this file was designed. This member can be one of the following values.
Flag | Description
VOS_DOS | The file was designed for MS-DOS.
VOS_NT | The file was designed for Windows NT/Windows 2000.
VOS__WINDOWS16 | The file was designed for 16-bit Windows.
VOS__WINDOWS32 | The file was designed for the Win32 API.
VOS_OS216 | The file was designed for 16-bit OS/2.
VOS_OS232 | The file was designed for 32-bit OS/2.
VOS__PM16 | The file was designed for 16-bit Presentation Manager.
VOS__PM32 | The file was designed for 32-bit Presentation Manager.
VOS_UNKNOWN | The operating system for which the file was designed is unknown to the system.

An application can combine these values to indicate that the file was designed for one operating system running on another. The following dwFileOS values are examples of this, but are not a complete list.
Flag | Description
VOS_DOS_WINDOWS16 | The file was designed for 16-bit Windows running on MS-DOS.
VOS_DOS_WINDOWS32 | The file was designed for 32-bit Windows running on MS-DOS.
VOS_NT_WINDOWS32 | The file was designed for Windows NT/Windows 2000.
VOS_OS216_PM16 | The file was designed for 16-bit Presentation Manager running on 16-bit OS/2.
VOS_OS232_PM32 | The file was designed for 32-bit Presentation Manager running on 32-bit OS/2.

dwFileType
Specifies the general type of file. This member can be one of the following values.
Flag | Description
VFT_UNKNOWN | The file type is unknown to the system.
VFT_APP | The file contains an application.
VFT_DLL | The file contains a dynamic-link library (DLL).
VFT_DRV | The file contains a device driver. If dwFileType is VFT_DRV, dwFileSubtype contains a more specific description of the driver.
VFT_FONT | The file contains a font. If dwFileType is VFT_FONT, dwFileSubtype contains a more specific description of the font file.
VFT_VXD | The file contains a virtual device.
VFT_STATIC_LIB | The file contains a static-link library.

All other values are reserved for future use by Microsoft.

dwFileSubtype
Specifies the function of the file. The possible values depend on the value of dwFileType. For all values of dwFileType not described in the following list, dwFileSubtype is zero.

If dwFileType is VFT_DRV, dwFileSubtype can be one of the following values.
Flag | Description
VFT2_UNKNOWN | The driver type is unknown by the system.
VFT2_DRV_COMM | The file contains a communications driver.
VFT2_DRV_PRINTER | The file contains a printer driver.
VFT2_DRV_KEYBOARD | The file contains a keyboard driver.
VFT2_DRV_LANGUAGE | The file contains a language driver.
VFT2_DRV_DISPLAY | The file contains a display driver.
VFT2_DRV_MOUSE | The file contains a mouse driver.
VFT2_DRV_NETWORK | The file contains a network driver.
VFT2_DRV_SYSTEM | The file contains a system driver.
VFT2_DRV_INSTALLABLE | The file contains an installable driver.
VFT2_DRV_SOUND | The file contains a sound driver.

If dwFileType is VFT_FONT, dwFileSubtype can be one of the following values.
Flag | Description
VFT2_UNKNOWN | The font type is unknown by the system.
VFT2_FONT_RASTER | The file contains a raster font.
VFT2_FONT_VECTOR | The file contains a vector font.
VFT2_FONT_TRUETYPE | The file contains a TrueType font.

If dwFileType is VFT_VXD, dwFileSubtype contains the virtual device identifier included in the virtual device control block.

All dwFileSubtype values not listed here are reserved for future use by Microsoft.

dwFileDateMS
Specifies the most significant 32 bits of the file's 64-bit binary creation date and time stamp.
dwFileDateLS
Specifies the least significant 32 bits of the file's 64-bit binary creation date and time stamp.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winver.h; include Windows.h.

See Also

Version Information Overview, Version Information Structures, StringFileInfo, String, VS_VERSIONINFO


VS_VERSIONINFO

The VS_VERSIONINFO structure depicts the organization of data in a file-version resource. It is the root structure that contains all other file-version information structures.

This structure is not a true C-language structure because it contains variable-length members. This structure was created solely to depict the organization of data in a version resource and does not appear in any of the header files shipped with the Microsoft Platform Software Development Kit (SDK).

struct VS_VERSIONINFO {
  WORD  wLength;
  WORD  wValueLength;
  WORD  wType;
  WCHAR szKey[];
  WORD  Padding1[];
  VS_FIXEDFILEINFO Value;
  WORD  Padding2[];
  WORD  Children[];
};

Members

wLength
Specifies the length, in bytes, of the VS_VERSIONINFO structure. This length does not include any padding that aligns any subsequent version resource data on a 32-bit boundary.
wValueLength
Specifies the length, in bytes, of the Value member. This value is zero if there is no Value member associated with the current version structure.
wType
Specifies the type of data in the version resource. This member is 1 if the version resource contains text data and 0 if the version resource contains binary data.
szKey
Contains the Unicode string "VS_VERSION_INFO".
Padding1
Contains as many zero words as necessary to align the Value member on a 32-bit boundary.
Value
Contains a VS_FIXEDFILEINFO structure that specifies arbitrary data associated with this VS_VERSIONINFO structure. The wValueLength member specifies the length of this member; if wValueLength is zero, this member does not exist.
Padding2
Contains as many zero words as necessary to align the Children member on a 32-bit boundary. These bytes are not included in wValueLength. This member is optional.
Children
Specifies an array of zero or one StringFileInfo structures, and zero or one VarFileInfo structures that are children of the current VS_VERSIONINFO structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.

See Also

Version Information Overview, Version Information Structures, StringFileInfo, VerQueryValue, VarFileInfo, VS_FIXEDFILEINFO


Message Compiler

The Microsoft® Message Compiler (MC) is a tool for creating messages needed by an application or dynamic-link library (DLL). Its input is a message text file, which defines the messages. The message text file format makes it easy to support multiple languages in the same image file.

This overview discusses how to create and compile message text files for inclusion in a resource script.

  • About Message Text Files
  • Using MC (The MC Command Line)


About Message Text Files

Messages are defined using ASCII text in a message text file. The message compiler automatically assigns numbers to each message, and generates a C/C++ include file for use by the application to access a message using a symbolic constant.

To use a message text file in your application, you must include it in a resource script (.RC) file. First, use MC to convert the message text file into a binary file suitable for inclusion in the .RC file. Then, use the resource compiler to place the messages into the resource table for the application.

For applications performing event logging, the messages are typically placed in a DLL that contains nothing but the message table. This resource-only DLL is registered by the application as the source of message text for the events that it logs. The application then uses the event logging functions or the FormatMessage function to retrieve and use the message text.

For information about the format of message text files, see the following topics.

  • Message Text File General Syntax
  • Message Text File Comments
  • Header Section
  • Message Definitions
  • Language-Specific Message Text Definitions


Message Text File General Syntax

The general syntax for lines in the message text file is:

keyword=value

Spaces around the equal sign are ignored, and the value is delimited by white space (including line breaks) from the next keyword=value pair. Case is ignored when comparing against keyword names. The value portion can be a numeric integer constant using C/C++ syntax; a symbol name that follows the rules for C/C++ identifiers; or a file name with eight characters or less, with no periods.


Message Text File Comments

Comment lines are allowed in the message text file. A semicolon (;) begins a comment that ends at the end of the line. A comment by itself on a line is copied to the generated include file with the semicolon converted to the C++ line-comment delimiter (//).


Header Section

The message text file contains a header which defines names and language identifiers for use by the message definitions in the body of the file. The header contains zero or more of the following statements:

MessageIdTypedef = [type]
SeverityNames = (name=number[:name])
FacilityNames = (name=number[:name])
LanguageNames = (name=number:filename)
OutputBase = {number}

MessageIdTypedef = type
Gives a typedef name that is used in a type cast for each message code in the generated include file. Each message code appears in the include file with the format:

#define name ((type) 0x nnnnnnnn)

The default value for type is empty, and no type cast is generated. It is the programmer's responsibility to specify a typedef statement in the application source code to define the type. The type used in the typedef must be large enough to accommodate the entire 32-bit message code.

SeverityNames = (name=number[:name])
Defines the set of names that are allowed as the value of the Severity keyword in the message definition. The set is delimited by left and right parentheses. Associated with each severity name is a number that, when shifted left by 30, gives the bit pattern to logical-OR with the Facility value and MessageId value to form the full 32-bit message code.

The default value of this keyword is:

SeverityNames=(
    Success=0x0
    Informational=0x1
    Warning=0x2
    Error=0x3
    )

Severity values occupy the high two bits of a 32-bit message code. Any severity value that does not fit in two bits is an error. The severity codes can be given symbolic names by following each value with :name

FacilityNames = (name=number[:name])
Defines the set of names that are allowed as the value of the Facility keyword in the message definition. The set is delimited by left and right parentheses. Associated with each facility name is a number that, when shifted left by 16 bits, gives the bit pattern to logical-OR with the Severity value and MessageId value to form the full 32-bit message code.

The default value of this keyword is:

FacilityNames=(
    System=0x0FF
    Application=0xFFF
    )

Facility codes occupy the low-order 12 bits of the high-order 16 bits of a 32-bit message code. Any facility code that does not fit in 12 bits is an error. This allows for 4096 facility codes. The first 256 codes are reserved for use by the system software. The facility codes can be given symbolic names by following each value with :name

LanguageNames = (name=number:filename)
Defines the set of names that are allowed as the value of the Language keyword in the message definition. The set is delimited by left and right parentheses. Associated with each language name are a number and a file name that are used to name the generated resource file that contains the messages for that language. The number corresponds to the language identifier to use in the resource table. The number is separated from the file name by a colon.

The initial value of LanguageNames is:

LanguageNames=(English=1:MSG00001)

Any new names in the message text file which don't override the built-in names are added to the list of valid languages. This allows an application to support private languages with descriptive names. For example, use the following syntax in the .MC file to support messages in both English and Japanese:

LanguageNames=(English=0x409:MSG00409)
LanguageNames=(Japanese=0x411:MSG00411)

MessageId=0x1
Severity=Error
Facility=Runtime
SymbolicName=MSG_BAD_COMMAND
Language=English
You have chosen an incorrect command.

Language=Japanese
òsÉ|é+âRâ}âôâhé¬æIæ=é|éOé_é|é+.
OutputBase = {number}
Sets the output radix for the message constants output to the C/C++ include file. It does not set the radix for the Severity and Facility constants; these default to HEX, but can be output in decimal by using the -d switch. If present, OutputBase overrides the -d switch for message constants in the include file.

The legal values for number are 10 and 16.

You can use OutputBase in both the header section and the message definition section of the input file. You can change OutputBase as often as you like.


Message Definitions

Following the header section is the body of the message text file. The body consists of zero or more message definitions. Each message definition begins with one or more of the following statements.

MessageId = [number|+number]
Severity = severity_name
Facility = facility_name
SymbolicName = name
OutputBase = {number}

The MessageId statement marks the beginning of the message definition. A MessageID statement is required for each message, although the value is optional. If no value is specified, the value used is the previous value for the facility plus one. If the value is specified as +number then the value used is the previous value for the facility, plus the number after the plus sign. Otherwise, if a numeric value is given, that value is used. Any MessageId value that does not fit in 16 bits is an error.

The Severity and Facility statements are optional. These statements specify additional bits to OR into the final 32-bit message code. If not specified they default to the value last specified for a message definition. The initial values prior to processing the first message definition are:

Severity=Success
Facility=Application

The value associated with Severity and Facility must match one of the names given in the FacilityNames and SeverityNames statements in the header section.

The SymbolicName statement allows you to associate a C/C++ symbolic constant with the final 32-bit message code.

The constant definition in the generated include file has the format:

//
// message text
//

#define name ((type) 0x nnnnnnnn)

The comment before the definition is a copy of the message text for the first language specified in the message definition. The name is the value given in the SymbolicName statement. The type is the type name specified in the MessageIdTypedef statement. If no type was specified, the cast is not generated.

The following comment appears in each header file to explain the bit fields in the 32-bit message:

//  Values are 32 bit values laid out as follows:
//
//   3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
//   1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
//  +---+-+-+-----------------------+-------------------------------+
//  |Sev|C|R|     Facility          |               Code            |
//  +---+-+-+-----------------------+-------------------------------+
//

The meanings of the fields in the message code are:

Sev
The severity code:
Bits | Meaning
00 | Success
01 | Informational
10 | Warning
11 | Error

C
The Customer code flag.
R
A reserved bit.
Facility
The facility code.
Code
The status code for the facility.

The OutputBase statement lets you set the output radix for the message constants output to the C/C++ include file. It does not set the radix for the Severity and Facility constants; these default to HEX, but can be output in decimal by using the -d switch. If present, OutputBase overrides the -d switch for message constants in the include file.

The legal values for number are 10 and 16

You can use OutputBase in both the header section and the message definition section of the input file. You can change OutputBase as often as you like.


Language-Specific Message Text Definitions

After the message definition statements, you specify one or more message text definitions.

Syntax

Language=language_name
messagetext

Each message begins with a Language statement that identifies the binary output file for this message. The first line of the message text begins with the next line. The message text is terminated by a line containing a single period at the beginning of the line, immediately followed by a new line. No spaces are allowed around the terminating period. Within the message, blank lines and white space are preserved as part of the message.

You can specify several escape sequences for formatting the message when the message text is used by the application or an event viewer. The percent sign character (%) begins all escape sequences.

%0
Terminates a message text line without a trailing newline. This can be used to build up long lines or to terminate the message without a trailing newline, which is useful for prompt messages.
%n[!printf-format-specifier!]
Identifies an insert. Each insert refers to a parameter used in a call to the FormatMessage function. FormatMessage returns an error if the message text specifies an insert that was not passed to FormatMessage.

The value of n can be between 1 and 99. The printf format specifier must be enclosed in exclamation marks. It is optional and defaults to !s! if not specified.

The printf format specifier can contain the * specifier for either the precision or width components. When specified, they consume inserts numbered n+1 and n+2 for their values at run time. MC prints a warning message if these inserts are specified elsewhere in the message text.

Any character following a percent sign other than a digit is formatted in the output message without the percent sign.

You can specify the following additional escape sequences:

%%
Generates a single percent sign in the formatted message text.
%\
Generates a hard line break when it occurs at the end of a line. Useful when FormatMessage is supplying normal line breaks so the message fits in a certain width.
%r
Generates a hard carriage return, without a trailing newline character.
%b
Generates a space character in the formatted message text. This can be used to ensure there are the appropriate number of trailing spaces in a message text line.
%.
Generates a single period in the formatted message text. This can be used to get a period at the beginning of a line without terminating the message definition.
%!
Generates a single exclamation point in the formatted message text. This can be used to specify an exclamation point immediately after an insert.


Using MC (The MC Command Line)

The message compiler has the following command-line syntax:

Syntax

MC [-v] [-w] [-s] [-d] [-h dir] [-e extension] [-r dir] filename[.mc]

Parameters

-v
Generates verbose output to stderr.
-w
Generates a warning message whenever an insert escape sequence is seen that is a superset of the type supported by the OS/2 MKMSGF utility. These are any escape sequences other than %0 and %n. This option is useful for converting MKMSGF message files to MC format.
-s
Adds an extra line to the beginning of each message that is the symbolic name associated with the message identifier.
-d
Outputs Severity and Facility constants in decimal. Sets the initial output radix for messages to decimal.
-h dirs
Specifies the target directory of the generated include file. The include-file name is the base name of the .MC file with a .H extension.
-e extension
Specifies the extension for the header file, which can be from one to three characters. The default is .H.
-r dir
Specifies the target directory of the generated Resource Compiler script (.RC file). The script file name is the base name of the .MC file with a .RC extension.
filename[.MC]
Specifies an input message file that is compiled into one or more binary resource files, one for each language specified in the message file.

The message compiler reads the message file and generates a C/C++ include file containing definitions for the symbolic names. For each LanguageId statement, the message compiler generates a binary file containing a message table resource. It also generates a single resource script file that contains the appropriate resource compiler statements to include each binary output file as a resource with the appropriate symbolic name and language type.


Sample Message Text File

The following example shows a message text file that defines messages for a resource-only DLL.

// Header

MessageIdTypedef=DWORD

SeverityNames=(Success=0x0:STATUS_SEVERITY_SUCCESS
               Informational=0x1:STATUS_SEVERITY_INFORMATIONAL
               Warning=0x2:STATUS_SEVERITY_WARNING
               Error=0x3:STATUS_SEVERITY_ERROR
              )

FacilityNames=(System=0x0:FACILITY_SYSTEM
               Runtime=0x2:FACILITY_RUNTIME
               Stubs=0x3:FACILITY_STUBS
               Io=0x4:FACILITY_IO_ERROR_CODE
              )

LanguageNames=(English=0x409:MSG00409)
LanguageNames=(Japanese=0x411:MSG00411)

// Message definitions

MessageId=0x1
Severity=Error
Facility=Runtime
SymbolicName=MSG_BAD_COMMAND
Language=English
You have chosen an incorrect command.
.
Language=Japanese
·s³‚ÈƒRƒ}ƒ"ƒh‚ª'I'ð‚³‚ê‚Ü‚µ‚½.
.

MessageId=0x2
Severity=Warning
Facility=Io
SymbolicName=MSG_BAD_PARM1
Language=English
Cannot reconnect to the server.
.
Language=Japanese
ƒT[ƒo[‚ÖÄÚ'±‚Å‚«‚Ü‚¹‚ñ.
.

MessageId=0x3
Severity=Success
Facility=System
SymbolicName=MSG_STRIKE_ANY_KEY
Language=English
Press any key to continue . . . %0
.
Language=Japanese
'±‚¯‚é‚É‚Í‰½‚©ƒL[‚ð‰Ÿ‚µ‚Ä‚‚¾‚³‚¢ . . . %0
.

MessageId=0x4
Severity=Error
Facility=System
SymbolicName=MSG_CMD_DELETE
Language=English
File %1 contains %2 which is in error
.
Language=Japanese
ƒtƒ@ƒCƒ‹ %1 '†‚ÉŠÜ‚Ü‚ê‚é %2 ‚ÍƒGƒ‰[‚Å‚·
.

MessageId=0x5
Severity=Success
Facility=System
SymbolicName=MSG_RETRYS
Language=English
There have been %1!d! retrys with %2!d!%% success%! Disconnect from%
the server and retry later.
.
Language=Japanese
%1!d! ‰ñÚ'±‚ðŽŽ‚Ý‚Ü‚µ‚½‚ª %2!d!%% ‚Ì¬Œ÷—‚Å‚µ‚½%!.
ƒT[ƒo[‚ÆØ'f‚µ‚½ŒãAÄÚ'±‚µ‚Ä‚‚¾‚³‚¢.
.

The header section defines names and language identifiers for use by the message definitions later in this file. The MessageIdTypedef, SeverityNames, FacilityNames, and LanguageNames keywords are optional.

The MessageIdTypedef keyword gives a name that is used in a type cast for each message code in the generated include file. Each message code appears in the include file with the format: #define name ((type) 0xnnnnnnnn) The default value for type is empty, and no type cast is generated. You must specify a typedef statement in the application source code to define the type. The type used in the typedef statement must be large enough to accommodate the entire 32-bit message code.

The SeverityNames keyword defines the set of names that are allowed as the value of the Severity keyword in the message definition. The set is delimited by left and right parentheses. Associated with each severity name is a number that, when shifted left by 30, gives the bit pattern to logical-OR with the Facility value and MessageId value to form the full 32-bit message code. The default value of this keyword is as follows:

SeverityNames=(
  Success=0x0
  Informational=0x1
  Warning=0x2
  Error=0x3
 )

Severity values occupy the high two bits of a 32-bit message code. Any severity value that does not fit in two bits is an error. The severity codes can be given symbolic names by following each value with :name

The FacilityNames keyword defines the set of names that are allowed as the value of the Facility keyword in the message definition. The set is delimited by left and right parentheses. Associated with each facility name is a number that, when shift it left by 16 bits, gives the bit pattern to logical-OR with the Severity value and MessageId value to form the full 32-bit message code. The default value of this keyword is as follows:

FacilityNames=(
  System=0x0FF
  Application=0xFFF
 )

Facility codes occupy the low order 12 bits of the high order 16-bits of a 32-bit message code. Any facility code that does not fit in 12 bits is an error. This allows for 4,096 facility codes. The first 256 codes are reserved for use by the system software. The facility codes can be given symbolic names by following each value with :name.

The LanguageNames keyword defines the set of names that are allowed as the value of the Language keyword in the message definition. The set is delimited by left and right parentheses. Associated with each language name is a number and a file name that are used to name the generated resource file that contains the messages for that language. The number corresponds to the language identifier to use in the resource table. The number is separated from the file name with a colon.

Any new names in the source file which don't override the built-in names are added to the list of valid languages. This allows an application to support private languages with descriptive names.

The MessageId statement marks the beginning of the message definition. A MessageID statement is required for each message, although the value is optional. If no value is specified, the value used is the previous value for the facility plus one. If the value is specified as +number then the value used is the previous value for the facility, plus the number after the plus sign. Otherwise, if a numeric value is given, that value is used. Any MessageId value that does not fit in 16 bits is an error.

The Severity and Facility statements are optional. These statements specify additional bits to OR into the final 32-bit message code. If not specified they default to the value last specified for a message definition. The initial values prior to processing the first message definition are:

Severity=Success
Facility=Application

The value associated with Severity and Facility must match one of the names given in the FacilityNames and SeverityNames statements in the header section. The SymbolicName statement allows you to associate a C/C++ symbolic constant with the final 32-bit message code.


Resource Compiler

The Microsoft® Windows® Resource Compiler (RC) is a tool used in building Win32®-based applications. This overview describes how to create a resource-definition (script) file, how to compile your application's resources, and how to add compiled resources to your application.

  • About Resource Files
  • Using RC (The RC Command Line)
  • Localizing Resources


About Resource Files

To include resources in your Win32-based application with RC, do the following:

  1. Create individual files for your cursors, icons, bitmaps, dialog boxes, and fonts. To do this, you can use the Dialog Editor, Image Editor, and Font Editor included with the Platform SDK, or equivalent developer tools.
  2. Create a resource-definition script (.RC file) that describes the resources used by your application.
  3. Compile the script with RC. For more information, see Using RC (The RC Command Line).
  4. Link the compiled resource (.RES) file into the application's executable file with your linker.

A script file is a text file with the extension .RC. The file can use single-byte, double-byte, or Unicode characters. The syntax and semantics for the RC preprocessor are similar to those of the Microsoft C/C++ compiler. However, RC supports a subset of the preprocessor directives, defines, and pragmas in a script.

The script file defines resources. For a resource that exists in a separate file, such as an icon or cursor, the script specifies the resource and the file that contains it. For some resources, such as a menu, the entire definition of the resource exists within the script.

The following topics describe the information a script file can contain:

  • Comments, which are notes to be ignored by RC.
  • Predefined macros, which take no arguments and cannot be redefined.
  • Preprocessor directives, which instruct RC to perform actions on the script before compiling it.
  • Preprocessor operators, which are used with the #define directive.
  • Pragma directives
  • Resource-definition statements, which name and describe resources.


Comments

RC supports C-style syntax for both single-line comments and block comments. Single-line comments begin with two forward slashes (//) and run to the end of the line. The following is an example of a resource statement followed by a single-line comment.

NewCursor  CURSOR  NEW.CUR  // a new cursor for the application.

Block comments begin with an opening delimiter (/*) and run to a closing delimiter (*/). Comments do not nest. The following is an example of a block comment at the beginning of a RC file.

/*
    Resources.Rc

    Contains the resource definitions for the application.
    Control identifiers are defined in Resources.H.
*/

#include "resources.h"
…


Predefined Macros

RC does not support the ANSI C predefined macros (__DATE__, __FILE__, __LINE__, __STDC__, __TIME__, __TIMESTAMP__). Therefore, you cannot include these macros in header files that you will include in your resource script.

RC does define RC_INVOKED, which enables you conditionally compile portions of your header files, depending on whether the compiler is your C compiler or the RC compiler. This is important because the RC compiler supports only a subset of the statements a C compiler would support.

To conditionally compile your code with the RC compiler, surround code that RC cannot compile with #ifndef RC_INVOKED and #endif.

The following example is taken from the SDK samples. It demonstrates how to create a header file that can be compiled conditionally.

#ifndef RC_INVOKED
#pragma message("Including CntrOutl.H from " __FILE__)
#endif


Preprocessor Directives

You can use the directives described in the following table as needed in your resource script. They instruct RC to perform actions or to assign values to names.

Directive | Description
#define | Defines a specified name by assigning it a given value.
#elif | Marks an optional clause of a conditional-compilation block.
#else | Marks the last optional clause of a conditional-compilation block.
#endif | Marks the end of a conditional-compilation block.
#if | Conditionally compiles the script if a specified expression is true.
#ifdef | Conditionally compiles the script if a specified name is defined.
#ifndef | Conditionally compiles the script if a specified name is not defined.
#include | Copies the contents of a file into the resource-definition file.
#undef | Removes the definition of the specified name.

To define symbols for your resource identifiers, use the #define directive to define them in a header file. Include this header both in the resource script and your application source code. Similarly, you define the values for resource attributes and styles by including WINDOWS.H in the resource script.

RC treats files with the .C and .H extensions in a special manner. It assumes that a file with one of these extensions does not contain resources. If a file has the .C or .H file extension, RC ignores all lines in the file except the preprocessor directives. Therefore, to include a file that contains resources in another resource script, give the file to be included an extension other than .C or .H.


#define

The #define directive assigns the given value to the specified name. All subsequent occurrences of the name are replaced by the value.

#define name value

Parameters

name
Specifies the name to be defined. This value is any combination of letters, digits, and punctuation.
value
Specifies any integer, character string, or line of text.

Example

This example assigns values to the names NONZERO and USERCLASS:

#define     NONZERO     1
#define     USERCLASS   "MyControlClass"

See Also

#ifdef, #ifndef, #undef


#elif

The #elif directive marks an optional clause of a conditional-compilation block defined by a #ifdef, #ifndef, or #if directive. The directive controls conditional compilation of the resource file by checking the specified constant expression. If the constant expression is nonzero, #elif directs the compiler to continue processing statements up to the next #endif, #else, or #elif directive and then skip to the statement after #endif. If the constant expression is zero, #elif directs the compiler to skip to the next #endif, #else, or #elif directive. You can use any number of #elif directives in a conditional block.

#elif constant-expression

Parameters

constant-expression
Specifies the expression to be checked. This value is a defined name, an integer constant, or an expression consisting of names, integers, and arithmetic and relational operators.

Example

In this example, #elif directs the compiler to process the second BITMAP statement only if the value assigned to the name Version is less than 7. The #elif directive itself is processed only if Version is greater than or equal to 3.

#if Version < 3
BITMAP 1 errbox.bmp
#elif Version < 7
BITMAP 1 userbox.bmp
#endif

See Also

#else, #endif, #if, #ifdef, #ifndef


#else

The #else directive marks an optional clause of a conditional-compilation block defined by a #ifdef, #ifndef, or #if directive. The #else directive must be the last directive before the #endif directive.

#else

Parameters

This directive has no parameters.

Example

This example compiles the second BITMAP statement only if the name DEBUG is not defined:

#ifdef DEBUG
    BITMAP 1 errbox.bmp
#else
    BITMAP 1 userbox.bmp
#endif

See Also

#elif, #endif, #if, #ifdef, #ifndef


#endif

The #endif directive marks the end of a conditional-compilation block defined by a #ifdef directive. One #endif is required for each #if, #ifdef, or #ifndef directive.

#endif

Parameters

This directive has no parameters.

See Also

#elif, #else, #if, #ifdef, #ifndef


#if

The #if directive controls conditional compilation of the resource file by checking the specified constant expression. If the constant expression is nonzero, #if directs the compiler to continue processing statements up to the next #endif, #else, or #elif directive and then skip to the statement after the #endif directive. If the constant expression is zero, #if directs the compiler to skip to the next #endif, #else, or #elif directive.

#if constant-expression

Parameters

constant-expression
Specifies the expression to be checked. This value is a defined name, an integer constant, or an expression consisting of names, integers, and arithmetic and relational operators.

Example

This example compiles the BITMAP statement only if the value assigned to the name Version is less than 3:

#if Version < 3
BITMAP 1 errbox.bmp
#endif

See Also

#elif, #else, #endif, #ifdef, #ifndef


#ifdef

The #ifdef directive controls conditional compilation of the resource file by checking the specified name. If the name has been defined by using a #define directive or by using the /d command-line option with the resource compiler, #ifdef directs the compiler to continue with the statement immediately after the #ifdef directive. If the name has not been defined, #ifdef directs the compiler to skip all statements up to the next #endif directive.

#ifdef name

Parameters

name
Specifies the name to be checked by the directive.

Example

This example compiles the BITMAP statement only if the name Debug is defined:

#ifdef Debug
BITMAP 1 errbox.bmp
#endif

See Also

#define, #endif, #if, #ifndef, #undef


#ifndef

The #ifndef directive controls conditional compilation of the resource file by checking the specified name. If the name has not been defined or if its definition has been removed by using the #undef directive, #ifndef directs the compiler to continue processing statements up to the next #endif, #else, or #elif directive and then skip to the statement after the #endif directive. If the name is defined, #ifndef directs the compiler to skip to the next #endif, #else, or #elif directive.

#ifndef name

Parameters

name
Specifies the name to be checked by the directive.

Example

This example compiles the BITMAP statement only if the name Optimize is not defined:

#ifndef Optimize
BITMAP 1 errbox.bmp
#endif

See Also

#elif, #else, #endif, #if, #ifdef, #undef


#include

The #include directive causes the resource compiler to process the file specified in the filename parameter. This file should be a header file that defines the constants used in the resource-definition file. The file can use single-byte, double-byte, or Unicode characters.

#include filename

Parameters

filename
Specifies the name of the file to be included. If the file is in the current directory, the string must be enclosed in double quotation marks; if the file is in the directory specified by the INCLUDE environment variable, the string must be enclosed in less-than and greater-than characters (<>). You must give a full path enclosed in double quotation marks (") if the file is not in the current directory or in the directory specified by the INCLUDE environment variable.

Remarks

Use the following statement in your header file to surround statements that can be compiled by a C compiler but not RC:

#ifndef RC_INVOKED

This way, you can use the same include files in your .C and .RC files.

Example

This example processes the header files Windows.H and MyDefs.H while compiling the resource-definition file:

#include <windows.h>
#include "headers\mydefs.h"

See Also

#define


#undef

The #undef directive removes the current definition of the specified name. All subsequent occurrences of the name are processed without replacement.

#undef name

Parameters

name
Specifies the name to be removed. This value is any combination of letters, digits, and punctuation.

Example

This example removes the definitions for the names nonzero and USERCLASS:

#undef     nonzero
#undef     USERCLASS

See Also

#define


Preprocessor Operators

RC supports using the standard C preprocessing operators in macro definitions. These operators are described in the following table.

Operator | Description
# | Encloses the argument in quotes.
#@ | Encloses the argument in single quotes.
## | Concatenates tokens used as arguments to form other tokens.


Pragma Directives

RC does not support the pragma directives supported by the C/C++ compiler. However, RC does support the following pragma directive for changing the code page:

#pragma code_page( [ DEFAULT | CodePageNum ] )


Resource-Definition Statements

The resource-definition statements define the resources that the resource compiler puts in the resource (.RES) file. After the .RES file is linked to the executable file, the application can load its resources at run time as needed. All resource statements associate an identifying name or number with a given resource.

The resource-definition statements can be divided into the following categories:

  • Resources
  • Controls
  • Statements

The following tables describe the resource-definition statements.

Resources

Resource | Description
ACCELERATORS | Defines menu accelerator keys.
BITMAP | Defines a bitmap by naming it and specifying the name of the file that contains it. (To use a particular bitmap, the application requests it by name.)
CURSOR | Defines a cursor or animated cursor by naming it and specifying the name of the file that contains it. (To use a particular cursor, the application requests it by name.)
DIALOG | Defines a template that an application can use to create dialog boxes.
DIALOGEX | Defines a template that an application can use to create dialog boxes.
FONT | Specifies the name of a file that contains a font.
ICON | Defines an icon or animated icon by naming it and specifying the name of the file that contains it. (To use a particular icon, the application requests it by name.)
MENU | Defines the appearance and function of a menu.
MENUEX | Defines the appearance and function of a menu.
MESSAGETABLE | Defines a message table by naming it and specifying the name of the file that contains it. The file is a binary resource file generated by the message compiler.
POPUP | Defines a menu item that can contain menu items and submenus.
RCDATA | Defines data resources. Data resources let you include binary data in the executable file.
STRINGTABLE | Defines string resources. String resources are Unicode strings that can be loaded from the executable file.
User-Defined | Defines a resource that contains application-specific data.
VERSIONINFO | Defines a version-information resource. Contains information such as the version number, intended operating system, and so on.

Controls

Control | Description
AUTO3STATE | Creates an automatic three-state check box control.
AUTOCHECKBOX | Creates an automatic check box control.
AUTORADIOBUTTON | Creates an automatic radio button control.
CHECKBOX | Creates a check box control.
COMBOBOX | Creates a combo box control.
CONTROL | Creates an application-defined control.
CTEXT | Creates a centered-text control.
DEFPUSHBUTTON | Creates a default pushbutton control.
EDITTEXT | Creates an edit control.
GROUPBOX | Creates a group box control.
ICON | Creates an icon control. This control is an icon displayed in a dialog box.
LISTBOX | Creates a list box control.
LTEXT | Creates a left-aligned text control.
PUSHBOX | Creates a push box control.
PUSHBUTTON | Creates a push button control.
RADIOBUTTON | Creates a radio button control.
RTEXT | Creates a right-aligned control.
SCROLLBAR | Creates a scroll bar control.
STATE3 | Creates a three-state check box control.

Statements

Statement | Description
CAPTION | Sets the title for a dialog box.
CHARACTERISTICS | Specifies information about a resource that can be used by tool that can read or write resource-definition files.
CLASS | Sets the class of the dialog box.
EXSTYLE | Sets the extended window style of the dialog box.
FONT | Sets the font with which the system will draw text for the dialog box.
LANGUAGE | Sets the language for all resources up to the next LANGUAGE statement or to the end of the file. When the LANGUAGE statement appears before the beginning of the body of an ACCELERATORS, DIALOG, MENU, RCDATA, or STRINGTABLE resource definition, the specified language applies only to that resource.
MENU | Sets the menu for the dialog box.
MENUITEM | Defines a menu item.
STYLE | Sets the window style for the dialog box.
VERSION | Specifies version information for a resource that can be used by tool that can read or write resource-definition files.


ACCELERATORS Resource

The ACCELERATORS resource-definition statement specifies one or more accelerators for an application. An accelerator is a keystroke defined by the application to give the user a quick way to perform a task.

The TranslateAccelerator function is used to translate accelerator messages from the application queue into WM_COMMAND or WM_SYSCOMMAND messages.

acctablename ACCELERATORS  [optional-statements]  {      event, idvalue, [type] [options]      . . .  }

Parameters

acctablename
Specifies either a unique name or a 16-bit unsigned integer value that identifies the resource.
optional-statements
Zero or more of the following statements:
Statement | Description
CHARACTERISTICS dword | User-defined information about a resource that can be used by tools that read and write resource files. For more information, see CHARACTERISTICS.
LANGUAGE language, sublanguage | Specifies the language for the resource. For more information, see LANGUAGE.
VERSION dword | User-defined version number for the resource that can be used by tools that read and write resource files. For more information, see VERSION.

event
Specifies the keystroke to be used as an accelerator. It can be any one of the following character types:
Type | Description
"char" | A single character enclosed in double quotation marks ("). The character can be preceded by a caret (^), meaning that the character is a control character.
Character | An integer value representing a character. The type parameter must be ASCII.
virtual-key character | An integer value representing a virtual key. The virtual key for alphanumeric keys can be specified by placing the uppercase letter or number in double quotation marks (for example, "9" or "C"). The type parameter must be VIRTKEY.

idvalue
Specifies a 16-bit unsigned integer value that identifies the accelerator.
type
Required only when the event parameter is a character or a virtual-key character. The type parameter specifies either ASCII or VIRTKEY; the integer value of event is interpreted accordingly. When VIRTKEY is specified and event contains a string, event must be uppercase.
options
Specifies the options that define the accelerator. This parameter can be one or more of the following values:
Option | Description
NOINVERT | Specifies that no top-level menu item is highlighted when the accelerator is used. This is useful when defining accelerators for actions such as scrolling that do not correspond to a menu item. If NOINVERT is omitted, a top-level menu item will be highlighted (if possible) when the accelerator is used.
ALT | Causes the accelerator to be activated only if the ALT key is down. Applies only to virtual keys.
SHIFT | Causes the accelerator to be activated only if the SHIFT key is down. Applies only to virtual keys
CONTROL | Defines the character as a control character (the accelerator is only activated if the CONTROL key is down). This has the same effect as using a caret (^) before the accelerator character in the event parameter. Applies only to virtual keys

Example

The following example demonstrates the use of accelerator keys:

1 ACCELERATORS
{
  "^C",  IDDCLEAR         ; control C
  "K",   IDDCLEAR         ; shift K
  "k",   IDDELLIPSE, ALT  ; alt k
  98,    IDDRECT, ASCII   ; b
  66,    IDDSTAR, ASCII   ; B (shift b)
  "g",   IDDRECT          ; g
  "G",   IDDSTAR          ; G (shift G)
  VK_F1, IDDCLEAR, VIRTKEY                ; F1
  VK_F1, IDDSTAR, CONTROL, VIRTKEY        ; control F1
  VK_F1, IDDELLIPSE, SHIFT, VIRTKEY       ; shift F1
  VK_F1, IDDRECT, ALT, VIRTKEY            ; alt F1
  VK_F2, IDDCLEAR, ALT, SHIFT, VIRTKEY    ; alt shift F2
  VK_F2, IDDSTAR, CONTROL, SHIFT, VIRTKEY ; ctrl shift F2
  VK_F2, IDDRECT, ALT, CONTROL, VIRTKEY   ; alt control F2
}

See Also

TranslateAccelerator
CHARACTERISTICS, DIALOG, LANGUAGE , MENU, RCDATA, STRINGTABLE, VERSION


AUTO3STATE Control

The AUTO3STATE resource-definition statement creates an automatic three-state check box. The control is an open box with the given text positioned to the right of the box. When chosen, the box automatically advances between three states: checked, unchecked, and disabled (grayed). The control sends a message to its parent whenever the user chooses the control.

AUTO3STATE text, id, x, y, width, height [, style [, extended-style]]

Parameters

style
Specifies styles for the control, which can be a combination of the BS_AUTO3STATE style and the following styles: WS_TABSTOP, WS_DISABLED, and WS_GROUP.

If you do not specify a style, the default style is BS_AUTO3STATE | WS_TABSTOP.

For more information on the text, id, x, y, width, height, style, and extended-style parameters, see Common Control Parameters.

See Also

AUTOCHECKBOX, CHECKBOX, CONTROL, STATE3


AUTOCHECKBOX Control

The AUTOCHECKBOX resource-definition statement creates an automatic check box control. The control is a small rectangle (check box) that has the specified text displayed next to it (typically, to the right). When the user chooses the control, the control highlights the rectangle and sends a message to its parent window.

The AUTOCHECKBOX statement can only be used in the body of a DIALOG or DIALOGEX statement.

AUTOCHECKBOX text, id, x, y, width, height [, style [, extended-style]]

Parameters

style
Specifies the styles of the control. This value can be a combination of the button class style BS_AUTOCHECKBOX and the WS_TABSTOP and WS_GROUP styles.

If you do not specify a style, the default style is BS_AUTOCHECKBOX | WS_TABSTOP.

For more information on the text, id, x, y, width, height, style, and extended-style parameters, see Common Control Parameters.

See Also

AUTO3STATE, CHECKBOX, CONTROL, STATE3


AUTORADIOBUTTON Control

The AUTORADIOBUTTON resource-definition statement creates an automatic radio button control. This control automatically performs mutual exclusion with the other AUTORADIOBUTTON controls in the same group. When the button is chosen, the application is notified with BN_CLICKED.

AUTORADIOBUTTON text, id, x, y, width, height [, style [, extended-style]]

Parameters

text
The specified text appears next to the radio button.
style
Specifies styles for the automatic radio button, which can be a combination of BUTTON-class styles and the following styles: WS_TABSTOP, WS_DISABLED, and WS_GROUP.

If you do not specify a style, the default style is BS_AUTORADIOBUTTON | WS_TABSTOP.

For more information on the text, id, x, y, width, height, style, and extended-style parameters, see Common Control Parameters.

See Also

CONTROL, RADIOBUTTON


BITMAP Resource

The BITMAP resource-definition statement specifies a bitmap that an application uses in its screen display or as an item in a menu or control.

nameID BITMAP filename

Parameters

nameID
Specifies either a unique name or a 16-bit unsigned integer value identifying the resource.
filename
Specifies the name of the file that contains the resource. The name must be a valid filename; it must be a full path if the file is not in the current working directory. The path should be a quoted string.

Example

The following example specifies two bitmap resources:

disk1   BITMAP disk.bmp
12      BITMAP diskette.bmp

See Also

LoadBitmap


CAPTION Statement

The CAPTION resource-definition statement sets the title for a dialog box. The title appears in the box's caption bar (if it has one).

The default caption is empty.

CAPTION "captiontext"

Parameters

captiontext
Specifies a character string enclosed in double quotation marks (").

Example

The following example demonstrates the use of the CAPTION statement:

CAPTION "Error!"


CHARACTERISTICS Statement

The CHARACTERISTICS resource-definition statement specifies information about a resource that can be used by tools that read and write resource-definition files. The specified DWORD value appears with the resource in the compiled .RES file. However, the value is not stored in the executable file and has no significance to the system.

The CHARACTERISTICS statement appears before the beginning of the body of an ACCELERATORS, DIALOG, MENU, RCDATA, or STRINGTABLE resource definition. The specified value applies only to that resource.

CHARACTERISTICS dword

Parameters

dword
A user-defined DWORD value.

See Also

ACCELERATORS, DIALOG, LANGUAGE, MENU, RCDATA, STRINGTABLE


CHECKBOX Control

The CHECKBOX resource-definition statement creates a check box control. The control is a small rectangle (check box) that has the specified text displayed next to it (typically, to the right). When the user selects the control, the control highlights the rectangle and sends a message to its parent window.

The CHECKBOX statement, which can only be used in a DIALOG statement, defines the text, identifier, dimensions, and attributes of the control.

CHECKBOX text, id, x, y, width, height [, style [, extended-style]]

Parameters

text
Specifies text that is displayed to the right of the control.
style
Specifies the control styles. This value can be a combination of the button class style BS_CHECKBOX and the WS_TABSTOP and WS_GROUP styles.

If you do not specify a style, the default style is BS_CHECKBOX | WS_TABSTOP.

For more information on the text, id, x, y, width, height, style, and extended-style parameters, see Common Control Parameters.

Example

This example creates a check-box control that is labeled Italic:

CHECKBOX "Italic", 3, 10, 10, 40, 10

See Also

AUTOCHECKBOX, AUTO3STATE, GetDialogBaseUnits, STATE3


CLASS Statement

The CLASS resource-definition statement sets the class of the dialog box.

The CLASS statement appears in the optional section before a DIALOG statement's main. If no class is given, the standard dialog class is used.

CLASS class

Parameters

class
Specifies a 16-bit unsigned integer or a string, enclosed in double quotation marks ("), that identifies the class of the dialog box. If the window procedure for the class does not process a message sent to it, it must call the DefDlgProc function to ensure that all messages are handled properly for the dialog box. A private class can use DefDlgProc as the default window procedure. The class must be registered with the cbWndExtra member of the WNDCLASS structure set to DLGWINDOWEXTRA.

Remarks

The CLASS statement should only be used with special cases, because it overrides the normal processing of a dialog box. The CLASS statement converts a dialog box to a window of the specified class; depending on the class, this could give undesirable results. Do not use the redefined control-class names with this statement.

Example

The following example demonstrates the use of the CLASS statement:

CLASS "myclass"

See Also

DefDlgProc, DIALOG


COMBOBOX Control

The COMBOBOX resource-definition statement creates a combination box control (a combo box). A combo box consists of either a static text box or an edit box combined with a list box. The list box can be displayed at all times or pulled down by the user. If the combo box contains a static text box, the text box always displays the selection (if any) in the list box portion of the combo box. If it uses an edit box, the user can type in the desired selection; the list box highlights the first item (if any) that matches what the user has entered in the edit box. The user can then select the item highlighted in the list box to complete the choice. In addition, the combo box can be owner-drawn and of fixed or variable height.

COMBOBOX id, x, y, width, height [, style [, extended-style]]

Parameters

style
Specifies the control styles. This value can be a combination of the COMBOBOX class styles and any of the following styles: WS_TABSTOP, WS_GROUP, WS_VSCROLL, and WS_DISABLED.

If you do not specify a style, the default style is CBS_SIMPLE | WS_TABSTOP.

For more information on the text, id, x, y, width, height, style, and extended-style parameters, see Common Control Parameters.

Example

This example creates a combo-box control with a vertical scroll bar:

COMBOBOX 777, 10, 10, 50, 54, CBS_SIMPLE | WS_VSCROLL | WS_TABSTOP


CONTROL Control

The CONTROL resource-definition statement creates a user-defined control.

CONTROL text, id, class, style, x, y, width, height [, extended-style]

Parameters

class
Specifies a redefined name, character string, or a 16-bit unsigned integer value that defines the class. This can be any one of the control classes; for a list of the control classes, see the first list following this description. If the value is a redefined name supplied by the application, it must be a string enclosed in double quotation marks (").
style
Specifies a redefined name or integer value that specifies the style of the given control. The exact meaning of style depends on the class value. The sections following this description show the control classes and corresponding styles.

For more information on the text, id, x, y, width, height, style, and extended-style parameters, see Common Control Parameters.

The six possible control classes are described in the following sections.

The Button Control Class

A button control is a small rectangular child window that the user can turn on or off by clicking it with the mouse. Button controls can be used alone or in groups, and can either be labeled or appear without text. Button controls typically change appearance when the user clicks them.

The button styles are described in the following topic: Button Styles.

The Combo Box Control Class

Combo box controls consist of a selection field similar to an edit control plus a list box. The list box may be displayed at all times or may be dropped down when the user selects a "pop box" next to the selection field.

Depending on the style of the combo box, the user can or cannot edit the contents of the selection field. If the list box is visible, typing characters into the selection box will cause the first entry that matches the characters typed to be highlighted. Conversely, selecting an item in the list box displays the selected text in the selection field. The combo box control styles are described in the following topic: Combo Box Styles.

The Edit Control Class

An edit control is a rectangular child window in which the user can enter text from the keyboard. The user selects the control, and gives it the input focus, by clicking the mouse inside it or pressing the TAB key. The user can enter text when the control displays a flashing insertion point. The mouse can be used to move the cursor and select characters to be replaced, or to position the cursor for inserting characters. The BACKSPACE key can be used to delete characters.

Edit controls use the fixed-pitch font and display Unicode characters. They expand tab characters into as many space characters as are required to move the cursor to the next tab stop. Tab stops are assumed to be at every eighth character position.

For a list of edit control styles, see Edit Control Styles.

The List Box Control Class

List box controls consist of a list of character strings. The control is used whenever an application needs to present a list of names, such as filenames, that the user can view and select. The user can select a string by pointing to the string with the mouse and clicking a mouse button. When a string is selected, it is highlighted and a notification message is passed to the parent window. A scroll bar can be used with a list box control to scroll lists that are too long or too wide for the control window.

The list box control styles are described in the following topic: List Box Styles.

The Scroll-Bar Control Class

A scroll-bar control is a rectangle that contains a scroll thumb and has direction arrows at both ends. The scroll bar sends a notification message to its parent whenever the user clicks the mouse in the control. The parent is responsible for updating the thumb position, if necessary. Scroll-bar controls have the same appearance and function as the scroll bars used in ordinary windows. But unlike scroll bars, scroll-bar controls can be positioned anywhere within a window and used whenever needed to provide scrolling input for a window.

The scroll bar styles are described in the following topic: Scroll Bar Control Styles.

The Static Control Class

Static controls are simple text fields, boxes, and rectangles that can be used to label, box, or separate other controls. Static controls take no input and provide no output.

The static control styles are described in the following topic: Static Control Styles.


CTEXT Control

The CTEXT resource-definition statement creates a centered-text control. The control is a simple rectangle displaying the given text centered in the rectangle. The text is formatted before it is displayed. Words that would extend past the end of a line are automatically wrapped to the beginning of the next line. Words that are longer than the width of the control are truncated.

The CTEXT statement, which you can use only in a DIALOG statement, defines the text, identifier, dimensions, and attributes of the control.

CTEXT text, id, x, y, width, height [, style [, extended-style]]

Parameters

text
Specifies text that is centered in the rectangular area of the control.
style
Specifies the control styles. This value can be any combination of the following styles: SS_CENTER, WS_TABSTOP, and WS_GROUP.

If you do not specify a style, the default style is SS_CENTER | WS_GROUP.

For more information on the text, id, x, y, width, height, style, and extended-style parameters, see Common Control Parameters.

Example

This example creates a centered-text control that is labeled Filename:

CTEXT "Filename", 101, 10, 10, 100, 100

See Also

CONTROL, DIALOG, LTEXT, RTEXT


CURSOR Resource

The CURSOR resource-definition statement specifies a bitmap that defines the shape of the cursor on the display screen or an animated cursor.

nameID CURSOR filename

Parameters

nameID
Specifies either a unique name or a 16-bit unsigned integer identifying the resource.
filename
Specifies the name of the file that contains the resource. The name must be a valid filename; it must be a full path if the file is not in the current working directory. The path should be a quoted string.

Remarks

Icon and cursor resources can contain more than one image.

Example

The following example specifies two cursor resources; one by name (cursor1) and the other by number (2):

cursor1 CURSOR bullseye.cur
2       CURSOR "d:\\cursor\\arrow.cur"


DEFPUSHBUTTON Control

The DEFPUSHBUTTON resource-definition statement creates a default push-button control. The control is a small rectangle with a bold outline that represents the default response for the user. The given text is displayed inside the button. The control highlights the button in the usual way when the user clicks the mouse in it and sends a message to its parent window.

DEFPUSHBUTTON text, id, x, y, width, height [, style [, extended-style]]

Parameters

text
Specifies text that is centered in the rectangular area of the control.
style
Specifies the control styles. This value can be a combination of the following styles: BS_DEFPUSHBUTTON, WS_TABSTOP, WS_GROUP, and WS_DISABLED.

If you do not specify a style, the default style is BS_DEFPUSHBUTTON | WS_TABSTOP.

For more information on the text, id, x, y, width, height, style, and extended-style parameters, see Common Control Parameters.

Example

This example creates a default push-button control that is labeled Cancel:

DEFPUSHBUTTON "Cancel", 101, 10, 10, 24, 50

See Also

PUSHBUTTON, RADIOBUTTON


DIALOG Resource

The DIALOG resource-definition statement specifies a window that an application can use to create dialog boxes. The statement defines the position and dimensions of the dialog box on the screen as well as the dialog box style.

Note: DIALOG is an obsolete resource ID. New applications should use DIALOGEX.

nameID DIALOG x, y, width, height  [optional-statements]  {      control-statement      . . .  }

Parameters

nameID
Identifies the dialog box. This is either a unique name or a unique 16-bit unsigned integer value in the range 1 to 65,535.
option-statements
Specifies options for the dialog box. This can be zero or more of the following statements:
Statement | Description
CAPTION "text" | Specifies the caption of the dialog box if it has a title bar. For more information, see CAPTION.
CHARACTERISTICS
dword 		Specifies a user-defined DWORD value for use by resource tools. This value is not used by the system. For more information, see CHARACTERISTICS.
CLASS class | Specifies a 16-bit unsigned integer or a string, enclosed in double quotation marks ("), that identifies the class of the dialog box. For more information, see CLASS.
EXSTYLE=extended-styles | Specifies the extended window style of the dialog box. For more information, see EXSTYLE.
FONT pointsize, typeface | Specifies the point size and typeface for the font. For more information, see FONT.
LANGUAGE
language,sublanguage 		Specifies the language of the dialog box. For more information, see LANGUAGE.
MENU menuname | Specifies the menu to use. This value is either the name of the menu or its integer identifier.
STYLE styles | Specifies the styles of the dialog box. For more information, see STYLE.
VERSION dword | Specifies a user-defined DWORD value. This statement is intended for use by additional resource tools and is not used by the system. For more information, see VERSION.

For more information on the x, y, width, and height parameters, see Common Control Parameters.

Remarks

The GetDialogBaseUnits function returns the dialog base units in pixels. The exact meaning of the coordinates depends on the style defined by the STYLE option statement. For child-style dialog boxes, the coordinates are relative to the origin of the parent window, unless the dialog box has the style DS_ABSALIGN; in that case, the coordinates are relative to the origin of the display screen.

Do not use the WS_CHILD style with a modal dialog box. The DialogBox function always disables the parent/owner of the newly created dialog box. When a parent window is disabled, its child windows are implicitly disabled. Since the parent window of the child-style dialog box is disabled, the child-style dialog box is too.

If a dialog box has the DS_ABSALIGN style, the dialog coordinates for its upper-left corner are relative to the screen origin instead of to the upper-left corner of the parent window. You would typically use this style when you wanted the dialog box to start in a specific part of the display no matter where the parent window may be on the screen.

The name DIALOG can also be used as the class-name parameter to the CreateWindow function to create a window with dialog-box attributes.

Example

The following demonstrates the usage of the DIALOG statement:

#include <windows.h>

ErrorDialog DIALOG  10, 10, 300, 110
STYLE WS_POPUP | WS_BORDER
CAPTION "Error!"
{
    CTEXT "Select One:", 1, 10, 10, 280, 12
    PUSHBUTTON "&Retry", 2, 75, 30, 60, 12
    PUSHBUTTON "&Abort", 3, 75, 50, 60, 12
    PUSHBUTTON "&Ignore", 4, 75, 80, 60, 12
}

See Also

CONTROL, CreateDialog, CreateWindow, DialogBox, DIALOGEX, GetDialogBaseUnits, ACCELERATORS, CHARACTERISTICS, LANGUAGE, MENU, RCDATA, STRINGTABLE, VERSION


DIALOGEX Resource

The DIALOGEX resource-definition statement is an extension of the DIALOG resource-definition statement. In addition to the functionality offered by DIALOG, DIALOGEX allows for the following:

  • Help IDs on the dialog itself as well as on controls within the dialog.
  • Use of the EXSTYLE statement for the dialog itself as well as on controls within the dialog.
  • Font weight and italic settings for the font to be used in the dialog.
  • Control-specific data for controls within the dialog.
  • Use of the BEDIT, IEDIT, and HEDIT predefined system class names.

Note DIALOG is an obsolete resource ID. New applications should use DIALOGEX.

nameID DIALOGEX x, y, width, height [ , helpID]]  [[ optional-statements]]  {       control-statements  }

Parameters

nameID
Identifies the dialog box. This is either a unique name or a unique 16-bit unsigned integer value in the range 1 to 65,535.
x
Specifies the location on the screen of the left side of the dialog, in dialog units.
y
Specifies the location on the screen of the top of the dialog, in dialog units.
width
Specifies the width of the dialog, in dialog units.
height
Specifies the height of the dialog, in dialog units.
helpID
Specifies a numeric expression indicating the ID used to identify the dialog during WM_HELP processing.
optional-statements
Specifies options for the dialog box. This can be zero or more of the following statements:
Statement | Description
CAPTION "text" | Specifies the caption of the dialog box if it has a title bar. For more information, see CAPTION.
CHARACTERISTICS
dword 		Specifies a user-defined DWORD value for use by resource tools. This value is not used by the system. For more information, see CHARACTERISTICS.
CLASS class | Specifies a 16-bit unsigned integer or a string, enclosed in double quotation marks ("), that identifies the class of the dialog box. For more information, see CLASS.
EXSTYLE=extended-styles | Specifies the extended window style of the dialog box. For more information, see EXSTYLE.
FONT pointsize, typeface,
weight, italic, charset 		Specifies the point size and typeface for the font. For weight, use the FW_* values defined in WINGDI.H. For italic, specify TRUE to use an italic font, FALSE otherwise. For charset, use the value defined in the charset member of the LOGFONT structure. To get the definitive font for a dialog box, an application should specify charset along with other font properties.

For more information, see FONT.

LANGUAGE
language,sublanguage 		Specifies the language of the dialog box. For more information, see LANGUAGE.
MENU menuname | Specifies the menu to use. This value is either the name of the menu or its integer identifier. For more information, see MENU.
STYLE styles | Specifies the styles of the dialog box. For more information, see STYLE.
VERSION dword | Specifies a user-defined DWORD value. This statement is intended for use by additional resource tools and is not used by the system. For more information, see VERSION.

control-statements
The body of the DIALOGEX resource is made up of any number of control statements. There are four families of control statements: generic, static, button, and edit. For more information, see Remarks.

Remarks

The valid operations that may be contained in any of the numeric expressions in the statements of DIALOGEX are as follows:

  • Add ('+')
  • Subtract ('-')
  • Unary minus ('-')
  • Unary NOT ('~')
  • AND ('&')
  • OR ('|')

The body of the resource is made up of generic, static, button, and edit control statements. While each of these families of statements uses a different syntax for defining specific features of its controls, they all share a common syntax for defining the position, size, extended styles, help identification number, and control-specific data. For more information, see Common Control Parameters.

Generic Control Statements

CONTROL controlText, id, className, style

Parameters

controlText
Specifies the window text for the control. For more information, see Common Control Parameters.
id
Specifies the control identifier. For more information, see Common Control Parameters.
className
Specifies the name of the class. This may be either a string enclosed in double quotation marks (") or one of the following predefined system classes: BUTTON, STATIC, EDIT, LISTBOX, SCROLLBAR, or COMBOBOX.
style
Specifies the window styles (explicit WS_*, BS_*, SS_*, ES_*, LBS_*, SBS_*, and CBS_* style values defined in WINUSER.H can be used by adding an include to the RC file: #include "winuser.h")

Static Control Statements

staticClass controlText, id

Parameters

staticClass
Specify LTEXT, RTEXT, or CTEXT.
controlText
Specifies the window text for the control. For more information, see Common Control Parameters.
id
Specifies the control identifier. For more information, see Common Control Parameters.

Button Control Statements

buttonClass controlText, id

Parameters

buttonClass
Specify AUTO3STATE, AUTOCHECKBOX, AUTORADIOBUTTON, CHECKBOX, PUSHBOX, PUSHBUTTON, RADIOBUTTON, STATE3, or USERBUTTON.
controlText
Specifies the window text for the control. For more information, see Common Control Parameters.
id
Specifies the control identifier. For more information, see Common Control Parameters.

Edit Control Statements

editClass id

Parameters

editClass
Specify EDITTEXT, BEDIT, HEDIT, or IEDIT.
id
Specifies the control identifier. For more information, see Common Control Parameters.

See Also

CONTROL, CreateDialog, CreateWindow, DialogBox, DIALOGEX, GetDialogBaseUnits, ACCELERATORS, CHARACTERISTICS, LANGUAGE, LOGFONT , MENU, RCDATA, STRINGTABLE, VERSION


EDITTEXT Control

The EDITTEXT resource-definition statement creates an edit control belonging to the EDIT class. It creates a rectangular region in which the user can type and edit text. The control displays a cursor when the user clicks the mouse in it. The user can then use the keyboard to enter text or edit the existing text. Editing keys include the BACKSPACE and DELETE keys. The user can also use the mouse to select characters to be deleted or to select the place to insert new characters.

EDITTEXT id, x, y, width, height [[, style [[, extended-style]]]]

Parameters

style
Specifies the control styles. This value can be a combination of the edit class styles and the following styles: WS_TABSTOP, WS_GROUP, WS_VSCROLL, WS_HSCROLL, and WS_DISABLED.

If you do not specify a style, the default style is ES_LEFT | WS_BORDER | WS_TABSTOP.

For more information on the text, id, x, y, width, height, style, and extended-style parameters, see Common Control Parameters.

Example

The following example demonstrates the use of the EDITTEXT statement:

EDITTEXT  3, 10, 10, 100, 10


EXSTYLE Statement

The EXSTYLE resource-definition statement sets extended window styles for a dialog box. In a resource definition, the EXSTYLE statement is placed with the optional statements before the beginning of the body of the resource definition.

EXSTYLE extended-style

Parameters

extended-style
The extended window style for the dialog box or control. For a list of extended window styles, see the CreateWindowEx function.

Remarks

For controls, extended styles are specified after the style option in the control resource-definition statement. For more information, see the resource-definition statement for the individual control.

See also

ACCELERATORS, CONTROL, DIALOG, MENU, POPUP, RCDATA, STRINGTABLE, User-Defined Resource


FONT Resource

The FONT resource-definition statement specifies a file that contains a font.

nameID FONT filename

Parameters

nameID
Specifies a unique 16-bit unsigned integer value identifying the resource.
filename
Specifies the name of the file that contains the resource. The name must be a valid filename; it must be a full path if the file is not in the current working directory. The path should be a quoted string.

Example

The following example specifies a single font resource:

5 FONT  CMROMAN.FNT


FONT Statement

The FONT resource-definition statement sets the font with which the system will draw text in the dialog box. The font must have been previously loaded, either from the WIN.INI file or by calling the LoadResource function.

FONT pointsize, "typeface"

Parameters

pointsize
Specifies the size, in points, of the font.
typeface
Specifies the name of the typeface. This name must be identical to the name defined in the [FONTS] section of WIN.INI. This parameter must be enclosed in quotes (").

Example

The following example demonstrates the use of the FONT statement:

FONT 12, "MS Shell Dlg"

See Also

DIALOG, LoadResource


GROUPBOX Control

The GROUPBOX resource-definition statement creates a group box control. The control is a rectangle that groups other controls together. The controls are grouped by drawing a border around them and displaying the given text in the upper-left corner.

The GROUPBOX statement, which you can use only in a DIALOG statement, defines the text, identifier, dimensions, and attributes of a control window.

When the style contains WS_TABSTOP or the text specifies an accelerator, tabbing or pressing the accelerator key moves the focus to the first control within the group.

GROUPBOX text, id, x, y, width, height [[, style [[, extended-style]]]]

Parameters

style
Specifies the control styles. This value can be a combination of the button class style BS_GROUPBOX and the WS_TABSTOP and WS_DISABLED styles.

If you do not specify a style, the default style is BS_GROUPBOX.

For more information on the text, id, x, y, width, height, style, and extended-style parameters, see Common Control Parameters.

Example

This example creates a group-box control that is labeled Options:

GROUPBOX "Options", 101, 10, 10, 100, 100

See Also

DIALOG


ICON Resource

The ICON resource-definition statement specifies a bitmap that defines the shape of the icon to be used for a given application or an animated icon.

nameID ICON filename

Parameters

nameID
Specifies either a unique name or a 16-bit unsigned integer value identifying the resource.
filename
Specifies the name of the file that contains the resource. The name must be a valid filename; it must be a full path if the file is not in the current working directory. The path should be a quoted string.

Remarks

Icon and cursor resources can contain more than one image.

Example

The following example specifies two icon resources:

desk1   ICON desk.ico
11      ICON custom.ico


ICON Control

The ICON resource-definition statement creates an icon control. This control is an icon displayed in a dialog box.

The ICON control statement, which you can use only in a DIALOG statement, defines the icon-resource identifier, icon-control identifier, position, and attributes of a control.

ICON text, id, x, y, [[width, height, style [[, extended-style]]]]

Parameters

text
Specifies the name of an icon (not a filename) defined elsewhere in the resource file.
width
This value is ignored and should be set to zero.
height
This value is ignored and should be set to zero.
style
Specifies the control style. This parameter is optional. The only value that can be specified is the SS_ICON style. This is the default style whether this parameter is specified or not.

For more information on the text, id, x, y, width, height, style, and extended-style parameters, see Common Control Parameters.

Example

This example creates an icon control whose icon identifier is 901 and whose name is myicon:

ICON "myicon" 901, 30, 30

See Also

DIALOG, ICON


LANGUAGE Statement

The LANGUAGE resource-definition statement specifies the language for all resources up to the next LANGUAGE statement or to the end of the file.

When the LANGUAGE statement appears before the beginning of the body of an ACCELERATORS, DIALOG, MENU, RCDATA, or STRINGTABLE resource definition, the specified language applies only to that resource.

LANGUAGE language, sublanguage

Parameters

language
Language identifier. Must be one of the constants described in Primary Language Identifiers.
sublanguage
Sublanguage identifier. Must be one of the constants described in Secondary Language Identifiers.

See Also

ACCELERATORS, CHARACTERISTICS, DIALOG, MENU, RCDATA, STRINGTABLE, VERSION


LISTBOX Control

The LISTBOX resource-definition statement creates commonly used controls for a dialog box or window. The control is a rectangle containing a list of strings (such as filenames) from which the user can select.

The LISTBOX statement, which can only be used in a DIALOG or WINDOW statement, defines the identifier, dimensions, and attributes of a control window.

LISTBOX id, x, y, width, height [[, style [[, extended-style]]]]

Parameters

style
Specifies the control styles. This value can be a combination of the list-box class styles and any of the following styles: WS_BORDER and WS_VSCROLL.

If you do not specify a style, the default style is LBS_NOTIFY | WS_BORDER.

For more information on the id, x, y, width, height, style, and extended-style parameters, see Common Control Parameters.

Example

This example creates a list-box control whose identifier is 101:

LISTBOX 101, 10, 10, 100, 100

See Also

COMBOBOX, DIALOG


LTEXT Control

The LTEXT resource-definition statement creates a left-aligned text control. The control is a simple rectangle displaying the given text left-aligned in the rectangle. The text is formatted before it is displayed. Words that would extend past the end of a line are automatically wrapped to the beginning of the next line. Words that are longer than the width of the control are truncated.

The LTEXT statement, which can be used only in a DIALOG statement, defines the text, identifier, dimensions, and attributes of the control.

LTEXT text, id, x, y, width, height [[, style [[, extended-style]]]]

Parameters

style
Specifies the control styles. This value can be any combination of the BS_RADIOBUTTON style and the following styles: SS_LEFT, WS_TABSTOP, and WS_GROUP.

If you do not specify a style, the default style is SS_LEFT | WS_GROUP.

For more information on the text, id, x, y, width, height, style, and extended-style parameters, see Common Control Parameters.

Example

This example creates a left-aligned text control that is labeled Filename:

LTEXT "Filename", 101, 10, 10, 100, 100

See Also

CONTROL, CTEXT, DIALOG, RTEXT


MENU Resource

The MENU resource-definition statement specifies the contents of a menu resource. A menu resource is a collection of information that defines the appearance and function of an application menu. A menu is a special input tool that lets a user select commands and open submenus from a list of menu items.

menuID MENU  [[optional-statements]]  {      item-definitions      . . .  }

Parameters

menuID
A number that identifies the menu. This value is either a unique string or a unique 16-bit unsigned integer value in the range of 1 to 65,535.
optional-statements
This parameter can be zero of more of the following statements:
Statement | Description
CHARACTERISTICS dword | User-defined information about a resource that can be used by tools that read and write resource files. For more information, see CHARACTERISTICS.
LANGUAGE language, sublanguage | Specifies the language for the resource. For more information, see LANGUAGE.
VERSION dword | User-defined version number for the resource that can be used by tools that read and write resource files. For more information, see VERSION.

Example

Following is an example of a complete MENU statement:

sample MENU
{
     MENUITEM "&Soup", 100
     MENUITEM "S&alad", 101
     POPUP "&Entree"
     {
          MENUITEM "&Fish", 200
          MENUITEM "&Chicken", 201, CHECKED
          POPUP "&Beef"
          {
               MENUITEM "&Steak", 301
               MENUITEM "&Prime Rib", 302
          }
     }
     MENUITEM "&Dessert", 103
}

See Also

MENUEX, MENUITEM, POPUP, ACCELERATORS, CHARACTERISTICS, DIALOG, LANGUAGE, RCDATA, STRINGTABLE, VERSION


MENU Statement

The MENU resource-definition statement sets the menu for a dialog box. If no statement is given, the dialog box has no menu.

MENU menuname

Parameters

menuname
Specifies the menu to use. This value is either the name of the menu or the integer identifier of the menu.

Example

The following example demonstrates the use of the MENU dialog statement:

MENU errmenu


MENUEX Resource

The MENUEX resource-definition statement is an extension of the MENU resource-definition statement. In addition to the functionality offered by MENU, MENUEX allows for the following:

  • Help identifiers on menus.
  • Identifiers on menus.
  • Use of the MFT_* type flags and MFS_* state flags. For more information on these flags, see the MENUITEMINFO structure.
menuID MENUEX{    [{[MENUITEM itemText [,[id][, [type][, state]]]] |   [POPUP itemText [,[id][, [type][, [state][, helpID]]]]      {          popupBody      }
    } ...]}

Parameters

MENUITEM statement
Defines a menu item.
itemText
A string containing the text for the menu item. For more information, see MENUITEM.
id
A numeric expression indicating the identifier of the menu item.
type
A numeric expression indicating the type of the menu item To use the predefined MFT_* type values, include the following statement in your .RC file:
#include "winuser.h"
state
A numeric expression indicating the state of the menu item To use the predefined MFS_* state values, include the following statement in your .RC file:
#include "winuser.h"
POPUP statement
Defines a menu item that has a submenu associated with it.
itemText
A string containing the text for the menu item.
id
A numeric expression indicating the identifier of the menu item.
type
A numeric expression indicating the type of the menu item To use the predefined MFT_* type values, include the following statement in your .RC file:
#include "winuser.h"
state
A numeric expression indicating the state of the menu item To use the predefined MFS_* state values, include the following statement in your .RC file:
#include "winuser.h"
helpID
A numeric expression indicating the identifier used to identify the menu during WM_HELP processing.
popupBody
Contains any combination of the MENUITEM and POPUP statements.

Remarks

The valid arithmetic and Boolean operations that can be contained in any of the numeric expressions in the statements of MENUEX are as follows:

  • Add ('+')
  • Subtract ('-')
  • Unary minus ('-')
  • Unary NOT ('~')
  • AND ('&')
  • OR ('|')

See Also

MENU, MENUITEM, POPUP, ACCELERATORS, CHARACTERISTICS, DIALOG, LANGUAGE, RCDATA, STRINGTABLE, VERSION


MENUITEM Statement

The MENUITEM resource-definition statement creates a menu item.

MENUITEM text, result, [[optionlist]]  MENUITEM SEPARATOR

Parameters

text
A string that indicates the name of the menu item.

The string can contain the escape characters \t and \a. The \t character inserts a tab in the string and is used to align text in columns. Tab characters should be used only in menus, not in menu bars. (For information on menus, see POPUP Resource.) The \a character aligns all text that follows it flush right to the menu bar or pop-up menu.

result
A number that specifies the result generated when the user selects the menu item. This parameter takes an integer value. Menu-item results are always integers; when the user clicks the menu-item name, the result is sent to the window that owns the menu.
optionlist
This parameter specifies the appearance of the menu item. This optional parameter takes one or more redefined menu options, separated by commas or spaces. The menu options are as follows:
Option | Description
CHECKED | Menu item has a check mark next to it.
GRAYED | Menu item is initially inactive and appears on the menu in gray or a lightened shade of the menu-text color. This option cannot be used with the INACTIVE option.
HELP | Identifies a help item.
INACTIVE | Menu item is displayed but it cannot be selected. This option cannot be used with the GRAYED option.
MENUBARBREAK | Same as MENUBREAK except that for pop-up menus, it separates the new column from the old column with a vertical line.
MENUBREAK | Places the menu item on a new line for static menu-bar items. For menus, it places the menu item in a new column with no dividing line between the columns.

SEPARATOR
The MENUITEM SEPARATOR form of the MENUITEM statement creates an inactive menu item that serves as a dividing bar between two active menu items on a menu.

Example

The following example demonstrates the use of the MENUITEM and MENUITEM SEPARATOR statements:

MENUITEM "&Roman", 206, CHECKED, GRAYED
MENUITEM SEPARATOR
MENUITEM "&Blackletter", 301

See Also

MENU, POPUP


MESSAGETABLE Resource

The MESSAGETABLE resource-definition statement defines the ID and file of an application's message table resource. Message tables are special string resources used in event logging and with the FormatMessage function. The file contains a binary message table generated by the message compiler, MC.EXE.

The message compiler also generates a resource script file that contains the MESSAGETABLE statements you need to include the message table resources in the compiled resource file. Use the #include directive to include this resource script into your main resource script.

nameID MESSAGETABLE filename

Parameters

nameID
Specifies either a unique name or a 16-bit unsigned integer value identifying the resource.
filename
Specifies the name of the file that contains the resource. The name must be a valid filename; it must be a full path if the file is not in the current working directory. The path should be a quoted string.

See Also

Message Compiler, STRINGTABLE


POPUP Resource

The POPUP resource-definition statement creates a menu item that can contain menu items and submenus.

POPUP text, [[optionlist]]{     item-definitions    .    .    .}

Parameters

text
A string that contains the name of the menu. This string must be enclosed in double quotation marks (").
optionlist
This parameter specifies redefined menu options that specify the appearance of the menu item. This optional parameter can be one or more of the following.
Option | Description
CHECKED | Menu item has a check mark next to it. This option is not valid for a top-level menu.
GRAYED | Menu item is initially inactive and appears on the menu in gray or a lightened shade of the menu-text color. This option cannot be used with the INACTIVE option.
HELP | Identifies a help item.
INACTIVE | Menu item is displayed but it cannot be selected. This option cannot be used with the GRAYED option.
MENUBARBREAK | Same as MENUBREAK except that for pop-up menus, it separates the new column from the old column with a vertical line.
MENUBREAK | Places the menu item on a new line for static menu-bar items. For menus, it places the menu item in a new column with no dividing line between the columns.

Example

The following example demonstrates the use of the POPUP statement:

chem MENU
{
    POPUP "&Elements"
    {
         MENUITEM "&Oxygen", 200
         MENUITEM "&Carbon", 201, CHECKED
         MENUITEM "&Hydrogen", 202
         MENUITEM SEPARATOR
         MENUITEM "&Sulfur", 203
         MENUITEM "Ch&lorine", 204
    }
    POPUP "&Compounds"
    {
         POPUP "&Sugars"
         {
            MENUITEM "&Glucose", 301
            MENUITEM "&Sucrose", 302, CHECKED
            MENUITEM "&Lactose", 303, MENUBREAK
            MENUITEM "&Fructose", 304
         }
         POPUP "&Acids"
         {
              "&Hydrochloric", 401
              "&Sulfuric", 402
         }
    }
}

See Also

MENU, MENUITEM


PUSHBOX Control

The PUSHBOX resource-definition statement creates a push-box control, which is identical to a PUSHBUTTON, except that it does not display a button face or frame; only the text appears.

PUSHBOX text, id, x, y, width, height [[, style [[, extended-style]]]]

Parameters

style
Specifies styles for the pushbox, which can be a combination of the BS_PUSHBOX style and the following styles: WS_TABSTOP, WS_DISABLED, and WS_GROUP.

If you do not specify a style, the default style is BS_PUSHBOX | WS_TABSTOP.

For more information on the text, id, x, y, width, height, style, and extended-style parameters, see Common Control Parameters.

See Also

PUSHBUTTON


PUSHBUTTON Control

The PUSHBUTTON resource-definition statement creates a push-button control. The control is a round-cornered rectangle containing the given text. The text is centered in the control. The control sends a message to its parent whenever the user chooses the control.

PUSHBUTTON text, id, x, y, width, height [[, style [[, extended-style]]]]

Parameters

style
Specifies styles for the pushbutton, which can be a combination of the BS_PUSHBUTTON style and the following styles: WS_TABSTOP, WS_DISABLED, and WS_GROUP.

If you do not specify a style, the default style is BS_PUSHBUTTON | WS_TABSTOP.

For more information on the text, id, x, y, width, height, style, and extended-style parameters, see Common Control Parameters.

Example

The following example demonstrates the use of the PUSHBUTTON statement:

PUSHBUTTON "ON", 7, 10, 10, 20, 10

See Also

GetDialogBaseUnits


RADIOBUTTON Control

The RADIOBUTTON resource-definition statement creates a radio-button control. The control is a small circle that has the given text displayed next to it, typically to its right. The control highlights the circle and sends a message to its parent window when the user selects the button. The control removes the highlight and sends a message when the button is next selected.

RADIOBUTTON text, id, x, y, width, height [[, style [[, extended-style]]]]

Parameters

style
Specifies styles for the radio button, which can be a combination of BUTTON-class styles and the following styles: WS_TABSTOP, WS_DISABLED, and WS_GROUP.

If you do not specify a style, the default style is BS_RADIOBUTTON | WS_TABSTOP.

For more information on the text, id, x, y, width, height, style, and extended-style parameters, see Common Control Parameters.

Example

The following example demonstrates the use of the RADIOBUTTON statement:

RADIOBUTTON "Italic", 100, 10, 10, 40, 10

See Also

GetDialogBaseUnits


RCDATA Resource

The RCDATA resource-definition statement specifies a raw data resource for an application. Raw data resources permit the inclusion of binary data directly in the executable file.

nameID RCDATA  [[optional-statements]]  {       raw-data      . . .  }

Parameters

nameID
Specifies either a unique name or a 16-bit unsigned integer value that identifies the resource.
optional-statements
This parameter can be zero or more of the following statements.
Statement | Description
CHARACTERISTICS dword | User-defined information about a resource that can be used by tools that read and write resource files. For more information, see CHARACTERISTICS.
LANGUAGE language, sublanguage | Specifies the language for the resource. For more information, see LANGUAGE.
VERSION dword | User-defined version number for the resource that can be used by tools that read and write resource files. For more information, see VERSION.

raw-data
Specifies raw data consisting of one or more integers or strings of characters. Integers can be specified in decimal, octal, or hexadecimal format. To be compatible with 16-bit Windows, integers are stored as WORD values. You can store an integer as a DWORD value by qualifying the integer with the L suffix.

Strings are enclosed in quotation marks. RC does not automatically append a terminating null character to a string. Each string is a sequence of the specified ANSI characters, unless you qualify it as a wide-character string with the L prefix.

The block of data begins on a DWORD boundary and RC performs no padding or alignment of data within the raw-data block. It is your responsibility to ensure the proper alignment of data within the block.

Example

The following example demonstrates the use of the RCDATA statement:

resname RCDATA
{
   "Here is an ANSI string\0",    // explicitly null-terminated
   L"Here is a Unicode string\0", // explicitly null-terminated
   1024,                          // integer, stored as WORD
   7L,                            // integer, stored as DWORD
   0x029a,                        // hex integer
   0o733,                         // octal integer
}

See Also

ACCELERATORS, CHARACTERISTICS, DIALOG, LANGUAGE, MENU, STRINGTABLE, VERSION


RTEXT Control

The RTEXT resource-definition statement creates a right-aligned text control. The control is a simple rectangle displaying the given text right-aligned in the rectangle. The text is formatted before it is displayed. Words that would extend past the end of a line are automatically wrapped to the beginning of the next line. Words that are longer than the width of the control are truncated.

RTEXT text, id, x, y, width, height [[, style [[, extended-style]]]]

Parameters

style
Specifies styles for the text control, which can be any combination of the following: WS_TABSTOP and WS_GROUP.

If you do not specify a style, the default style is SS_RIGHT | WS_GROUP.

For more information on the text, id, x, y, width, height, style, and extended-style parameters, see Common Control Parameters.

Example

The following example demonstrates the use of the RTEXT statement:

RTEXT "Number of Messages", 4, 30, 50, 100, 10

See Also

CONTROL, CTEXT, DIALOG, LTEXT


SCROLLBAR Control

The SCROLLBAR resource-definition statement creates a scroll-bar control. The control is a rectangle that contains a scroll box and has direction arrows at both ends. The scroll-bar control sends a notification message to its parent whenever the user clicks the mouse in the control. The parent is responsible for updating the scroll-box position. Scroll-bar controls can be positioned anywhere in a window and used whenever needed to provide scrolling input.

SCROLLBAR text, id, x, y, width, height [[, style [[, extended-style]]]]

Parameters

style
Specifies a combination (or none) of the following styles: WS_TABSTOP, WS_GROUP, and WS_DISABLED.

In addition to these styles, the style parameter may contain a combination (or none) of the SCROLLBAR-class styles.

If you do not specify a style, the default style is SBS_HORZ.

For more information on the text, id, x, y, width, height, style, and extended-style parameters, see Common Control Parameters.

Example

The following example demonstrates the use of the SCROLLBAR statement:

SCROLLBAR 999, 25, 30, 10, 100


STATE3 Control

The STATE3 resource-definition statement defines a three-state check box control. The control is identical to a CHECKBOX, except that it has three states: checked, unchecked, and disabled (grayed).

STATE3 text, id, x, y, width, height [[, style [[, extended-style]]]]

Parameters

text
Specifies text that is displayed to the right of the control.
style
Specifies the control styles. This value can be a combination of the button class style BS_3STATE and the WS_TABSTOP and WS_GROUP styles.

If you do not specify a style, the default style is BS_3STATE | WS_TABSTOP.

For more information on the text, id, x, y, width, height, style, and extended-style parameters, see Common Control Parameters.

See Also

AUTOCHECKBOX, CHECKBOX, CONTROL


STRINGTABLE Resource

The STRINGTABLE resource-definition statement specifies one or more string resources for an application. String resources are simply null-terminated Unicode strings that can be loaded when needed from the executable file, using the LoadString function.

STRINGTABLE  [[optional-statements]]  {      stringID string      . . .  }

Parameters

optional-statements
This parameter can be zero or more of the following statements.
Statement | Description
CHARACTERISTICS dword | User-defined information about a resource that can be used by tools that read and write resource files. For more information, see CHARACTERISTICS.
LANGUAGE language, sublanguage | Specifies the language for the resource. For more information, see LANGUAGE.
VERSION dword | User-defined version number for the resource that can be used by tools that read and write resource files. For more information, see VERSION.

stringID
Specifies an unsigned 16-bit integer that identifies the resource.
string
Specifies one or more strings, enclosed in quotation marks. The string must be no longer than 4097 characters and must occupy a single line in the source file. To add a carriage return to the string, use this character sequence: \012. For example, "Line one\012Line two" defines a string that is displayed as follows:
Line one
Line two

To embed quotes in the string, use the following sequence: "". For example, """Line three""" defines a string that is displayed as follows:

"Line three"

To encode Unicode characters, use a capital L followed by the Unicode characters enclosed by quotes. See the Examples section for an example.

The resource compiler also supports line continuations in string. See the Examples section for an example.

Remarks

RC allocates 16 strings per section and uses the identifier value to determine which section is to contain the string. Strings whose identifiers differ only in the bottom 4 bits are placed in the same section.

Examples

The following example demonstrates the use of the STRINGTABLE statement:

#define IDS_HELLO    1
#define IDS_GOODBYE  2

STRINGTABLE
{
    IDS_HELLO,   "Hello"
    IDS_GOODBYE, "Goodbye"
}

The following example shows how to encode Unicode characters:

STRINGTABLE
BEGIN
IDS_CHINESESTRING L"\x5e2e\x52a9"
IDS_RUSSIANSTRING L"\x0421\x043f\x0440\x0430\x0432\x043a\x0430"
IDS_ARABICSTRING L"\x062a\x0639\x0644\x064a\x0645\x0627\x062a"
END

The following example shows how line continuations can be used:

STRINGTABLE
BEGIN
IDS_VERYLONGSTRING "blah blah blah blah blah blah \
blah blah blah blah blah blah \
blah blah blah blah blah blah \
blah blah blah blah blah blah"
END

See Also

LoadString, ACCELERATORS, CHARACTERISTICS, DIALOG, LANGUAGE, MENU, RCDATA, VERSION


STYLE Statement

The STYLE resource-definition statement sets the window style of the dialog box. The window style specifies whether the box is a pop-up or a child window.

STYLE style

Parameters

style
Specifies the window style. This parameter can be an integer value or a combination of window style values (such as WS_CAPTION and WS_SYSMENU) and dialog box style values (such as DS_CENTER).

For a list of window styles, see CreateWindow. For a list of dialog box styles, see Dialog Box Template Styles. If you use the window or dialog box style values, you must include WINDOWS.H.


User-Defined Resource

A user-defined resource-definition statement specifies a resource that contains application-specific data. The data can have any format and can be defined either as the content of a given file (if the filename parameter is given) or as a series of numbers and strings (if the raw-data block is given).

nameID typeID filename

The filename specifies the name of a file containing the binary data of the resource. The contents of the file are included as the resource. RC does not interpret the binary data in any way. It is the programmer's responsibility to ensure that the data is properly aligned for the target computer architecture.

A user-defined resource can also be defined completely in the resource script using the following syntax:

nameID typeID   {      raw-data  }

Parameters

nameID
Specifies either a unique name or a 16-bit unsigned integer that identifies the resource.
typeID
Specifies either a unique name or a 16-bit unsigned integer that identifies the resource type. If a number is given, it must be greater than 255. The numbers 1 through 255 are reserved for existing and future redefined resource types.
filename
Specifies the name of the file that contains the resource data. The parameter must be a valid filename; it must be a full path if the file is not in the current working directory.
raw-data
Specifies raw data consisting of one or more integers or strings of characters. Integers can be specified in decimal, octal, or hexadecimal format. To be compatible with 16-bit Windows, integers are stored as WORD values. You can store an integer as a DWORD value by qualifying the integer with the L suffix.

Strings are enclosed in quotation marks. RC does not automatically append a terminating null character to a string. Each string is a sequence of the specified ANSI characters, unless you qualify it as a wide-character string with the L prefix.

The block of data begins on a DWORD boundary and RC performs no padding or alignment of data within the raw-data block. It is the programmer's responsibility to ensure the proper alignment of data within the block.

Example

The following example shows several user-defined statements:

array   MYRES   data.res
14      300     custom.res
18 MYRES2
{
   "Here is an ANSI string\0",    // explicitly null-terminated
   L"Here is a Unicode string\0", // explicitly null-terminated
   1024,                          // integer, stored as WORD
   7L,                            // integer, stored as DWORD
   0x029a,                        // hex integer
   0o733,                         // octal integer
}


VERSION Statement

The VERSION resource-definition statement specifies version information about a resource that can be used by tools that read and write resource files. The specified dword value appears with the resource in the compiled .RES file. However, the value is not stored in the executable file and has no significance to the system.

The VERSION statement appears before the beginning of the body of an ACCELERATORS, DIALOG, MENU, RCDATA, or STRINGTABLE resource definition. The specified value applies only to that resource.

VERSION dword

Parameters

dword
A user-defined DWORD value.

See Also

ACCELERATORS, CHARACTERISTICS, DIALOG, LANGUAGE, MENU, RCDATA, STRINGTABLE


VERSIONINFO Resource

The VERSIONINFO resource-definition statement creates a version-information resource. The resource contains such information about the file as its version number, its intended operating system, and its original filename. The resource is intended to be used with the Version Information functions.

versionID VERSIONINFO fixed-info  {      block-statement      . . .  }

Parameters

versionID
Specifies the version-information resource identifier. This value must be 1.
fixed-info
Specifies the version information, such as the file version and the intended operating system. This parameter consists of the following statements.
Statement | Description
FILEVERSION
version 		Specifies the binary version number for the file. The version consists of two 32-bit integers, defined by four 16-bit integers. For example, "FILEVERSION 3,10,0,61" is translated into two doublewords: 0x0003000a and 0x0000003d, in that order. Therefore, if version is defined by the DWORD values dw1 and dw2, they need to appear in the FILEVERSION statement as follows: HIWORD(dw1), LOWORD(dw1), HIWORD(dw2), LOWORD(dw2).
PRODUCTVERSION
version 		Specifies the binary version number for the product with which the file is distributed. The version parameter is two 32-bit integers, defined by four 16-bit integers. For more information about version, see the FILEVERSION description.
FILEFLAGSMASK
fileflagsmask 		Specifies which bits in the FILEFLAGS statement are valid. If a bit is set, the corresponding bit in FILEFLAGS is valid.
FILEFLAGS fileflags | Specifies the Boolean attributes of the file. The fileflags parameter must be the combination of all the file flags that are valid at compile time. For 16-bit Windows, this value is 0x3f.
FILEOS fileos | Specifies the operating system for which this file was designed. The fileos parameter can be one of the operating system values given in the Remarks section.
FILETYPE filetype | Specifies the general type of file. The filetype parameter can be one of the file type values listed in the Remarks section.
FILESUBTYPE
subtype 		Specifies the function of the file. The subtype parameter is zero unless the type parameter in the FILETYPE statement is VFT_DRV, VFT_FONT, or VFT_VXD. For a list of file subtype values, see the Remarks section.

block-statement
Specifies one or more version-information blocks. A block can contain string information or variable information. For more information, see StringFileInfo Block or VarFileInfo Block.

Remarks

To use the constants specified with the VERSIONINFO statement, you must include the Winver.h or Windows.h header file in the resource-definition file.

The following list describes the parameters used in the VERSIONINFO statement:

fileflags
Specifies a combination of the following values.
Value | Description
VS_FF_DEBUG | File contains debugging information or is compiled with debugging features enabled.
VS_FF_PATCHED | File has been modified and is not identical to the original shipping file of the same version number.
VS_FF_PRERELEASE | File is a development version, not a commercially released product.
VS_FF_PRIVATEBUILD | File was not built using standard release procedures. If this value is given, the StringFileInfo block must contain a PrivateBuild string.
VS_FF_SPECIALBUILD | File was built by the original company using standard release procedures but is a variation of the standard file of the same version number. If this value is given, the StringFileInfo block must contain a SpecialBuild string.

fileos
Specifies one of the following values.
Value | Description
VOS_UNKNOWN | The operating system for which the file was designed is unknown.
VOS_DOS | File was designed for MS-DOS.
VOS_NT | File was designed for Windows NT/Windows 2000.
VOS__WINDOWS16 | File was designed for 16-bit Windows.
VOS__WINDOWS32 | File was designed for 32-bit Windows.
VOS_DOS_WINDOWS16 | File was designed for 16-bit Windows running with MS-DOS.
VOS_DOS_WINDOWS32 | File was designed for 32-bit Windows running with MS-DOS.
VOS_NT_WINDOWS32 | File was designed for Windows NT/2000.

The values 0x00002L, 0x00003L, 0x20000L and 0x30000L are reserved.

filetype
Specifies one of the following values.
Value | Description
VFT_UNKNOWN | File type is unknown.
VFT_APP | File contains an application.
VFT_DLL | File contains a dynamic-link library (DLL).
VFT_DRV | File contains a device driver. If filetype is VFT_DRV, subtype contains a more specific description of the driver.
VFT_FONT | File contains a font. If filetype is VFT_FONT, subtype contains a more specific description of the font.
VFT_VXD | File contains a virtual device.
VFT_STATIC_LIB | File contains a static-link library.

All other values are reserved for use by Microsoft.

subtype
Specifies additional information about the file type.

If filetype specifies VFT_DRV, this parameter can be one of the following values.
Value | Description
VFT2_UNKNOWN | Driver type is unknown.
VFT2_DRV_COMM | File contains a communications driver.
VFT2_DRV_PRINTER | File contains a printer driver.
VFT2_DRV_KEYBOARD | File contains a keyboard driver.
VFT2_DRV_LANGUAGE | File contains a language driver.
VFT2_DRV_DISPLAY | File contains a display driver.
VFT2_DRV_MOUSE | File contains a mouse driver.
VFT2_DRV_NETWORK | File contains a network driver.
VFT2_DRV_SYSTEM | File contains a system driver.
VFT2_DRV_INSTALLABLE | File contains an installable driver.
VFT2_DRV_SOUND | File contains a sound driver.

If filetype specifies VFT_FONT, this parameter can be one of the following values.
Value | Description
VFT2_UNKNOWN | Font type is unknown.
VFT2_FONT_RASTER | File contains a raster font.
VFT2_FONT_VECTOR | File contains a vector font.
VFT2_FONT_TRUETYPE | File contains a TrueType font.

If filetype specifies VFT_VXD, this parameter must be the virtual-device identifier included in the virtual-device control block.

All subtype values not listed here are reserved for use by Microsoft.

langID
Specifies one of the following language codes.
Code | Language | Code | Language
0x0401 | Arabic | 0x0415 | Polish
0x0402 | Bulgarian | 0x0416 | Brazilian Portuguese
0x0403 | Catalan | 0x0417 | Rhaeto-Romanic
0x0404 | Traditional Chinese | 0x0418 | Romanian
0x0405 | Czech | 0x0419 | Russian
0x0406 | Danish | 0x041A | Croato-Serbian (Latin)
0x0407 | German | 0x041B | Slovak
0x0408 | Greek | 0x041C | Albanian
0x0409 | U.S. English | 0x041D | Swedish
0x040A | Castilian Spanish | 0x041E | Thai
0x040B | Finnish | 0x041F | Turkish
0x040C | French | 0x0420 | Urdu
0x040D | Hebrew | 0x0421 | Bahasa
0x040E | Hungarian | 0x0804 | Simplified Chinese
0x040F | Icelandic | 0x0807 | Swiss German
0x0410 | Italian | 0x0809 | U.K. English
0x0411 | Japanese | 0x080A | Mexican Spanish
0x0412 | Korean | 0x080C | Belgian French
0x0413 | Dutch | 0x0C0C | Canadian French
0x0414 | Norwegian – Bokml | 0x100C | Swiss French
0x0810 | Swiss Italian | 0x0816 | Portuguese
0x0813 | Belgian Dutch | 0x081A | Serbo-Croatian (Cyrillic)
0x0814 | Norwegian – Nynorsk

charsetID
Specifies one of the following character-set identifiers.
Identifier | Character Set
0 | 7-bit ASCII
932 | Japan (Shift – JIS X-0208)
949 | Korea (Shift – KSC 5601)
950 | Taiwan (Big5)
1200 | Unicode
1250 | Latin-2 (Eastern European)
1251 | Cyrillic
1252 | Multilingual
1253 | Greek
1254 | Turkish
1255 | Hebrew
1256 | Arabic

string-name
Specifies one of the following predefined names.
Name | Description
Comments | Specifies additional information that should be displayed for diagnostic purposes.
CompanyName | Specifies the company that produced the file—for example, "Microsoft Corporation" or "Standard Microsystems Corporation, Inc." This string is required.
FileDescription | Specifies a file description to be presented to users. This string may be displayed in a list box when the user is choosing files to install—for example, "Keyboard Driver for AT-Style Keyboards". This string is required.
FileVersion | Specifies the version number of the file—for example, "3.10" or "5.00.RC2". This string is required.
InternalName | Specifies the internal name of the file, if one exists—for example, a module name if the file is a dynamic-link library. If the file has no internal name, this string should be the original filename, without extension. This string is required.
LegalCopyright | Specifies all copyright notices that apply to the file. This should include the full text of all notices, legal symbols, copyright dates, and so on—for example, "Copyright© Microsoft Corporation 1990–1999". This string is optional.
LegalTrademarks | Specifies all trademarks and registered trademarks that apply to the file. This should include the full text of all notices, legal symbols, trademark numbers, and so on. This string is optional.
OriginalFilename | Specifies the original name of the file, not including a path. This information enables an application to determine whether a file has been renamed by a user. The format of the name depends on the file system for which the file was created. This string is required.
PrivateBuild | Specifies information about a private version of the file—for example, "Built by TESTER1 on \TESTBED". This string should be present only if VS_FF_PRIVATEBUILD is specified in the fileflags parameter of the root block.
ProductName | Specifies the name of the product with which the file is distributed. This string is required.
ProductVersion | Specifies the version of the product with which the file is distributed—for example, "3.10" or "5.00.RC2". This string is required.
SpecialBuild | Specifies how this version of the file differs from the standard version—for example, "Private build for TESTER1 solving mouse problems on M250 and M250E computers". This string should be present only if VS_FF_SPECIALBUILD is specified in the fileflags parameter of the root block.


StringFileInfo Block

A string information block has the following form:

BLOCK "StringFileInfo"  {       BLOCK "lang-charset"      {          VALUE "string-name", "value"              . . .      }  }

Parameters

lang-charset
Specifies a language and character-set identifier pair. It is a hexadecimal string consisting of the concatenation of the language and character-set identifiers specified in the Remarks section.
string-name
Specifies the name of a value in the block and can be one of the predefined names specified in the Remarks section.
value
Specifies, as a character string, the value of the corresponding string name. More than one VALUE statement can be given.

Remarks

The lang-charset parameter specifies one of the following language codes.

Code | Language | Code | Language
0x0401 | Arabic | 0x0415 | Polish
0x0402 | Bulgarian | 0x0416 | Brazilian Portuguese
0x0403 | Catalan | 0x0417 | Rhaeto-Romanic
0x0404 | Traditional Chinese | 0x0418 | Romanian
0x0405 | Czech | 0x0419 | Russian
0x0406 | Danish | 0x041A | Croato-Serbian (Latin)
0x0407 | German | 0x041B | Slovak
0x0408 | Greek | 0x041C | Albanian
0x0409 | U.S. English | 0x041D | Swedish
0x040A | Castilian Spanish | 0x041E | Thai
0x040B | Finnish | 0x041F | Turkish
0x040C | French | 0x0420 | Urdu
0x040D | Hebrew | 0x0421 | Bahasa
0x040E | Hungarian | 0x0804 | Simplified Chinese
0x040F | Icelandic | 0x0807 | Swiss German
0x0410 | Italian | 0x0809 | U.K. English
0x0411 | Japanese | 0x080A | Mexican Spanish
0x0412 | Korean | 0x080C | Belgian French
0x0413 | Dutch | 0x0C0C | Canadian French
0x0414 | Norwegian – Bokml | 0x100C | Swiss French
0x0810 | Swiss Italian | 0x0816 | Portuguese
0x0813 | Belgian Dutch | 0x081A | Serbo-Croatian (Cyrillic)
0x0814 | Norwegian – Nynorsk |  |

The lang-charset parameter also specifies one of the following character-set identifiers.

Identifier | Character Set
0 | 7-bit ASCII
932 | Japan (Shift – JIS X-0208)
949 | Korea (Shift – KSC 5601)
950 | Taiwan (Big5)
1200 | Unicode
1250 | Latin-2 (Eastern European)
1251 | Cyrillic
1252 | Multilingual
1253 | Greek
1254 | Turkish
1255 | Hebrew
1256 | Arabic

The string-name parameter specifies one of the following predefined names.

Name | Description
Comments | Specifies additional information that should be displayed for diagnostic purposes.
CompanyName | Specifies the company that produced the file—for example, "Microsoft Corporation" or "Standard Microsystems Corporation, Inc." This string is required.
FileDescription | Specifies a file description to be presented to users. This string may be displayed in a list box when the user is choosing files to install—for example, "Keyboard Driver for AT-Style Keyboards". This string is required.
FileVersion | Specifies the version number of the file—for example, "3.10" or "5.00.RC2". This string is required.
InternalName | Specifies the internal name of the file, if one exists—for example, a module name if the file is a dynamic-link library. If the file has no internal name, this string should be the original filename, without extension. This string is required.
LegalCopyright | Specifies all copyright notices that apply to the file. This should include the full text of all notices, legal symbols, copyright dates, and so on—for example, "Copyright© Microsoft Corporation 1990–1999". This string is optional.
LegalTrademarks | Specifies all trademarks and registered trademarks that apply to the file. This should include the full text of all notices, legal symbols, trademark numbers, and so on. This string is optional.
OriginalFilename | Specifies the original name of the file, not including a path. This information enables an application to determine whether a file has been renamed by a user. The format of the name depends on the file system for which the file was created. This string is required.
PrivateBuild | Specifies information about a private version of the file—for example, "Built by TESTER1 on \TESTBED". This string should be present only if VS_FF_PRIVATEBUILD is specified in the fileflags parameter of the root block.
ProductName | Specifies the name of the product with which the file is distributed. This string is required.
ProductVersion | Specifies the version of the product with which the file is distributed—for example, "3.10" or "5.00.RC2". This string is required.
SpecialBuild | Specifies how this version of the file differs from the standard version—for example, "Private build for TESTER1 solving mouse problems on M250 and M250E computers". This string should be present only if VS_FF_SPECIALBUILD is specified in the fileflags parameter of the root block.


VarFileInfo Block

A variable information block has the following form:

BLOCK "VarFileInfo"  {      VALUE "Translation",          langID, charsetID              . . .  }

Parameters

langID
Specifies one of the language identifiers specified in the Remarks section.
charsetID
Specifies one of the character-set identifiers specified in the Remarks section.

Remarks

More than one identifier pair can be given, but each pair must be separated from the preceding pair with a comma.

The langID parameter specifies one of the following language codes:

Code | Language | Code | Language
0x0401 | Arabic | 0x0415 | Polish
0x0402 | Bulgarian | 0x0416 | Brazilian Portuguese
0x0403 | Catalan | 0x0417 | Rhaeto-Romanic
0x0404 | Traditional Chinese | 0x0418 | Romanian
0x0405 | Czech | 0x0419 | Russian
0x0406 | Danish | 0x041A | Croato-Serbian (Latin)
0x0407 | German | 0x041B | Slovak
0x0408 | Greek | 0x041C | Albanian
0x0409 | U.S. English | 0x041D | Swedish
0x040A | Castilian Spanish | 0x041E | Thai
0x040B | Finnish | 0x041F | Turkish
0x040C | French | 0x0420 | Urdu
0x040D | Hebrew | 0x0421 | Bahasa
0x040E | Hungarian | 0x0804 | Simplified Chinese
0x040F | Icelandic | 0x0807 | Swiss German
0x0410 | Italian | 0x0809 | U.K. English
0x0411 | Japanese | 0x080A | Mexican Spanish
0x0412 | Korean | 0x080C | Belgian French
0x0413 | Dutch | 0x0C0C | Canadian French
0x0414 | Norwegian – Bokml | 0x100C | Swiss French
0x0810 | Swiss Italian | 0x0816 | Portuguese
0x0813 | Belgian Dutch | 0x081A | Serbo-Croatian (Cyrillic)
0x0814 | Norwegian – Nynorsk |  |

The charsetID parameter specifies one of the following character-set identifiers:

Identifier | Character Set
0 | 7-bit ASCII
932 | Japan (Shift – JIS X-0208)
949 | Korea (Shift – KSC 5601)
950 | Taiwan (Big5)
1200 | Unicode
1250 | Latin-2 (Eastern European)
1251 | Cyrillic
1252 | Multilingual
1253 | Greek
1254 | Turkish
1255 | Hebrew
1256 | Arabic


Common Control Parameters

The following describes the general syntax for a control resource-definition statement, represented by control. The meaning of each parameter is given below. Occasionally, a statement will use a parameter differently, or may ignore a parameter. The statement-specific variation is described in the documentation for the statement.

control [[text,]] id, x, y, width, height[[, style[[, extended-style]]]][, helpId]
[{    data-element-1 [,    data-element-2 [,    ... ]]}]

Parameters

text
Specifies text that is displayed with the control. The text is positioned within the control's specified dimensions or adjacent to the control.

This parameter must contain zero or more characters enclosed in double quotation marks ("). Strings are automatically null-terminated and converted to Unicode in the resulting resource file.

By default, the characters listed between the double quotation marks are ANSI characters, and escape sequences are interpreted as byte escape sequences. If the string is preceded by the L prefix, the string is a wide-character string and escape sequences are interpreted as 2-byte escape sequences that specify Unicode characters. If a double quotation mark is required in the text, you must include the double quotation mark twice.

An ampersand (&) character in the text indicates that the following character is used as a mnemonic character for the control. When the control is displayed, the ampersand is not shown, but the mnemonic character is underlined. The user can choose the control by pressing the key corresponding to the underlined mnemonic character. To use the ampersand as a character in a string, insert two ampersands (&&).

id
Specifies the control identifier. This value must be a 16-bit unsigned integer in the range 0 through 65,535 or a simple arithmetic expression that evaluates to a value in that range.
x
Specifies the x-coordinate of the left side of the control relative to the left side of the dialog box. This value must be a 16-bit unsigned integer in the range 0 through 65,535. The coordinate is in dialog units and is relative to the origin of the dialog box, window, or control containing the specified control.
y
Specifies the y-coordinate of the top side of the control relative to the top of the dialog box. This value must be a 16-bit unsigned integer in the range 0 through 65,535. The coordinate is in dialog units relative to the origin of the dialog box, window, or control containing the specified control.
width
Specifies the width of the control. This value must be a 16-bit unsigned integer in the range 1 through 65,535. The width is in 1/4-character units.
height
Specifies the height of the control. This value must be a 16-bit unsigned integer in the range 1 through 65,535. The height is in 1/8-character units.
style
Specifies the control styles. Use the bitwise OR (|) operator to combine styles. For more information, see Window Styles.
extended-style
Specifies extended window styles. You must specify style to specify extended-style. For more information, see EXSTYLE.
helpID
Specifies a numeric expression indicating the ID used to identify the control during WM_HELP processing.
controlData
Specifies the control-specific data for the control. When a dialog is created, and a control in that dialog which has control-specific data is created, a pointer to that data is passed into the control's window procedure via the lParam to the WM_CREATE message for that control.

Remarks

Horizontal dialog units are 1/4 of the dialog base width unit. Vertical units are 1/8 of the dialog base height unit. The current dialog base units are computed from the height and width of the current system font. The GetDialogBaseUnits function returns the dialog base units in pixels. The coordinates are relative to the origin of the dialog box.


Common Resource Attributes

The resource-definition statements supported on 16-bit Windows include a load-mem option that specifies the loading and memory characteristics of the resource. The resource statements supported on 32-bit Windows do not use any of these attributes. However, the attributes are permitted in resource scripts for backward compatibility. Win32 resources are loaded when the corresponding module is loaded, and are freed when the module is unloaded. These attributes are ignored.

These attributes are divided into two groups: load attributes and memory attributes.

Load Attributes

The load attributes specify when the resource is to be loaded. The load parameter must be one of the following attirbutes.

Attribute | Description
PRELOAD | Ignored. In 16-bit Windows, the resource is loaded with the executable file.
LOADONCALL | Ignored. In 16-bit Windows, the resource is loaded when called.

Memory Attributes

The memory attributes specify whether the resource is fixed or movable, whether it is discardable, and whether it is pure. The memory parameter can be one or more of the following attributes.

Attribute | Description
FIXED | Ignored. In 16-bit Windows, the resource remains at a fixed memory location.
MOVEABLE | Ignored. In 16-bit Windows, the resource can be moved if necessary to compact memory.
DISCARDABLE | Ignored. In 16-bit Windows, the resource can be discarded if no longer needed.
PURE | Ignored. Accepted for compatibility with existing resource scripts.
IMPURE | Ignored. Accepted for compatibility with existing resource scripts.
SHARED | Ignored. In 16-bit Windows, SHARED is ignored for regular modules. For a resource from a ROM Windows module, the memory is shared.
NONSHARED | Ignored. In 16-bit Windows, NONSHARED is ignored for regular modules. For a resource from a ROM Windows module, the memory is not shared.


Sample Resource-Definition File

The following example shows a script file that defines the resources for an application named Shapes:

#include "shapes.h"

ShapesCursor  CURSOR  SHAPES.CUR
ShapesIcon    ICON    SHAPES.ICO

ShapesMenu MENU
{
    POPUP "&Shape"
    {
        MENUITEM "&Clear", ID_CLEAR
        MENUITEM "&Rectangle", ID_RECT
        MENUITEM "&Triangle", ID_TRIANGLE
        MENUITEM "&Star", ID_STAR
        MENUITEM "&Ellipse", ID_ELLIPSE
    }
}

The CURSOR statement names the application's cursor resource ShapesCursor and specifies the cursor file SHAPES.CUR, which contains the image for that cursor.

The ICON statement names the application's icon resource ShapesIcon and specifies the icon file SHAPES.ICO, which contains the image for that icon.

The MENU statement defines an application menu named ShapesMenu, a pop-up menu with five menu items.

The body of the menu definition, enclosed by the curly braces, or the BEGIN and END keywords, specifies each menu item and the menu identifier that is returned when the user selects that item. For example, the first item on the menu, Clear, returns the menu identifier ID_CLEAR when the user selects it. The menu identifiers are defined in the application header file, SHAPES.H.


Using RC (The RC Command Line)

To start RC, use the RC command.

RC [[options]] script-file

The script-file parameter specifies the name of the resource-definition file that contains the names, types, filenames, and descriptions of the resources to be compiled. The options parameter can be one or more of the following command-line options.

Options

/?
Displays a list of RC command-line options.
/d
Defines a symbol for the preprocessor that you can test with the #ifdef directive.
/fo resname
Uses resname for the name of the .RES file.
/h
Displays a list of RC command-line options.
/i
Searches the specified directory before searching the directories specified by the INCLUDE environment variable.
/l codepage
Specifies default language for compilation. For example, -l409 is equivalent to including the following statement at the top of the resource script file:
LANGUAGE LANG_ENGLISH,SUBLANG_ENGLISH_US

For more information, see Language Identifiers.

Alternatively, you use #pragma code_page(409) in the .RC file.

/n
Null terminates all strings in the string table.
/r
Ignored. Provided for compatibility with existing makefiles.
/u
Undefines a symbol for the preprocessor.
/v
Displays messages that report on the progress of the compiler.
/x
Prevents RC from checking the INCLUDE environment variable when searching for header files or resource files.

Remarks

Options are not case sensitive, and a hyphen (-) can be used in place of a slash mark (/). You can combine single-letter options if they do not require any additional parameters. For example, the following two commands are equivalent:

rc /V /X SAMPLE.RC
rc -vx sample.rc

For more information, see the following topics:

  • Defining Names for the Preprocessor
  • Renaming the Compiled Resource File
  • Searching for Files
  • Displaying Progress Messages
  • RC Diagnostic Messages


Defining Names for the Preprocessor

You can specify conditional compilation in a script, based on whether a name is defined on the RC command line with the /d option, or in the file or an include file with the #define directive.

For example, suppose your application has a pop-up menu, the Debug menu, that should appear only with debugging versions of the application. When you compile the application for normal use, the Debug menu is not included. The following example shows the statements that can be added to the resource-definition file to define the Debug menu:

MainMenu MENU
{
    . . .
#ifdef DEBUG
    POPUP "&Debug"
    {
        MENUITEM "&Memory usage", ID_MEMORY
        MENUITEM "&Walk data heap", ID_WALK_HEAP
    }
#endif
}

When compiling resources for a debugging version of the application, you could include the Debug menu by using the following command:

rc -d DEBUG myapp.rc

To compile resources for a normal version of the application—one that does not include the Debug menu—you could use the following command:

rc myapp.rc


Renaming the Compiled Resource File

By default, when compiling resources, RC names the compiled resource (.RES) file with the base name of the .RC file and places it in the same directory as the .RC file. CVTRES must then be invoked to convert the .RES file to a binary resource (.RBJ) format which can be understood by the linker. The following example compiles MYAPP.RC and creates a compiled resource file named MYAPP.RES in the same directory as MYAPP.RC:

rc myapp.rc

The /fo option gives the resulting .RES file a name that differs from the name of the corresponding .RC file. For example, to name the resulting .RES file NEWFILE.RES, use the following command:

rc -fo newfile.res myapp.rc

The /fo option can also place the .RES file in a different directory. For example, the following command places the compiled resource file MYAPP.RES in the directory C:\SOURCE\RESOURCE:

rc -fo c:\source\resource\myapp.res myapp.rc


Searching for Files

By default, RC searches for header files and resource files (such as icon and cursor files) first in the current directory and then in the directories specified by the INCLUDE environment variable. (The PATH environment variable has no effect on which directories RC searches.)

Adding a Directory to Search

You can use the /i option to add a directory to the list of directories RC searches. The compiler then searches the directories in the following order:

  1. The current directory
  2. The directory or directories you specify by using the /i option, in the order in which they appear on the RC command line
  3. The list of directories specified by the INCLUDE environment variable, in the order in which the variable lists them, unless you specify the /x option

The following example compiles the resource-definition file MYAPP.RC:

rc /i c:\source\stuff /i d:\resources myapp.rc

When compiling the script MYAPP.RC, RC searches for header files and resource files first in the current directory, then in C:\SOURCE\STUFF and D:\RESOURCES, and then in the directories specified by the INCLUDE environment variable.

Ignoring the INCLUDE Environment Variable

You can prevent RC from using the INCLUDE environment variable when determining the directories to search. To do so, use the /x option. The compiler then searches for files only in the current directory and in any directories you specify by using the /i option.

The following command compiles the script file MYAPP.RC:

rc /x /i c:\source\stuff myapp.rc

When compiling the script MYAPP.RC, RC searches for header files and resource files first in the current directory and then in C:\SOURCE\STUFF. It does not search the directories specified by the INCLUDE environment variable.


Displaying Progress Messages

By default, RC compiles without displaying progress messages. However, you can specify that RC is to display progress messages. To do so, use the /v option.

The following example causes RC to report its progress as it compiles the resource-definition file SAMPLE.RC and creates the compiled resource file SAMPLE.RES:

rc /v sample.rc


RC Diagnostic Messages

This section describes of diagnostic messages produced by RC. Many of these messages appear when RC is not able to compile resources properly. The descriptions clarify the cause of each message.

A capital V in parentheses (V) at the beginning of a message description indicates that the message is displayed only if RC is run with the /v (verbose) option. These messages are generally informative and do not necessarily indicate errors.

The messages are listed in alphabetic order.

A
B
C
E
F
I
N
O
R
T
U
V
W


A

Accelerator Type required (ASCII or VIRTKEY)
The type parameter in the ACCELERATORS statement must contain either the ASCII or VIRTKEY value.


B

BEGIN expected in Accelerator Table
An ACCELERATORS statement was not followed by the BEGIN keyword.
BEGIN expected in Dialog
A DIALOG statement was not followed by the BEGIN keyword.
BEGIN expected in menu
A MENU statement was not followed by the BEGIN keyword.
BEGIN expected in RCData
An RCDATA statement was not followed by the BEGIN keyword.
BEGIN expected in String Table
A STRINGTABLE statement was not followed by the BEGIN keyword.
BEGIN expected in VERSIONINFO resource
A VERSIONINFO statement was not followed by the BEGIN keyword.
Bitmap file resource-file is not in version-number format.
Use Microsoft Image Editor (IMAGEDIT.EXE) to convert old resource files to the current format.


C

Cannot Re-use String Constants
You are using the same value twice in a STRINGTABLE statement. Make sure that you have not mixed overlapping decimal and hexadecimal values.
Control Character out of range [A – Z]
A control character in the ACCELERATORS statement is invalid. The character following the caret (^) must be in the range A through Z.
Could not open in-file-name
Microsoft Windows 32 Resource Compiler (RC) could not open the specified file. Make sure that the file exists and that you typed the filename correctly.
Couldn't open resource-name
Microsoft Windows 32 Resource Compiler (RC) could not open the specified file. Make sure that the file exists and that you typed the filename correctly.
Creating resource-name
(V) Microsoft Windows 32 Resource Compiler (RC) is creating a new binary resource (.RES) file.


E

Empty menus not allowed
An END keyword appears before any menu items are defined in the MENU statement. Empty menus are not permitted by Microsoft Windows 32 Resource Compiler (RC). Make sure that you do not have any opening quotation marks within the MENU statement.
END expected in Dialog
The END keyword must appear at the end of a DIALOG statement. Make sure that there are no opening quotation marks left from the preceding statement.
END expected in menu
The END keyword must appear at the end of a MENU statement. Make sure that there are no mismatched BEGIN and END statements.
Error Creating resource-name
Microsoft Windows 32 Resource Compiler (RC) could not create the specified binary resource (.RES) file. Make sure that it is not being created on a read-only drive. Use the /voption to find out whether the file is being created.
Expected Comma in Accelerator Table
Microsoft Windows 32 Resource Compiler (RC) requires a comma between the event and idvalue parameters in the ACCELERATORS statement.
Expected control class name
The class parameter of a CONTROL statement in the DIALOG statement must be one of the following control types: BUTTON, COMBOBOX, EDIT, LISTBOX, SCROLLBAR, STATIC, or user-defined. Make sure that the class is spelled correctly.
Expected font face name
The typeface parameter of the FONT statement in the DIALOG statement must be a character string enclosed in double quotation marks ("). This parameter specifies the name of a font.
Expected ID value for Menuitem
The MENU statement must contain a MENUITEM statement, which has either an integer or a symbolic constant in the MenuID parameter.
Expected Menu String
Each MENUITEM and POPUP statement must contain a text parameter. This parameter is a string enclosed in double quotation marks (") that specifies the name of the menu item or pop-up menu. A MENUITEM SEPARATOR statement requires no quoted string.
Expected numeric command value
Microsoft Windows 32 Resource Compiler (RC) was expecting a numeric idvalue parameter in the ACCELERATORS statement. Make sure that you have used a #define constant to specify the value and that the constant used is spelled correctly.
Expected numeric constant in string table
A numeric constant, defined in a #define statement, must immediately follow the BEGIN keyword in a STRINGTABLE statement.
Expected numeric point size
The pointsize parameter of the FONT statement in the DIALOG statement must be an integer point-size value.
Expected Numerical Dialog constant
A DIALOG statement requires integer values for the x, y, width, and height parameters. Make sure that these values, which are included after the DIALOG keyword, are not negative.
Expected String in STRINGTABLE
A string is expected after each numeric stringid parameter in a STRINGTABLE statement.
Expected String or Constant Accelerator command
Microsoft Windows 32 Resource Compiler (RC) was not able to determine which key was being set up for the accelerator. The event parameter in the ACCELERATORS statement might be invalid.
Expected VALUE, BLOCK, or END keyword.
The VERSIONINFO structure requires a VALUE, BLOCK, or END keyword.
Expecting number for ID
A number is expected for the id parameter of a CONTROL statement in the DIALOG statement. Make sure that you have a number or a #define statement for the control identifier.
Expecting quoted string for key
The key string following the BLOCK or VALUE keyword should be enclosed in double quotation marks.
Expecting quoted string in dialog class
The class parameter of the CLASS statement in the DIALOG statement must be an integer or a string enclosed in double quotation marks (").
Expecting quoted string in dialog title
The captiontext parameter of the CAPTION statement in the DIALOG statement must be a character string, enclosed in double quotation marks (").


F

File not found: filename
The file specified in the rc command was not found. Make sure that the file has not been moved to another directory and that the filename or path is typed correctly.
Font names must be ordinals
The pointsize parameter in the FONT statement must be an integer, not a string.


I

Invalid Accelerator
An event parameter in the ACCELERATORS statement was not recognized or was more than two characters long.
Invalid Accelerator Type (ASCII or VIRTKEY)
The type parameter in the ACCELERATORS statement must contain either the ASCII or VIRTKEY value.
Invalid control character
A control character in the ACCELERATORS statement is invalid. A valid control character consists of a caret (^) followed by a single letter.
Invalid Control type
The control statement in a DIALOG statement must be one of the following: AUTO3STATE, AUTOCHECKBOX, AUTORADIOBUTTON, CHECKBOX, COMBOBOX, CONTROL, CTEXT, DEFPUSHBUTTON, EDITTEXT, GROUPBOX, ICON, LISTBOX, LTEXT, PUSHBOX, PUSHBUTTON, RADIOBUTTON, RTEXT, SCROLLBAR, STATE3.
Invalid directive in preprocessed RC file
The specified filename has an embedded newline character.
Invalid .EXE file
The executable (.EXE) file is invalid. Make sure that the linker created it correctly and that the file exists.
Invalid switch, option
An option used was invalid. For a list of the command-line options, use the rc /? command.
Invalid switch, too many -D switches
Too many -d options were specified. To define a large number of symbols, use the #include directive to include a file of definitions.
Invalid type
The resource type was not among the types defined in the include file.
Invalid usage. Use RC -? for Help
Make sure that you have at least one filename to work with. For a list of the command-line options, use the rc -? command.
I/O error reading file
Read failed. Since this is a generic routine, no specific filename is supplied.
I/O error seeking in file
Seeking in file failed. Since this is a generic routine, no specific filename is supplied.
I/O error writing file
Write failed. Since this is a generic routine, no specific filename is supplied.


N

No resource binary filename specified.
The /fo option was used, but no binary resource (.RES) file was specified.


O

Old DIB in resource-name. Pass it through IMAGEDIT.
The resource file specified is not compatible with Win32. Make sure you have read and saved this file using the latest version of Microsoft Image Editor (IMAGEDIT.EXE).
Out of heap memory
There was not enough memory.
Out of memory, needed n bytes
Microsoft Windows 32 Resource Compiler (RC) was not able to allocate the specified amount of memory.


R

Redefinition of Button Type
The specified button styles conflict with or modify the style specified by the control keyword. This is a warning only and may be ignored.

The following common method of declaring an automatic radio button generates this warning:

RADIOBUTTON "&Italic", MYRB_ITALIC, 10, 10, 30, 12, BS_AUTORADIOBUTTON

To avoid the warning, use the control statement appropriate for the type of button that you want to define. In this example, the corrected statement is:

AUTORADIOBUTTON "&Italic", MYRB_ITALIC, 10, 10, 30, 12
RC: Invalid switch: option
An option used was invalid. For a list of the command-line options, use the rc /? command.
RC: RCPP.ERR not found
The RCPP.ERR file must be in the current directory or in a directory specified in the PATH environment variable.
RC terminated by user
A CTRL+C key combination was pressed, exiting Microsoft Windows 32 Resource Compiler (RC).
RC terminating after preprocessor errors
For information about preprocessor errors, see the documentation for the preprocessor.
Resource file resource-name is not in version-number format.
Make sure your icons and cursors have been read and saved using the latest version of Microsoft Image Editor (IMAGEDIT.EXE).


T

Text string or ordinal expected in Control
The text parameter of a CONTROL statement in the DIALOG statement must be either a text string or an ordinal reference to the type of control that is expected. If using an ordinal, make sure that you have a #define statement for the control.


U

Unable to create destination
Microsoft Windows 32 Resource Compiler (RC) was not able to create the destination file. Make sure that there is enough disk space.
Unbalanced Parentheses
Make sure that you have closed every opening parenthesis in the DIALOG statement.
Unexpected value in RCData
The values for the raw-data parameter in the RCDATA statement must be integers or strings, separated by commas. Make sure that you did not leave out a comma or a quotation mark around a string.
Unexpected value in value data
A statement contained information with a format or size different from the expected value for that parameter.
Unknown DIB header format
The device-independent bitmap (DIB) header is not a BITMAPCOREHEADER or BITMAPINFOHEADER structure.
Unknown Menu SubType
The item-definitions parameter of the MENU statement can contain only MENUITEM and POPUP statements.
Unrecognized VERSIONINFO field; BEGIN or comma expected
The format of the information following a VERSIONINFO statement is incorrect.


V

Version WORDs separated by commas expected
Values in an information block for a VERSIONINFO statement should be separated by commas.


W

Warning: ASCII character not equivalent to virtual key code
An invalid virtual-key code exists in the ACCELERATORS statement. The ASCII values for some characters such as *, ^, or & are not equivalent to the virtual-key codes for the corresponding keys. In the case of the asterisk (*), the virtual-key code is equivalent to the ASCII value for 8, the numeric character on the same key. Therefore, the statement VIRTKEY '*' is invalid.
Warning: SHIFT or CONTROL used without VIRTKEY
The ALT, SHIFT, and CONTROL options apply only to virtual keys in the ACCELERATORS statement. Make sure that the VIRTKEY option is used with one of these other options.
Writing resource type image lang:language size:size
(V) Microsoft Windows 32 Resource Compiler (RC) is writing the specified resource. The type is the resource type. It may be a number or a string. The image can be a number or a string. The language is the national language of the resource. The size is the decimal size of the resource in bytes.


Localizing Resources

The Platform SDK includes several utilities that are useful for localizing resources. This overview covers the following topics:

  • Converting to and from Unicode Text with UCONVERT
  • Automating Localization with RLMAN


Converting to and from Unicode Text with UCONVERT

To convert a file to Unicode from an ANSI, OEM, or other code page, use the Unicode Converter (UCONVERT). To perform the conversion, use the following steps:

  • Click Open Source File on the File menu. Specify the file you want to convert.
  • Click Convert Now on the Conversion menu.
  • Click Save As from the File menu. Specify a filename for the converted file.

You can use the Conversion menu to specify conversion options. For more information, see the help file UCONVERT.HLP, included with the Unicode Converter.


Automating Localization with RLMAN

The Resource Localization Manager (RLMAN) was designed to automate localization of products that make use of the Windows resource model. You can extract resources directly from the applications that use them, modify the resources, and use the modified resources to create localized versions of the original applications. This allows you to localize your product without recompilation, and share glossaries of common terms among your applications.

When resource files are localized as they are developed, they may change after you have already begun translation. RLMAN uses update tracking to allow you to update the localized file without losing any work that you have already done. Any resources that have changed since your most recent update are marked, and the change is tracked so you can see what has changed and exactly how it changed. RLMAN uses a master token file to track changes and update token files for each target language. These token files are used to generate the target resource files.

The RLMAN command-line syntax is as follows:

rlman [-c RDFile] [-p CodePage] [-f ResType] [-{n|o} PriLang SubLang] [-w] [-x] -{e|t|m|l|r|a} files

-c RDFile
Use custom resources defined in the resource description file RDFile.
-p CodePage
The code page used in the conversion. The default is the Windows ANSI code page.
-f ResType
Extract a single resource type, defined by the resource type ResType.
-n PriLang SubLang
Specifies the language of the tokens in the token file. Used when setting up a new language project (-l) and with the -r and -a switches
-o PriLang SubLang
Specifies the language of the resources being replaced, or extracted from the resource file.
-w
Print warnings about unknown custom resource types.
-x
Use the extended token file format.
-e InputExeFile OutputResFile
Extract resources from the source file (.EXE, .DLL, .CPL, and so forth) InputExeFile, and create a resource file OutputResFile.
-t InputResOrExeFile OutputTokenFile
Extract the resources from InputResOrExeFile and create a project token file OutputTokenFile. This option circumvents the history-keeping mechanism. It is intended to simply view the resources or for one-time localization.
-m MasterProjectFile [InputResOrExeFile MasterTokenFile]
If the MasterProjectFile does not exist, InputResOrExeFile and MasterTokenFile must be provided.
-l LanguageProjectFile [MasterProjectFile LanguageTokenFile]
Create a new localization project or update an existing one. If LanguageProjectFile does not exist, you must provide the MasterProjectFIle (created with -m) and LanguageTokenFile.
-r InputResOrExeFile LanguageTokenFileOrResFile OutputResOrExeFile
The resources in InputResOrExeFile are replaced with the localized resource in LanguageTokenFileOrResFile. OutputResOrExeFile is the localized version. If LanguageTokenFileOrResFile is a token file, use -o to specify the old language and -n to specify the new language.
-a InputResOrExeFile LanguageTokenFileOrResFile OutputResOrExeFile
The resource in the resulting OutputResOrExeFile includes the original resource from InputResOrExeFile, plus the localized resources in LanguageTokenFileOrResFile. If LanguageTokenFileOrResFile is a token file, use -n to specify the new language.

For more information, see the help file RLMAN.HLP included with the Resource Localization Manager.


Raw Input

[This is preliminary documentation and subject to change.]

This overview describes how the system provides raw input to your application and how an application receives and processes that input.

  • About Raw Input
  • Using Raw Input
  • Raw Input Reference


About Raw Input

[This is preliminary documentation and subject to change.]

There are many user-input devices beside the traditional keyboard and mouse. For example, user input can come from a joystick, a touch screen, a microphone, or other devices that allow great flexibility in user input. These devices are collectively known as Human Input Devices (HID). With Whistler, Microsoft introduces the raw input APIs to provide a stable and robust way for applications to accept raw input from any HID, including the keyboard and mouse.

This section covers the following topics:

  • Raw Input Model
  • Registration for Raw Input
  • Reading Raw Input


Raw Input Model

[This is preliminary documentation and subject to change.]

Previously, the keyboard and mouse typically generated input data. The system interpreted the data coming from these devices in a way that eliminated the device-specific details of the raw information. For example, the keyboard generates the device-specific scan code but the system provides an application with the virtual key code. Besides hiding the details of the raw input, the window manager did not support all the new HID devices. To get input from the unsupported HID devices, an application had to do many things: open the device, manage the shared mode, periodically read the device or set up the I/O completion port, and so forth. The raw input model and the associated APIs were developed to allow simple access to raw input from all input devices, including the keyboard and mouse.

The raw input model is different from the original Microsoft® Windows® input model for the keyboard and mouse. In the original input model, an application receives device-independent input in the form of messages that are sent or posted to its windows, such as WM_CHAR, WM_MOUSEMOVE, and WM_APPCOMMAND. In contrast, for raw input an application must register the devices it wants to get data from. Also, the application gets the raw input through the WM_INPUT message.

There are several advantages to the raw input model:

  • An application does not have to detect or open the input device.
  • An application gets the data directly from the device, and processes the data for its needs.
  • An application can distinguish the source of the input even if it is from the same type of device. For example, two mouse devices.
  • An application manages the data traffic by specifying data from a collection of devices or only specific device types.
  • HID devices can be used as they become available in the marketplace, without waiting for new message types or an updated OS to have new commands in WM_APPCOMMAND.

Note that WM_APPCOMMAND does provide for some HID devices. However, WM_APPCOMMAND is a higher level device-independent input event, while WM_INPUT sends raw, low level data that is specific to a device.


Registration for Raw Input

[This is preliminary documentation and subject to change.]

By default, no application receives raw input. To receive raw input from a device, an application must register the device.

To register the devices, an application first creates an array of RAWINPUTDEVICE structures that specify the top level collection (TLC) for the devices it wants. The TLC is defined by a Usage Page (the class of the device) and a Usage (the device within the class). For example, to get the keyboard TLC, set UsagePage = 1 and Usage = 6. The application calls RegisterRawInputDevices to register the devices.

Note that an application can register a device that is not currently attached to the system. When this device is attached, the Window Manager will automatically send the raw input to the application. To get the list of raw input devices on the system, an application calls GetRawInputDeviceList. Using the hDevice from this call, an application calls GetRawInputDeviceInfo to get the device information.

Through the dwFlags member of RAWINPUTDEVICE, an application can select the devices to listen to and also those it wants to ignore. For example, an application can ask for input from all telephony devices except for answering machines. For sample code, see Registering for Raw Input.

Note that the mouse and the keyboard are also HID devices, so data from them can come through both the HID message WM_INPUT and from traditional messages. An application can select either method by the proper selection of flags in RAWINPUTDEVICE.

To get an application's registration status, call GetRegisteredRawInputDevices at any time.


Reading Raw Input

[This is preliminary documentation and subject to change.]

An application receives raw input from any device whose top level collection (TLC) matches a TLC from the registration. When an application receives raw input, its message queue gets a WM_INPUT message and the queue status flag QS_RAWINPUT is set (QS_INPUT also includes this flag). An application can receive data when it is in the foreground and when it is in the background.

There are two ways to read the raw data: the unbuffered method and the buffered method. The unbuffered method gets the raw data one RAWINPUT structure at a time and is adequate for many HID devices. Here, the application calls GetMessage to get the WM_INPUT message. Then the application calls GetRawInputData using the RAWINPUT handle contained in WM_INPUT.

In contrast, the buffered method gets an array of RAWINPUT structures at a time. This is provided for devices that can produce large amounts of raw input. In this method, the application calls GetRawInputBuffer to get an array of RAWINPUT structures. Note that the NEXTRAWINPUTBLOCK macro is used to traverse an array of RAWINPUT structures.

To interpret the raw input, detailed information about the HID device is required. An application gets the device information by calling GetRawInputDeviceInfo with the device handle. This handle can come either from WM_INPUT or from RAWINPUTHEADER .hDevice.


Using Raw Input

[This is preliminary documentation and subject to change.]

This section includes sample code for the following purposes:

Registering for Raw Input


Registering for Raw Input

[This is preliminary documentation and subject to change.]

Example #1: In this sample, an application specifies the raw input from game controllers (both game pads and joysticks) and all devices off the telephony usage page except answering machines.

RAWINPUTDEVICE Rid[4];

Rid[0].usUsagePage = 01h;
Rid[0].usUsage = 05h;
Rid[0].dwFlags = 0;                 // adds game pad

Rid[1].usUsagePage = 01h;
Rid[1].usUsage = 04h;
Rid[1].dwFlags = 0;                 // adds joystick

Rid[2].usUsagePage = 0Bh;
Rid[2].usUsage = 00h;
Rid[2].dwFlags = RIDEV_PAGEONLY;    //adds devices from telephony page
Rid[3].usUsagePage = 0Bh;
Rid[3].usUsage = 02h;
Rid[3].dwFlags = RIDEV_EXCLUDE;     //excludes answering machines

if (RegisterRawInputDevices(Rid, 4, sizeof(Rid[0])) == FALSE) {
    //registration failed. Call GetLastError for the cause of the error.
}

Example #2: In this sample, an application wants raw input from the keyboard and mouse but wants to ignore legacy window messages (which would come from the same keyboard and mouse).

RAWINPUTDEVICE Rid[2];

Rid[0].usUsagePage = 01h;
Rid[0].usUsage = 02h;
Rid[0].dwFlags = RIDEV_NOLEGACY;   // adds HID mouse and also ignores legacy mouse messages

Rid[1].usUsagePage = 01h;
Rid[1].usUsage = 06h;
Rid[1].dwFlags = RIDEV_NOLEGACY;   // adds HID keyboard and also ignores legacy keyboard messages

if (RegisterRawInputDevices(Rid, 2, sizeof (RID [0])) == FALSE) {
    //registration failed. Call GetLastError for the cause of the error
}


Raw Input Reference

[This is preliminary documentation and subject to change.]

The following elements are associated with keyboard input:

  • Raw Input Functions
  • Raw Input Structures
  • Raw Input Macros
  • Raw Input Messages


Raw Input Functions

[This is preliminary documentation and subject to change.]

The following functions are used to receive and process raw input.

Function | Description
DefRawInputProc | Provides default raw input processing for bulk-read (buffered-read) raw input.
GetRawInputBuffer | Does a buffered read of raw input.
GetRawInputData | Does an unbuffered read of raw input.
GetRawInputDeviceInfo | Gets info about a raw input device.
GetRawInputDeviceList | Enumerates the raw input devices.
GetRegisteredRawInputDevices | Gets information about the raw input devices for the current application.
RegisterRawInputDevices | Registers raw input devices.


DefRawInputProc

[This is preliminary documentation and subject to change.]

The DefRawInputProc function calls the default raw input procedure to provide default processing for any raw input messages that an application does not process. This function ensures that every message is processed. DefRawInputProc is called with the same parameters received by the window procedure.

LRESULT WINAPI DefRawInputProc (
  PRAWINPUT * paRawInput,
  INT         nInput,
  UINT        cbSizeHeader
);

Parameters

paRawInput
[in] Pointer to an array of RAWINPUT structures.
nInput
[in] Number of RAWINPUT structures pointed to by paRawInput.
cbSizeHeader
[in] Size, in bytes, of the RAWINPUTHEADER structure.

Return Values

If successful, the function returns S_OK. Otherwise it returns an error value.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Raw Input Overview, Raw Input Functions, RAWINPUT , RAWINPUTHEADER


GetRawInputBuffer

[This is preliminary documentation and subject to change.]

The GetRawInputBuffer function does a buffered read of the raw input data.

UINT WINAPI GetRawInputBuffer(
  PRAWINPUT  pData,
  PUINT    pcbSize,
  UINT     cbSizeHeader
);

Parameters

pData
[out] Pointer to a buffer of RAWINPUT structures that contain the raw input data. If NULL, the minimum required buffer, in bytes, is returned in *pcbSize.
pcbSize
[in/out] Pointer to a UINT that contains the size, in bytes, of a RAWINPUT structure.
cbSizeHeader
[in] Size, in bytes, of RAWINPUTHEADER.

Return Values

If pData is NULL and the function is successful, the return value is zero. If pData is not NULL and the function is successful, the return value is the number of RAWINPUT structures written to pData.

If an error occurs, the return value is (UINT)-1. Call GetLastError for the error code.

Remarks

Using GetRawInputBuffer, the raw input data is buffered in the array of RAWINPUT structures. For an unbuffered read, use the GetMessage function to read in the raw input data.

The NEXTRAWINPUTBLOCK macro allows an application to traverse an array of RAWINPUT structures.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Raw Input Overview, Raw Input Functions, GetMessage , RAWINPUT , RAWINPUTHEADER, NEXTRAWINPUTBLOCK


GetRawInputData

[This is preliminary documentation and subject to change.]

The GetRawInputData function gets the raw input from the specified device.

UINT WINAPI GetRawInputData(
  HRAWINPUT hRawInput,
  UINT      uiCommand,
  LPVOID    pData,
  PUINT     pcbSize,
  UINT      cbSizeHeader,
);

Parameters

hRawInput
[in] Handle to the RAWINPUT structure. This comes from the lParam in WM_INPUT.
uiCommand
[in] Command flag. It can be one of the following values.
Value | Meaning
RID_INPUT | Get the raw data from the RAWINPUT structure.
RID_HEADER | Get the header information from the RAWINPUT structure.

pData
[out] Pointer to the data that comes from the RAWINPUT structure. This depends on the value of uiCommand. If pData is NULL, the required size of the buffer is returned in *pcbSize.
pcbSize
[in/out] Pointer to a UINT that contains the size, in bytes, of the data that pData points to.
cbSizeHeader
[in] Size, in bytes, of RAWINPUTHEADER.

Return Values

If pData is NULL and the function is successful, the return value is 0. If pData is not NULL and the function is successful, the return value is the number of bytes copied into pData.

If there is an error, the return value is (UINT)-1.

Remarks

GetRawInputData gets the raw input one RAWINPUT structure at a time. In contrast, GetRawInputBuffer gets an array of RAWINPUT structures.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Raw Input Overview, Raw Input Functions, GetRawInputBuffer, RAWINPUT, RAWINPUTHEADER


GetRawInputDeviceInfo

[This is preliminary documentation and subject to change.]

The GetRawInputDeviceInfo function gets information about the raw input device.

UINT WINAPI GetRawInputDeviceInfo(
  HANDLE  hDevice,
  UINT    uiCommand,
  LPVOID  pData,
  PUINT   pcbSize
);

Parameters

hDevice
[in] Handle to the raw input device. This comes from the lParam of the WM_INPUT message or from RAWINPUTHEADER .hDevice.
uiCommand
[in] Specifies what data will be returned in pData. It can be one of the following values.
Value | Meaning
RIDI_PREPARSEDDATA | pData points to the previously parsed data.
RIDI_DEVICENAME pData points to a string that contains the device name.

For this uiCommand only, the value in pcbSize is the character count (not the byte count).
RIDI_DEVICEINFO | pData points to an RID_DEVICE_INFO structure.

pData
[out] Pointer to a buffer that contains the information specified by uiCommand.
pcbSize
[in/out] Pointer to a UINT that contains the size, in bytes, of the data in pData.

Return Values

If successful, this function returns a non-negative number indicating the number of bytes copied to pData.

If pData is not large enough for the data, the function returns -1. If pData is NULL, the function returns a value of zero. In both of these cases, pcbSize is set to the minimum size required for the pData buffer.

Call GetLastError to identify any other errors.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Raw Input Overview, Raw Input Functions, RAWINPUTHEADER, RID_DEVICE_INFO , WM_INPUT,


GetRawInputDeviceList

[This is preliminary documentation and subject to change.]

The GetRawInputDeviceList function enumerates the raw input devices attached to the system.

UINT WINAPI GetRawInputDeviceList(
  PRAWINPUTDEVICELIST  pRawInputDeviceList,
  PUINT        puiNumDevices,
  UINT         cbSize
);

Parameters

pRawInputDeviceList
[out] Pointer to buffer that holds an array of RAWINPUTDEVICELIST structures for the devices attached to the system. If NULL, the number of devices are returned in *puiNumDevices.
puiNumDevices
[in/out] Pointer to a UINT. If pRawInputDeviceList is NULL, this is the number of devices attached to the system. Otherwise, it contains the size, in bytes, of the preallocated buffer pointed to by pRawInputDeviceList. However, if *puiNumDevices is smaller than needed to contain RAWINPUTDEVICELIST structures, the required buffer size is returned here.
cbSize
[in] The size of a RAWINPUTDEVICELIST structure.

Return Values

If the function is successful, the return value is the number of devices stored in the buffer pointed to by pRawInputDeviceList.

If pRawInputDeviceList is NULL, the return value is zero.

If *puiNumDevices is smaller than needed to contain all the RAWINPUTDEVICELIST structures, the return value is (UINT) -1 and the required buffer is returned in *puiNumDevices. Calling GetLastError returns ERROR_INSUFFICIENT_BUFFER.

On any other error, the function returns (UINT) -1 and GetLastError returns the error indication.

Remarks

The devices returned from this function are the mouse, the keyboard, and other HID devices.

To get more detailed information about the attached devices, call GetRawInputDeviceInfo using the hDevice from RAWINPUTDEVICELIST. The following sample code shows a typical call to RawInputDeviceList:

UINT nDevices;
PRAWINPUTDEVICELIST pRawInputDeviceList;

if (GetRawInputDeviceList(NULL, &nDevices) != 0) { Error();}
if ((pRawInputDeviceList = malloc(sizeof(PRAWINPUTDEVICELIST) * nDevices)) == NULL) {Error();}
if (GetRawInputDevices(pRawInputDevices(pRawInputDeviceList, &nDevices) == (UINT)-1) {Error();}
// do the job...

// after the job, free the RAWINPUTDEVICE
free(pRawInputDeviceList);

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Raw Input Overview, Raw Input Functions, GetRawInputDeviceInfo, RAWINPUTDEVICELIST


GetRegisteredRawInputDevices

[This is preliminary documentation and subject to change.]

The GetRegisteredRawInputDevices function gets the information about the raw input devices for the current application.

UINT WINAPI GetRegisteredRawInputDevices(
  PRAWINPUTDEVICE  pRawInputDevices,
  PUINT        puiNumDevices,
  UINT        cbSize
);

Parameters

pRawInputDevices
[out] Pointer to an array of RAWINPUTDEVICE structures for the application.
puiNumDevices
[in/out] Number of RAWINPUTDEVICE structures in *pRawInputDevices.
cbSize
[in] Size, in bytes, of a RAWINPUTDEVICE structure.

Return Values

If successful, the function returns a non-negative number that is the number of RAWINPUTDEVICE structures written to the buffer.

If the pRawInputDevices buffer is too small, the function returns -1 and sets cbSize to the minimum buffer size required for the registration structures. If the function fails for any other reason, it returns -1. Call GetLastError for more details.

Remarks

To receive raw input from a device, an application must register it by using RegisterRawInputDevices.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Raw Input Overview, Raw Input Functions, RegisterRawInputDevices, RAWINPUTDEVICE


RegisterRawInputDevices

[This is preliminary documentation and subject to change.]

The RegisterRawInputDevices function registers the devices that supply the raw input data.

BOOL WINAPI RegisterRawInputDevices(
  PCRAWINPUTDEVICE  pRawInputDevices,
  UINT        uiNumDevices,
  UINT        cbSize
);

Parameters

pRawInputDevices
[in] Pointer to an array of RAWINPUTDEVICE structures for the devices that supply the raw input.
uiNumDevices
[in] Number of RAWINPUTDEVICE structures pointed to by pRawInputDevices.
cbSize
[in] Size, in bytes, of a RAWINPUTDEVICE structure.

Return Values

If the function succeeds, it returns TRUE. Otherwise it returns FALSE. If the function fails, call GetLastError for more information.

Remarks

To receive WM_INPUT messages, an application must first register the raw input devices using RegisterRawInputDevices. By default, an application does not receive raw input.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Raw Input Overview, Raw Input Functions, RAWINPUTDEVICE, WM_INPUT


Raw Input Structures

[This is preliminary documentation and subject to change.]

The following structures are used for raw input.

RAWHID
RAWINPUT
RAWINPUTDEVICE
RAWINPUTDEVICELIST
RAWINPUTHEADER
RAWKEYBOARD
RAWMOUSE
RID_DEVICE_INFO
RID_DEVICE_INFO_HID
RID_DEVICE_INFO_KEYBOARD
RID_DEVICE_INFO_MOUSE


RAWHID

[This is preliminary documentation and subject to change.]

The RAWHID structure describes the format of the raw input from a Human Input Device (HID).

typedef struct tagRAWHID {
  DWORD    dwSizeHid;
  DWORD    dwCount;
  BYTE     bRawData[1];
} RAWHID, *PRAWHID; *LPRAWHID;

Members

dwSizeHid
Specifies the size, in bytes, of each HID input in bRawData.
dwCount
Specifies the number of HID inputs in bRawData.
bRawData
The raw input data as an array of bytes.

Remarks

Each WM_INPUT can indicate several inputs, but all of the inputs come from the same HID. The size of the bRawData array is dwSizeHid * dwCount.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Raw Input Overview, Raw Input Structures, RAWINPUT, WM_INPUT


RAWINPUT

[This is preliminary documentation and subject to change.]

The RAWINPUT structure contains the raw input from a device.

typedef struct tagRAWINPUT {
  RAWINPUTHEADER    header;
  union {
      RAWMOUSE    mouse;
      RAWKEYBOARD keyboard;
      RAWHID      hid;
  } data;
} RAWINPUT, *PRAWINPUT; *LPRAWINPUT;

Members

header
The RAWINPUTHEADER structure for the raw input data.
mouse
If the data comes from a mouse, this is the RAWMOUSE structure for the raw input data.
keyboard
If the data comes from a keyboard, this is the RAWKEYBOARD structure for the raw input data.
hid
If the data comes from an HID, this is the RAWHID structure for the raw input data.

Remarks

The handle to this structure is passed in the lParam parameter of WM_INPUT.

To get detailed information -- such as the header and the content of the raw input -- call GetRawInputData.

To read the RawInput in the message loop as a buffered read, call GetRawInputBuffer.

To get device specific information, call GetRawInputDeviceInfo with the hDevice from RAWINPUTHEADER.

Raw input is available only when the application calls RegisterRawInputDevices with valid device specifications.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Raw Input Overview, Raw Input Structures, GetRawInputBuffer, GetRawInputData, RAWHID, RAWINPUTHEADER, RAWKEYBOARD, RAWMOUSE


RAWINPUTDEVICE

[This is preliminary documentation and subject to change.]

The RAWINPUTDEVICE structure defines information for the raw input devices.

typedef struct tagRAWINPUTDEVICE {
  USHORT    usUsagePage;   // top level collection UsagePage
  USHORT    usUsage;       // top level collection Usage
  DWORD     dwFlags;
  HWND      hwndTarget;    // target hwnd
} RAWINPUTDEVICE, *PRAWINPUTDEVICE, *LPRAWINPUTDEVICE;

Members

usUsagePage
Top level collection UsagePage for the raw input device.
usUsage
Top level collection Usage for the raw input device.
dwFlags
Mode flag that tells how to interpret the information provided by usUsagePage and usUsage. It can be zero (the default) or one of the following values. By default, the operating system sends raw input from devices with the specified TLC to the registered application as long as it has the window focus.
Value | Meaning
RIDEV_CAPTUREMOUSE | If set, the mouse button click does not activate the other window.
RIDEV_EXCLUDE | If set, this specifies the top level collections to exclude when reading a complete usage page. This flag only affects a TLC whose usage page is already specified with RIDEV_PAGEONLY.
RIDEV_NODEFSYSKEYS | If set, the system will not handle the ALT+TAB keystroke combination. By default the system handles this combination.
RIDEV_NOLEGACY | If set, this prevents any devices specified by usUsagePage or usUsage from generating legacy messages. This is only for the mouse and keyboard. See Remarks.
RIDEV_PAGEONLY If set, this specifies all devices whose top level collection is from the specified usUsagePage. Note that usUsage must be zero.

To exclude a particular top level collection, use RIDEV_EXCLUDE.
RIDEV_REMOVE | If set, this removes the top level collection from the inclusion list. This tells the operating system to stop reading from a device which matches the top level collection.

hwndTarget
Handle to the target device. If NULL, it follows the keyboard focus.

Remarks

If RIDEV_NOLEGACY is set for a mouse or a keyboard, the system does not generate any legacy message for that device for the application. For example, if the mouse TLC is set with RIDEV_NOLEGACY, WM_KEYDOWN, WM_LBUTTONDOWN, and so forth are not generated.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Raw Input Overview, Raw Input Structures, GetRegisteredRawInputDevices, RegisterRawInputDevices


RAWINPUTDEVICELIST

[This is preliminary documentation and subject to change.]

The RAWINPUTDEVICELIST structure contains information about a raw input device.

typedef struct tagRAWINPUTDEVICELIST {
  HANDLE    hDevice;
  DWORD     dwType;
} RAWINPUTDEVICELIST, *PRAWINPUTDEVICELIST;

Members

hDevice
[out] Handle to the raw input device.
dwType
[out] The type of device. This can be one of the following values.
Value | Meaning
RIM_TYPEHID | The device is an HID that is not a keyboard and not a mouse.
RIM_TYPEKEYBOARD | The device is a keyboard.
RIM_TYPEMOUSE | The device is a mouse.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Raw Input Overview, Raw Input Structures, GetRawInputDeviceList


RAWINPUTHEADER

[This is preliminary documentation and subject to change.]

The RAWINPUTHEADER structure contains the header information that is part of the raw input data.

typedef struct tagRAWINPUTHEADER {
  DWORD    dwType;
  DWORD    dwSize;
  HANDLE   hDevice;
  WPARAM   wParam
} RAWINPUTHEADER, *PRAWINPUTHEADER;

Members

dwType
Specifies the type of raw input. It can be one of the following values.
Value | Meaning
RIM_TYPEHID | Raw input comes from some device that is not a keyboard or a mouse.
RIM_TYPEKEYBOARD | Raw input comes from the keyboard.
RIM_TYPEMOUSE | Raw input comes from the mouse.

dwSize
Specifies the size, in bytes, of RAWINPUTHEADER
hDevice
Handle for the device generating the raw input data.
wParam
Reserved.

Remarks

To get more information on the device, use hDevice in a call to GetRawInputDeviceInfo.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Raw Input Overview, Raw Input Structures, GetRawInputDeviceInfo, RAWINPUT


RAWKEYBOARD

[This is preliminary documentation and subject to change.]

The RAWKEYBOARD structure contains information about the state of the keyboard.

typedef struct tagRAWKEYBOARD {
  USHORT    MakeCode;
  USHORT    Flags;
  USHORT    Reserved;
  USHORT    VKey;
  UINT      Message;
  ULONG     ExtraInformation;
} RAWKEYBOARD, *PRAWKEYBOARD, *LPRAWKEYBOARD;

Members

MakeCode
The "make" scan code (key depression).
Flags
Flags for scan code information. It can be one or more of the following.

RI_KEY_MAKE

RI_KEY_BREAK

RI_KEY_E0

RI_KEY_E1

RI_KEY_TERMSRV_SET_LED

RI_KEY_TERMSRV_SHADOW

Reserved
Reserved; must be zero.
VKey
Windows message compatible virtual key code.
Message
Corresponding window message, for example WM_KEYDOWN, WM_SYSKEYDOWN, and so forth.
ExtraInformation
Device-specific additional information for the event.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Raw Input Overview, Raw Input Structures, GetRawInputDeviceInfo, RAWINPUT


RAWMOUSE

[This is preliminary documentation and subject to change.]

The RAWMOUSE structure contains information about the state of the mouse.

typedef struct tagRAWMOUSE {
  USHORT    usFlags;
  union {
      ULONG    ulButtons;
      struct {
          USHORT usButtonFlags;
          USHORT usButtonData;
      };
  };
  ULONG ulRawButtons;
  LONG  lLastX;
  LONG  lLastY;
  ULONG ulExtraInformation;
} RAWMOUSE, *PRAWMOUSE, *LPRAWMOUSE;

Members

usFlags
Indicators for the mouse state. It can be one or more of the following.
Value | Meaning
MOUSE_ATTRIBUTES_CHANGED | Mouse attributes changed; application needs to query the mouse attributes.
MOUSE_MOVE_RELATIVE | Mouse movement data is relative to the last mouse position.
MOUSE_MOVE_ABSOLUTE | Mouse movement data is based on absolute position.
MOUSE_VIRTUAL_DESKTOP | Mouse coordinates are mapped to the virtual desktop (for a multiple monitor system).

ulButtons
Reserved.
usButtonFlags
Specifies the transition state of the mouse buttons. It can be one or more of the following values.
Value | Meaning
RI_MOUSE_LEFT_BUTTON_DOWN | Left button changed to down.
RI_MOUSE_LEFT_BUTTON_UP | Left button changed to up.
RI_MOUSE_MIDDLE_BUTTON_DOWN | Middle button changed to down.
RI_MOUSE_MIDDLE_BUTTON_UP | Middle button changed to up.
RI_MOUSE_RIGHT_BUTTON_DOWN | Right button changed to down.
RI_MOUSE_RIGHT_BUTTON_UP | Right button changed to up.
RI_MOUSE_BUTTON_1_DOWN | RI_MOUSE_LEFT_BUTTON_DOWN
RI_MOUSE_BUTTON_1_UP | RI_MOUSE_LEFT_BUTTON_UP
RI_MOUSE_BUTTON_2_DOWN | RI_MOUSE_RIGHT_BUTTON_DOWN
RI_MOUSE_BUTTON_2_UP | RI_MOUSE_RIGHT_BUTTON_UP
RI_MOUSE_BUTTON_3_DOWN | RI_MOUSE_MIDDLE_BUTTON_DOWN
RI_MOUSE_BUTTON_3_UP | RI_MOUSE_MIDDLE_BUTTON_UP
RI_MOUSE_BUTTON_4_DOWN | XBUTTON1 changed to down. See XBUTTONs.
RI_MOUSE_BUTTON_4_UP | XBUTTON1 changed to up. See XBUTTONs.
RI_MOUSE_BUTTON_5_DOWN | XBUTTON2 changed to down. See XBUTTONs.
RI_MOUSE_BUTTON_5_UP | XBUTTON2 changed to up. See XBUTTONs.
RI_MOUSE_WHEEL | Raw input comes from a mouse wheel. The wheel delta is stored in usButtonData.

usButtonData
If usButtonFlags is RI_MOUSE_WHEEL, the wheel delta is stored here. It is a signed value.
ulRawButtons
The raw state of the mouse buttons.
lLastX
The motion in the X direction. This is signed relative motion or absolute motion, depending on the value of usFlags.
lLastY
The motion in the Y direction. This is signed relative motion or absolute motion, depending on the value of usFlags.
ulExtraInformation
Device-specific additional information for the event.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Raw Input Overview, Raw Input Structures, GetRawInputDeviceInfo, RAWINPUT


RID_DEVICE_INFO

[This is preliminary documentation and subject to change.]

The RID_DEVICE_INFO structure defines the raw input data coming from any device.

typedef struct tagRID_DEVICE_INFO {
  DWORD    cbSize;
  DWORD    dwType;
  union {
      RID_DEVICE_INFO_MOUSE     mouse;
      RID_DEVICE_INFO_KEYBOARD  keyboard;
      RID_DEVICE_INFO_HID       hid;
} RID_DEVICE_INFO, *PRID_DEVICE_INFO, *LPRID_DEVICE_INFO;

Members

cbSize
Size, in bytes, of the RID_DEVICE_INFO structure.
dwType
Type of raw input data. It can be one of the following values.
Value | Meaning
RIM_TYPEHID | Data comes from an HID that is not a keyboard or a mouse.
RIM_TYPEKEYBOARD | Data comes from a keyboard.
RIM_TYPEMOUSE | Data comes from a mouse.

mouse
If dwType is RIM_TYPEMOUSE, this is the RID_DEVICE_INFO_MOUSE structure that defines the mouse.
keyboard
If dwType is RIM_TYPEKEYBOARD, this is the RID_DEVICE_INFO_KEYBOARD structure that defines the keyboard.
hid
If dwType is RIM_TYPEHID, this is the RID_DEVICE_INFO_HID structure that defines the HID device.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Raw Input Overview, Raw Input Structures, GetRawInputDeviceInfo, RID_DEVICE_INFO_HID, RID_DEVICE_INFO_KEYBOARD, RID_DEVICE_INFO_MOUSE


RID_DEVICE_INFO_HID

[This is preliminary documentation and subject to change.]

The RID_DEVICE_INFO_HID structure defines the raw input data coming from the specified HID.

typedef struct tagRID_DEVICE_INFO_HID {
  DWORD    dwVendorId;
  DWORD    dwProductId;
  DWORD    dwVersionNumber;
  USHORT   usUsagePage;
  USHORT   usUsage;
} RID_DEVICE_INFO_HID, *PRID_DEVICE_INFO_HID;

Members

dwVendorId
Vendor ID for the HID.
dwProductId
Product ID for the HID.
dwVersionNumber
Version number for the HID.
usUsagePage
Top level collection Usage Page for the device.
usUsage
Top level collection Usage for the device.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Raw Input Overview, Raw Input Structures, RID_DEVICE_INFO


RID_DEVICE_INFO_KEYBOARD

[This is preliminary documentation and subject to change.]

The RID_DEVICE_INFO_KEYBOARD structure defines the raw input data coming from the specified keyboard.

typedef struct tagRID_DEVICE_INFO_KEYBOARD {
  DWORD    dwType;
  DWORD    dwSubType;
  DWORD    dwKeyboardMode;
  DWORD    dwNumberOfFunctionKeys;
  DWORD    dwNumberOfIndicators;
  DWORD    dwNumberOfKeysTotal;
} RID_DEVICE_INFO_KEYBOARD, *PRID_DEVICE_INFO_KEYBOARD;

Members

dwType
Type of the keyboard.
dwSubType
Subtype of the keyboard.
dwKeyboardMode
Scan code mode.
dwNumberOfFunctionKeys
Number of function keys on the keyboard.
dwNumberOfIndicators
Number of LED indicators on the keyboard.
dwNumberOfKeysTotal
Total number of keys on the keyboard.

Remarks

For the keyboard, the Usage Page is 1 and the Usage is 6.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Raw Input Overview, Raw Input Structures, RID_DEVICE_INFO


RID_DEVICE_INFO_MOUSE

[This is preliminary documentation and subject to change.]

The RID_DEVICE_INFO_MOUSE structure defines the raw input data coming from the specified mouse.

typedef struct tagRID_DEVICE_INFO_MOUSE {
  DWORD    dwId;
  DWORD    dwNumberOfButtons;
  DWORD    dwSampleRate;
} RID_DEVICE_INFO_MOUSE , *PRID_DEVICE_INFO_MOUSE;

Members

dwId
The ID for the mouse device.
dwNumberOfButtons
Number of buttons for the mouse.
dwSampleRate
Number of data points per second. This may not be applicable for every mouse device.

Remarks

For the keyboard, the Usage Page is 1 and the Usage is 2.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Raw Input Overview, Raw Input Structures, RID_DEVICE_INFO


Raw Input Macros

[This is preliminary documentation and subject to change.]

The following macros are used for raw input.

GET_RAWINPUT_CODE_WPARAM

NEXTRAWINPUTBLOCK


GET_RAWINPUT_CODE_WPARAM

[This is preliminary documentation and subject to change.]

The GET_RAWINPUT_CODE_WPARAM macro gets the input code from wParam in WM_INPUT.

WPARAM GET_RAWINPUT_CODE_WPARAM (
  WPARAM wParam
);

Parameters

wParam
wParam parameter from WM_INPUT.

Return Values

The return value is the input code for the raw input data. Currently, it can only the following value:

Value | Meaning
RIM_INPUT | Input occurred while the application was in the foreground. The application must call DefWindowProc so the system can perform cleanup.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Raw Input Overview, Raw Input Macros, RAWINPUT, WM_INPUT


NEXTRAWINPUTBLOCK

[This is preliminary documentation and subject to change.]

The NEXTRAWINPUTBLOCK macro gets the location of the next structure in an array of RAWINPUT structures.

PRAWINPUT NEXTRAWINPUTBLOCK (
  PRAWINPUT ptr
);

Parameters

ptr
Pointer to a structure in an array of RAWINPUT structures.

Return Values

The return value is a pointer to the next structure in the array of RAWINPUT structures.

Remarks

This macro is called repeatedly to traverse an array of RAWINPUT structures.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Raw Input Overview, Raw Input Macros, RAWINPUT


Raw Input Messages

[This is preliminary documentation and subject to change.]

The following messages are used for raw input.

WM_INPUT


WM_INPUT

[This is preliminary documentation and subject to change.]

The WM_INPUT message is sent to the window that is getting raw input.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_INPUT
  WPARAM wParam,   // not used
  LPARAM lParam    // handle to RAWINPUT structure
);

Parameters

wParam
Input code. Currently it can only be the following value.
Value | Meaning
RIM_INPUT | Input occurred while the application was in the foreground. The application must call DefWindowProc so the system can perform cleanup.

lParam
Handle to the RAWINPUT structure that contains the raw input from the device.

Return Values

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

Remarks

To get the wParam value, use the GET_RAWINPUT_CODE_WPARAM macro.

Note that lParam has the handle to the RAWINPUT structure, not a pointer to it. To get the raw data, use the handle in the call to GetRawInputData.

Raw input is available only when the application calls RegisterRawInputDevices with valid device specifications

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Raw Input Overview, Raw Input Messages, GetRawInputData, RegisterRawInputDevices, RAWINPUT, GET_RAWINPUT_CODE_WPARAM


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
  • Using Common Dialog Boxes
  • Common Dialog Box Reference


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, Print Property Sheet, 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.

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. For more information, see Color Dialog Box.
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. For more information, see Find and Replace Dialog Boxes.
Font | Displays lists of available fonts, point sizes, and other font attributes that the user can select. Use the ChooseFont function and CHOOSEFONT structure. For more information, see Font Dialog Box.
Open | Displays a dialog box in which the user can type or select the name of a file or shell name-space object to open. The dialog box includes lists of drives, directories, and shell name-space extensions that enable the user to browse the shell name-space. It also includes a list of file name extensions that enables the user to filter the file names displayed. Use the GetOpenFileName function and OPENFILENAME structure. For more information, see Open and Save As Dialog Boxes.
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. For more information, see Page Setup Dialog Box.
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. For more information, see Print Dialog Box.
Print Property Sheet | Windows 2000 or 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. For more information, see Print Property Sheet.
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. For more information, see Find and Replace Dialog Boxes.
Save As | Displays a dialog box in which the user can type or select the name with which to save a file or shell name-space object. The dialog box includes lists of drives, directories, and shell name-space extensions that enable the user to browse the shell name space. It also includes a list of file name extensions that enables the user to filter the file names displayed. Use the GetSaveFileName function and OPENFILENAME structure. For more information, see Open and Save As Dialog Boxes.

Note Although a Print Setup dialog box is also available, it has been superseded by the Page Setup dialog box. Applications written for Windows 95/98 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 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.

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 applications written for Windows 95/98 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.

Contants | 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 file name and clicks the OK button. The hook procedure can accept the file name, 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 is a pointer 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 File Name 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
Click the right mouse button over a control. | WM_CONTEXTMENU
Pressed the F1 key. | WM_HELP
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 Help.

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 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 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 specified 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 Color.dlg 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 file name filter, validating the user's input, and getting the file name 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 for Windows 2000. For earlier versions of Windows NT and Windows 95/98, the dialog box will be slightly different.

The following illustration shows a typical Explorer-style Save As dialog box for Windows 2000. For earlier versions of Windows NT and Windows 95/98, the dialog box will be slightly different.

If the user specifies a file name 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 file name 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/98/Me: 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.


File Names 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 file name. The nMaxFile member must specify the size, in TCHARs, of the lpstrFile buffer. For an ANSI function this is the number of bytes, but for a Unicode function this is the number of characters.

If the user specifies a file name and clicks the OK button, the dialog box copies the selected drive, directory, and file name to the lpstrFile buffer. The function also sets the nFileOffset and nFileExtension members to the offsets, in TCHARs, from the start of the buffer to the file name and to the file name extension, respectively.

To retrieve just the file name and extension, set the lpstrFileTitle member to point to a buffer and set the nMaxFileTitle member to the size, in TCHARs, 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 file name that GetFileTitle returns includes an extension only if that is the user's preference for displaying file names.

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 file name extension, use the lpstrDefExt member. If the user specifies a file name that does not have an extension, the dialog box adds your default extension. If you specify a default extension and the user specifies a file name 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 file names of the selected files. The nFileOffset member is the offset to the first file name, and the nFileExtension member is not used. The following table describes the difference between Explorer-style and old-style dialog boxes in returning multiple file names.

Dialog box style | Description
Explorer-style dialog boxes | The directory and file name strings are NULL separated, with an extra NULL character after the last file name. This format enables the Explorer-style dialog boxes to return long file names that include spaces.
Old-style dialog boxes | The directory and file name strings are separated by spaces. For file names with spaces, the function uses short file names.

You can use the FindFirstFile function to convert between long and short file names.

If you specify OFN_ALLOWMULTISELECT and the user selects only one file, the lpstrFile string does not have a separator between the path and file name.


Filters

The information in this section applies to both Explorer-style and old style Open and Save As dialog boxes.

You can provide file name filters to assist the user in limiting the file names that the dialog box displays. A file name 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 file name characters and the asterisk (*). The asterisk is a wildcard that represents any combination of valid file name 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. Note, in the C programming language, a string enclosed in double quotes is null-terminated.

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.

The CDN_INCLUDEITEM notification message provides another way to filter the names that the dialog box displays. To use this message, provide an OFNHookProc hook procedure and specify the OFN_ENABLEINCLUDENOTIFY flag in the OPENFILENAME structure when you create the dialog box. Each time the user opens a folder, the dialog box sends a CDN_INCLUDEITEM notification to your hook procedure for each item in the newly opened folder. The return value of the hook procedure indicates whether the dialog box should display the item in the folder's item list.


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 file names typed by the user to ensure that the names contain only valid characters. To override the file name 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 file name 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.

Windows 2000 or later: A user's HKEY_CURRENT_USER (HKCU) registry hive can contain values that customize the contents of the Explorer-style Open and Save As dialog boxes. These registry entries affect only the dialog boxes displayed for the user associated with the registry hive.

To hide features of Explorer-style Open and Save As dialog boxes, a user can set values under the following key.

HKCU\Software\Microsoft\Windows\CurrentVersion
    \Policies\Comdlg32
Value name | Value | Meaning
NoPlacesBar | 1 | Hides the places bar.
NoFileMRU | 1 | Hides the most-recently-used (MRU) list.
NoBackButton | 1 | Hides the back button.

The contents of the places bar are determined by the contents of the following key:

HKCU\Software\Microsoft\Windows\CurrentVersion
    \Policies\Comdlg32\Placesbar

Currently, there can only be five entries under this key, and the value-name index is zero based. The names for the entries should be Place0, Place1, Place2,Place3, and Place4. The values of the entries can be REG_DWORD, REG_SZ, and REG_EXPAND_SZ values that identify locations to include in the places bar.

Value type | Meaning
REG_DWORD | A CSIDL value that identifies a folder. For a list of CSIDL values, see the SHGetFolderLocation function.
REG_SZ or REG_EXPAND_SZ | A null-terminated string that specifies a valid path.


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 file name 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 or OFNOTIFYEX structure that defines the action. The code member in the header of this structure contains one of the following notification messages.

Message | Meaning
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_INCLUDEITEM | Determines whether an item should be displayed. When the user opens a new folder or directory, the system sends this notification for each item in the folder or directory. The system sends this notification only if the OFN_ENABLEINCLUDENOTIFY flag was set.
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.

Message | Meaning
CDM_GETFILEPATH | Retrieves the path and file name 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 file name (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 file name 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 dialog boxes 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
chx1 | The read-only check box
cmb1 | Drop-down combo box that displays the list of file type filters
stc2 | Label for the cmb1 combo box
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
cmb13 | Drop-down combobox that displays the name of the current file, allows the user to type the name of a file to open, and select a file that has been opened or saved recently.This is for earlier Explorer-compatible applications without hook or dialog template, or for Windows 2000 applications. Compare with edt1.
edt1 | Edit control that displays the name of the current file, or allows the user to type the name of the file to open. Compare with cmb13.
stc3 | Label for the cmb13 combo box and the edt1 edit control
lst1 | List box that displays the contents of the current drive or folder
stc1 | Label for the lst1 list 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 2000 or 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 selected. 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 selected. 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. To display information for another installed printer, initialize a DEVMODE and a DEVNAMES structure and assign the global memory handle for the structure to the hDevMode and hDevNames members. The device name you specify in the dmDeviceName member of the DEVMODE structure and 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 a handle to 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

The Print property sheet is a standard user interface that enables the user to specify the properties of a particular print job. 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 dialog box.

To create and display a Print property sheet, initialize a PRINTDLGEX structure and pass the structure to the PrintDlgEx function.

The following illustration shows the General page of a typical Print property sheet.

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

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. Typically, the custom template must be the same size as the default template. However, you can enlarge the custom template if you specify the PD_USELARGETEMPLATE flag to create a larger General page. 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

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 enters the margin settings.
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 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 a handle to 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, a handle to 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 selected, indicating that the user wants the search to be case sensitive. If FR_MATCHCASE is not set, the check box is unselected so that the search can be case insensitive.
FR_WHOLEWORD | If set, the Match Whole Word Only check box is selected, 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 unselected 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

This section covers tasks that invoke 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 array of COLORREF values. 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 is a pointer to a buffer that specifies two file name filters that the user can select to limit the file names 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 file name specified by the user actually exist.

The GetOpenFileName function returns TRUE if the user clicks the OK button and the specified path and file name exist. In this case, the buffer pointed to by the lpstrFile member contains the path and file name. 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. Note, in the C programming language, a string enclosed in double quotes is null-terminated.

OPENFILENAME ofn;       // common dialog box structure
char szFile[260];       // buffer for file name
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 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 to 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 a handle to 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.

Function | Description
ChooseColor | Creates a Color dialog box that enables the user to select a color.
ChooseFont | Creates a Font dialog box that enables the user to choose attributes for a logical font.
CommDlgExtendedError | Returns a common dialog box error code.
FindText | 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.
GetFileTitle | Retrieves the name of the specified file.
GetOpenFileName | Creates an Open dialog box that lets the user specify the drive, directory, and the name of a file or set of files to open.
GetSaveFileName | Creates a Save dialog box that lets the user specify the drive, directory, and name of a file to save.
PageSetupDlg | Creates a Page Setup dialog box that enables the user to specify the attributes of a printed page.
PrintDlg | Displays a Print dialog box.
PrintDlgEx | Displays a Print property sheet that enables the user to specify the properties of a particular print job.
ReplaceText | 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.

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

The LPCCHOOKPROC type defines a pointer to this callback function. CCHookProc is a placeholder for the application-defined function name.

UINT_PTR CALLBACK CCHookProc(
  HWND hdlg,      // handle to dialog box
  UINT uiMsg,     // message identifier
  WPARAM wParam,  // message parameter
  LPARAM lParam   // message parameter
);

Parameters

hdlg
[in] Handle to the Color dialog box for which the message is intended.
uiMsg
[in] Identifies the message being received.
wParam
[in] Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.
lParam
[in] 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 a common dialog box. However, the 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.

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

The LPCFHOOKPROC type defines a pointer to this callback function. CFHookProc is a placeholder for the application-defined function name.

UINT_PTR CALLBACK CFHookProc(
  HWND hdlg,      // handle to dialog box
  UINT uiMsg,     // message identifier
  WPARAM wParam,  // message parameter
  LPARAM lParam   // message parameter
);

Parameters

hdlg
[in] Handle to the Font dialog box for which the message is intended.
uiMsg
[in] Identifies the message being received.
wParam
[in] Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.
lParam
[in] 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 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 a common dialog box. However, the 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.

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 dialog box that enables the user to select a color.

BOOL ChooseColor(
  LPCHOOSECOLOR lpcc   // initialization data
);

Parameters

lpcc
[in/out] 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_DIALOGFAILURE
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.

For an example, see Choosing a Color.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.
Library: Use Comdlg32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Common Dialog Box Library Overview, Common Dialog Box Functions, CCHookProc, CHOOSECOLOR, CommDlgExtendedError


ChooseFont

The ChooseFont function creates a Font 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   // initialization data
);

Parameters

lpcf
[in/out] 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_DIALOGFAILURE
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.

For an example, see Choosing a Color.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.
Library: Use Comdlg32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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 common dialog box functions. These error codes are defined in Cderr.h.

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 file name specified by the user. The first two bytes of the lpstrFile buffer contain an integer value specifying the size, in TCHARs, required to receive the full name.
FNERR_INVALIDFILENAME | A file name 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.
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   // initialization data
);

Parameters

lpfr
[in] 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 is a handle to 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.

For an example, see Finding Text.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.
Library: Use Comdlg32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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

The LPFRHOOKPROC type defines a pointer to this callback function. FRHookProc is a placeholder for the application-defined function name.

UINT_PTR CALLBACK FRHookProc(
  HWND hdlg,      // handle to dialog box
  UINT uiMsg      // message identifier
  WPARAM wParam,  // message parameter
  LPARAM lParam   // message parameter
);

Parameters

hdlg
[in] Handle to the Find or Replace dialog box for which the message is intended.
uiMsg
[in] Identifies the message being received.
wParam
[in] Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.
lParam
[in] 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 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 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 a common dialog box. However, the 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Functions, EndDialog, FINDREPLACE, FindText, PostMessage, ReplaceText, WM_INITDIALOG, WM_CTLCOLORDLG


GetFileTitle

The GetFileTitle function retrieves the name of the specified file.

short GetFileTitle(
  LPCTSTR lpszFile,  // path and file name
  LPTSTR lpszTitle,  // file name buffer
  WORD cbBuf         // length of buffer
);

Parameters

lpszFile
[in] Pointer to the name and location of a file.
lpszTitle
[out] Pointer to a buffer that receives the name of the file.
cbBuf
[in] Specifies the length, in TCHARs, of the buffer pointed to by the lpszTitle parameter. For the ANSI version of the function, this is in bytes; for the Unicode version, this is in characters.

Return Values

If the function succeeds, the return value is zero.

If the file name is invalid, the return value is unknown. If there is an error, 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 TCHARs. The required buffer size includes the terminating null character.

Remarks

GetFileTitle should only be called with legal Win32 file names; using an illegal file name has an unknown result.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 file name to the user. The display name includes an extension only if that is the user's preference for displaying file names. 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.
Library: Use Comdlg32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Common Dialog Box Library Overview, Common Dialog Box Functions, GetOpenFileName, GetSaveFileName


GetOpenFileName

The GetOpenFileName function creates an Open 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   // initialization data
);

Parameters

lpofn
[in/out] 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 file name 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 file name 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_DIALOGFAILURE
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/98 and Windows NT/Windows 2000 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.

With Windows 2000, the OPENFILENAME structure has increased to include some additional members. However, this causes problems for applications on previous operation systems. To use the current header files for applications on Windows 95/98 and Windows NT 4.0, either use the #define "/D_WIN32_WINNT=0x0400" or use OPENFILENAME_SIZE_VERSION_400 for the lStructSize member of OPENFILENAME.

For an example, see Opening a File.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.
Library: Use Comdlg32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Common Dialog Box Library Overview, Common Dialog Box Functions, CommDlgExtendedError, GetSaveFileName, OFNHookProc, OFNHookProcOldStyle, OPENFILENAME, SHBrowseForFolder


GetSaveFileName

The GetSaveFileName function creates a Save dialog box that lets the user specify the drive, directory, and name of a file to save.

BOOL GetSaveFileName(
  LPOPENFILENAME lpofn   // initialization data
);

Parameters

lpofn
[in/out] 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 file name 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 file name 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_DIALOGFAILURE
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.

With Windows 2000, the OPENFILENAME structure has increased to include some additional members. However, this causes problems for applications on previous operation systems. To use the current header files for applications on Windows 95/98 and Windows NT 4.0, either use the #define "/D_WIN32_WINNT=0x0400" or use OPENFILENAME_SIZE_VERSION_400 for the lStructSize member of OPENFILENAME.

For an example, see Creating an Enhanced Metafile.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.
Library: Use Comdlg32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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 dialog boxes. The function receives notification messages sent from the 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 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_PTR CALLBACK OFNHookProc(
  HWND hdlg,      // handle to child dialog box
  UINT uiMsg,     // message identifier
  WPARAM wParam,  // message parameter
  LPARAM lParam   // message parameter
);

Parameters

hdlg
[in] 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.
uiMsg
[in] Identifies the message being received.
wParam
[in] Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.
lParam
[in] 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 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. However, the Explorer-style common dialog boxes 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.

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 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 dialog box, and you want a hook procedure, you must use an Explorer-style OFNHookProc hook procedure.

UINT_PTR CALLBACK OFNHookProcOldStyle(
  HWND hdlg,      // handle to dialog box
  UINT uiMsg      // message identifier
  WPARAM wParam,  // message parameter
  LPARAM lParam   // message parameter
);

Parameters

hdlg
[in] Handle to the Open or Save As dialog box for which the message is intended.
uiMsg
[in] Identifies the message being received.
wParam
[in] Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.
lParam
[in] 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.

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 a common dialog box. However, the 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.

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_PTR CALLBACK PagePaintHook(
  HWND hdlg,      // handle to dialog box
  UINT uiMsg,     // message identifier
  WPARAM wParam,  // message parameter
  LPARAM lParam   // message parameter
);

Parameters

hdlg
[in] Handle to the Page Setup dialog box.
uiMsg
[in] Identifies the message being received.
wParam
[in] Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.
lParam
[in] 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 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.

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  // initialization data
);

Parameters

lppsd
[in/out] 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

Note that the values of hDevMode and hDevNames in PAGESETUPDLG may change when they are passed into PageSetupDlg. This is because these members are filled on both input and output.

For an example, see Setting Up the Printed Page.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.
Library: Use Comdlg32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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 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_PTR CALLBACK PageSetupHook(
  HWND hdlg,      // handle to dialog box
  UINT uiMsg,     // message identifier
  WPARAM wParam,  // message parameter
  LPARAM lParam   // message parameter
);

Parameters

hdlg
[in] Handle to the Page Setup dialog box for which the message is intended.
uiMsg
[in] Identifies the message being received.
wParam
[in] Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.
lParam
[in] 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 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 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 a common dialog box. However, the 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.

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. The Print dialog box enables the user to specify the properties of a particular print job.

Windows 2000 or later: The PrintDlg function has been superseded by the PrintDlgEx function. PrintDlgEx displays a Print property sheet, which has a General page containing controls similar to the Print dialog box.

BOOL PrintDlg(
  LPPRINTDLG lppd   // initialization data
);

Parameters

lppd
[in/out] 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.

Value | Value (continued)
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.

The PrintDlg function can also display a Print Setup dialog box. However, new applications should not use PrintDlg for this purpose. The Print Setup dialog box has been superseded by the Page Setup dialog box created by the PageSetupDlg function.

Note that the values of hDevMode and hDevNames in PRINTDLG may change when they are passed into PrintDlg. This is because these members are filled on both input and output.

For an example, see Displaying the Print Dialog Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.
Library: Use Comdlg32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Common Dialog Box Library Overview, Common Dialog Box Functions, CommDlgExtendedError, CreateDC, DOCINFO, PRINTDLG, PrintHookProc, SetupHookProc, StartDoc, WM_CTLCOLORDLG


PrintDlgEx

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 dialog box. The property sheet can also have additional application-specific and driver-specific property pages following the General page.

HRESULT PrintDlgEx(
  LPPRINTDLGEX lppd   // initialization data
);

Parameters

lppd
[in/out] 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

Note that the values of hDevMode and hDevNames in PRINTDLGEX may change when they are passed into PrintDlgEx. This is because these members are filled on both input and output.

For more information, see Print Property Sheet.

For an example, see Using the Print Property Sheet.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Commdlg.h; include Windows.h.
Library: Use Comdlg32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

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 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_PTR CALLBACK PrintHookProc(
  HWND hdlg,      // handle to dialog box
  UINT uiMsg,     // message identifier
  WPARAM wParam,  // message parameter
  LPARAM lParam   // message parameter
);

Parameters

hdlg
[in] Handle to the Print dialog box for which the message is intended.
uiMsg
[in] Identifies the message being received.
wParam
[in] Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.
lParam
[in] 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 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 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 a common dialog box. However, the 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.

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   // initialization data
);

Parameters

lpfr
[in/out] 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 is a handle to 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.
Library: Use Comdlg32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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 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_PTR CALLBACK SetupHookProc(
  HWND hdlg,      // handle to dialog box
  UINT uiMsg,     // message identifier
  WPARAM wParam,  // message parameter
  LPARAM lParam   // message parameter
);

Parameters

hdlg
[in] Handle to the Print Setup dialog box for which the message is intended.
uiMsg
[in] Identifies the message being received.
wParam
[in] Specifies additional information about the message. The exact meaning depends on the value of the uiMsg parameter.
lParam
[in] 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 a common dialog box. However, the 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.

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
OFNOTIFY
OFNOTIFYEX
OPENFILENAME
OPENFILENAME_NT4
PAGESETUPDLG
PRINTDLG
PRINTDLGEX
PRINTPAGERANGE


CHOOSECOLOR

The CHOOSECOLOR structure contains information the ChooseColor function uses to initialize the Color dialog box. After the user closes the dialog box, the system returns information about the user's selection in this structure.

typedef struct {
  DWORD        lStructSize;
  HWND         hwndOwner;
  HWND         hInstance;
  COLORREF     rgbResult;
  COLORREF   * lpCustColors;
  DWORD        Flags;
  LPARAM       lCustData;
  LPCCHOOKPROC lpfnHook;
  LPCTSTR      lpTemplateName;
} CHOOSECOLOR, *LPCHOOSECOLOR;

Members

lStructSize
Specifies the length, in bytes, of the structure.
hwndOwner
Handle to 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 a handle to a memory object containing a dialog box template. If the CC_ENABLETEMPLATE flag is set, hInstance is a handle to 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.

To create a COLORREF color value, use the RGB macro.

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.

To create a COLORREF color value, use the RGB macro.

Flags
A set of bit flags that you can use to initialize the Color 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Common Dialog Box Library Overview, Common Dialog Box Structures, CCHookProc, ChooseColor, MAKEINTRESOURCE, WM_INITDIALOG, COLORREF, RGB


CHOOSEFONT

The CHOOSEFONT structure contains information that the ChooseFont function uses to initialize the Font dialog box. After the user closes the dialog box, the system returns information about the user's selection in this structure.

typedef struct {
  DWORD        lStructSize;
  HWND         hwndOwner;
  HDC          hDC;
  LPLOGFONT    lpLogFont;
  INT          iPointSize;
  DWORD        Flags;
  COLORREF     rgbColors;
  LPARAM       lCustData;
  LPCFHOOKPROC lpfnHook;
  LPCTSTR      lpTemplateName;
  HINSTANCE    hInstance;
  LPTSTR       lpszStyle;
  WORD         nFontType;
  WORD         ___MISSING_ALIGNMENT__;
  INT          nSizeMin;
  INT          nSizeMax;
} CHOOSEFONT, *LPCHOOSEFONT;

Members

lStructSize
Specifies the length, in bytes, of the structure.
hwndOwner
Handle to 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
Handle to 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 dialog box. When the dialog box returns, it sets these flags to indicate the user's input. This member can be one or more of the following values.
Value | 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 is a handle to 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 is a pointer 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. To create a COLORREF color value, use the RGB macro.
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 a handle to a memory object containing a dialog box template. If the CF_ENABLETEMPLATE flag is set, hInstance is a handle to 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 one or more 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Common Dialog Box Library Overview, Common Dialog Box Structures, ChooseFont, LOGFONT, MAKEINTRESOURCE , COLORREF, RGB


DEVNAMES

The DEVNAMES structure contains strings that identify the driver, device, and output port names for a printer. The PrintDlgEx and PrintDlg functions use these strings to initialize the system-defined Print property sheet or Print dialog box. When the user closes the property sheet or dialog box, information about the selected printer is returned in this structure.

typedef struct tagDEVNAMES {
  WORD wDriverOffset;
  WORD wDeviceOffset;
  WORD wOutputOffset;
  WORD wDefault;
// Driver, device, and port name strings follow wDefault.
} DEVNAMES, *LPDEVNAMES;

Members

wDriverOffset
(Input/Output) Specifies the offset in characters from the beginning of this structure to a null-terminated string that contains the file name (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 that contains the name of the device.
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 dialog box procedure for the Print property sheet or Print dialog box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Structures, DEVMODE, PrintDlg, PrintDlgEx


FINDREPLACE

The FINDREPLACE structure contains information that the FindText and ReplaceText functions use to initialize the Find and Replace 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 dialog box.

typedef struct {
  DWORD        lStructSize;
  HWND         hwndOwner;
  HINSTANCE    hInstance;
  DWORD        Flags;
  LPTSTR        lpstrFindWhat;
  LPTSTR        lpstrReplaceWith;
  WORD         wFindWhatLen;
  WORD         wReplaceWithLen;
  LPARAM        lCustData;
  LPFRHOOKPROC lpfnHook;
  LPCTSTR       lpTemplateName;
} FINDREPLACE, *LPFINDREPLACE;

Members

lStructSize
Specifies the length, in bytes, of the structure.
hwndOwner
Handle to 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 a handle to a memory object containing a dialog box template. If the FR_ENABLETEMPLATE flag is set, hInstance is a handle to 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 one or more of the following values.
Value | 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 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 selected indicating that the search should be case-sensitive. If not set, the check box is unselected 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 selected indicating that you should search only for whole words that match the search string. If not set, the check box is unselected 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.
Unicode: Declared 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 a WM_NOTIFY message sent to an OFNHookProc hook procedure for an Open or Save As dialog box. The lParam parameter of the WM_NOTIFY message is a pointer to an OFNOTIFY structure.

typedef struct _OFNOTIFY {
  NMHDR          hdr;
  LPOPENFILENAME lpOFN;
  LPTSTR         pszFile;
} OFNOTIFY, *LPOFNOTIFY;

Members

hdr
Specifies an NMHDR structure. The code member of the NMHDR structure can be one of the following notification messages 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 file name for which a network sharing violation has occurred. This member is valid only with the CDN_SHAREVIOLATION notification message.

Remarks

Not all of the Open and Save As notification messages use the OFNOTIFY structure. The CDN_INCLUDEITEM notification message uses the OFNOTIFYEX structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.
Unicode: Declared 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, OFNOTIFYEX, OPENFILENAME


OFNOTIFYEX

The OFNOTIFYEX structure contains information about a CDN_INCLUDEITEM notification message.

typedef struct _OFNOTIFYEX {
  NMHDR           hdr;
  LPOPENFILENAME  lpOFN;
  LPVOID          psf;
  LPVOID          pidl;
} OFNOTIFYEX, *LPOFNOTIFYEX;

Members

hdr
Specifies an NMHDR structure. The code member of the NMHDR structure identifies the notification message being sent.
lpOFN
Pointer to an OPENFILENAME structure containing the values specified when the Open or Save As dialog box was created.
psf
Pointer to the IShellFolder interface for the folder or shell name-space extension whose items are being enumerated.
pidl
Pointer to an item identifier list that identifies an item in the container identified by the psf member. The item identifier is relative to the psf container.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Commdlg.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Common Dialog Box Library Overview, Common Dialog Box Structures, CDN_INCLUDEITEM, NMHDR, OFNHookProc, OFNOTIFY, OPENFILENAME


OPENFILENAME

The OPENFILENAME structure contains information that the GetOpenFileName and GetSaveFileName functions use to initialize an Open or Save As dialog box. After the user closes the dialog box, the system returns information about the user's selection in this structure.

typedef struct tagOFN {
  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;
  LPARAM        lCustData;
  LPOFNHOOKPROC lpfnHook;
  LPCTSTR       lpTemplateName;
#if (_WIN32_WINNT >= 0x0500)
  void *        pvReserved;
  DWORD         dwReserved;
  DWORD         FlagsEx;
#endif // (_WIN32_WINNT >= 0x0500)
} OPENFILENAME, *LPOPENFILENAME;

Members

lStructSize
Specifies the length, in bytes, of the structure.

Windows 95/98 and Windows NT 4.0: In an application intended for Windows 95/98 or Windows NT 4.0 and that is compiled with WINVER and _WIN32_WINNT >= 0x0500, use OPENFILENAME_SIZE_VERSION_400 for this member.

Windows 2000 and later: Use sizeof (OPENFILENAME) for this parameter.

hwndOwner
Handle to 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 a handle to a memory object containing a dialog box template. If the OFN_ENABLETEMPLATE flag is set, hInstance is a handle to 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 file name 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 TCHARs, of the lpstrCustomFilter buffer. For the ANSI version, this is the number of bytes; for the Unicode version, this is the number of characters.

nMaxCustFilter
Specifies the size, in TCHARs, of the buffer identified by lpstrCustomFilter. For the ANSI version, this is the number of bytes; for the Unicode version, this is the number of characters. 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 file name 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, file name, 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 file names of the selected files. For Explorer-style dialog boxes, the directory and file name strings are NULL separated, with an extra NULL character after the last file name. For old-style dialog boxes, the strings are space separated and the function uses short file names for file names with spaces. You can use the FindFirstFile function to convert between long and short file names. If the user selects only one file, the lpstrFile string does not have a separator between the path and file name.

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 TCHARs, of the buffer pointed to by lpstrFile. For the ANSI version, this is the number of bytes; for the Unicode version, this is the number of characters. The buffer must be large enough to store the path and file name string or strings, including the terminating null character. 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 file name and extension (without path information) of the selected file. This member can be NULL.
nMaxFileTitle
Specifies the size, in TCHARs, of the buffer pointed to by lpstrFileTitle. For the ANSI version, this is the number of bytes; for the Unicode version, this is the number of characters. This member is ignored if lpstrFileTitle is NULL.
lpstrInitialDir
Pointer to a null terminated string that can specify the initial directory. The algorithm for selecting the initial directory varies on different platforms.

Windows 2000 or later:

  1. If lpstrFile contains a path, that path is the initial directory.
  2. Otherwise, lpstrInitialDir specifies the initial directory.
  3. Otherwise, if the application has used an Open or Save As dialog box in the past, the path most recently used is selected as the initial directory. However, if an application is not run for a long time, its saved selected path is discarded.
  4. If lpstrInitialDir is NULL and the current directory contains any files of the specified filter types, the initial directory is the current directory.
  5. Otherwise, the initial directory is the personal files directory of the current user.
  6. Otherwise, the initial directory is the Desktop folder.

Windows 98/Me:

  1. lpstrInitialDir specifies the initial directory.
  2. If lpstrInitialDir is NULL and lpstrFile contains a path, that path is the initial directory.
  3. Otherwise, if the current directory contains any files of the specified filter types, the initial directory is the current directory.
  4. Otherwise, the initial directory is the personal files directory of the current user.

Earlier versions of Windows and Windows NT:

  1. lpstrInitialDir specifies the initial directory.
  2. If lpstrInitialDir is NULL and lpstrFile contains a path, that path is the initial directory.
  3. Otherwise, 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 file names of the selected files. The nFileOffset member is the offset, in bytes or characters, to the first file name, and the nFileExtension member is not used. For Explorer-style dialog boxes, the directory and file name strings are NULL separated, with an extra NULL character after the last file name. This format enables the Explorer-style dialog boxes to return long file names that include spaces. For old-style dialog boxes, the directory and file name strings are separated by spaces and the function uses short file names for file names with spaces. You can use the FindFirstFile function to convert between long and short file names.

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_DONTADDTORECENT | Windows 2000 or later: Prevents the system from adding a link to the selected file in the file system directory that contains the user's most recently used documents. To retrieve the location of this directory, call the SHGetSpecialFolderLocation function with the CSIDL_RECENT flag.
OFN_ENABLEHOOK | Enables the hook function specified in the lpfnHook member.
OFN_ENABLEINCLUDENOTIFY | Windows 2000 or later: Causes the dialog box to send CDN_INCLUDEITEM notification messages to your OFNHookProc hook procedure when the user opens a folder. The dialog box sends a notification for each item in the newly opened folder. These messages enable you to control which items the dialog box displays in the folder's item list.
OFN_ENABLESIZING | Windows 2000, Windows 98/Me: 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 is a pointer 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 file name 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_FORCESHOWHIDDEN | Windows 2000 or later: Forces the showing of system and hidden files, thus overriding the user setting to show or not show hidden files. However, a file that is marked both system and hidden is not shown.
OFN_HIDEREADONLY | Hides the Read Only check box.
OFN_LONGNAMES For old-style dialog boxes, this flag causes the dialog box to use long file names. If this flag is not specified, or if the OFN_ALLOWMULTISELECT flag is also set, old-style dialog boxes use short file names (8.3 format) for file names with spaces.

Explorer-style dialog boxes ignore this flag and always display long file names.
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 file name of the selected shortcut (.LNK) file. If this value is not specified, the dialog box returns the path and file name of the file referenced by the shortcut.
OFN_NOLONGNAMES For old-style dialog boxes, this flag causes the dialog box to use short file names (8.3 format).

Explorer-style dialog boxes ignore this flag and always display long file names.
OFN_NONETWORKBUTTON | Hides and disables the Network button.
OFN_NOREADONLYRETURN | Specifies that the returned file does not have the Read Only check box selected 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 file name. Typically, the calling application uses a hook procedure that checks the file name 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 file name is invalid. Otherwise, the file name 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 file names. If this flag is used and the user types an invalid path and file name 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 selected 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 file name.

If this flag is not set, the dialog box notifies your hook procedure when a network sharing violation occurs for the file name 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 TCHARs, from the beginning of the path to the file name in the string pointed to by lpstrFile. For the ANSI version, this is the number of bytes; for the Unicode version, this is the number of characters. 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 file name.

nFileExtension
Specifies the zero-based offset, in TCHARs, from the beginning of the path to the file name extension in the string pointed to by lpstrFile. For the ANSI version, this is the number of bytes; for the Unicode version, this is the number of characters. 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 file name, this member specifies zero.
lpstrDefExt
Pointer to a buffer that contains the default extension. GetOpenFileName and GetSaveFileName append this extension to the file name 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.

pvReserved
This member is reserved.
dwReserved
This member is reserved.
FlagsEx
Windows 2000 or later: A set of bit flags you can use to initialize the dialog box. This member can be a combination of the following flags.
Flag | Meaning
OFN_EX_NOPLACESBAR | If this flag is set, the places bar is not displayed. If this flag is not set, Explorer-style dialog boxes include a places bar containing icons for commonly-used folders, such as Favorites and Desktop.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Common Dialog Box Library Overview, Common Dialog Box Structures, GetOpenFileName, GetSaveFileName, SHGetSpecialFolderLocation


OPENFILENAME_NT4

The OPENFILENAME_NT4 structure is identical to OPENFILENAME with _WIN32_WINNT set to 0x0400. It allows an application to take advantage of other post-NT4 features while running on NT4. Also, MFC42 applications must use OPENFILENAME_NT4 to avoid heap corruption. This is because MFC has classes with embedded OPENFILENAME structures, and you must use the same structure size.

For more information, see OPENFILENAME.


PAGESETUPDLG

The PAGESETUPDLG structure contains information the PageSetupDlg function uses to initialize the Page Setup 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 {
  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
Handle to 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 specified, 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 specified, 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 dialog box. When the dialog box returns, it sets these flags to indicate the user's input. This member can be one or more of the following values.
Value | Meaning
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 a handle to 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 a handle to 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.
Unicode: Declared 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 {
  DWORD           lStructSize;
  HWND            hwndOwner;
  HGLOBAL         hDevMode;
  HGLOBAL         hDevNames;
  HDC             hDC;
  DWORD           Flags;
  WORD            nFromPage;
  WORD            nToPage;
  WORD            nMinPage;
  WORD            nMaxPage;
  WORD            nCopies;
  HINSTANCE       hInstance;
  LPARAM          lCustData;
  LPPRINTHOOKPROC lpfnPrintHook;
  LPSETUPHOOKPROC lpfnSetupHook;
  LPCTSTR         lpPrintTemplateName;
  LPCTSTR         lpSetupTemplateName;
  HGLOBAL         hPrintTemplate;
  HGLOBAL         hSetupTemplate;
} PRINTDLG, *LPPRINTDLG;

Members

lStructSize
Specifies the structure size, in bytes.
hwndOwner
Handle to 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 data to 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
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 dialog box. When the dialog box returns, it sets these flags to indicate the user's input. This member can be one or more of the following values.
Value | Meaning
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 selected.

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.

See PD_NOPAGENUMS.
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. Also, it causes the Collate checkbox to appear in the dialog.
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/2000 or later: 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 a handle to 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 a handle to 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 a handle to a memory object containing a dialog box template. This template replaces the default Print Setup dialog box template.

Remarks

If both hDevMode and hDevNames are NULL, PrintDlg initializes the dialog box using the current default printer. To initialize the dialog box for a different printer, use the wDeviceOffset member of the DEVNAMES structure to specify the name of the printer.

Note that the dmDeviceName member of the DEVMODE structure also specifies a printer name. However, dmDeviceName is limited to 32 characters, and the wDeviceOffset name is not. If the wDeviceOffset and dmDeviceName names are not the same, PrintDlg initializes the dialog box using the printer specified by wDeviceOffset.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Common Dialog Box Library Overview, Common Dialog Box Structures, CreateDC, CreateIC, PrintDlg, DEVMODE, DEVNAMES, WM_INITDIALOG


PRINTDLGEX

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 data to 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 one or more of the following values.
Value | Meaning
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 selected.

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.

See PD_NOPAGENUMS.
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. Also, it causes the Collate checkbox to appear in the dialog.
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.
PD_USELARGETEMPLATE | Forces the property sheet to use a large template for the General page. The larger template provides more space for applications that specify a custom template for the lower portion of the General page.

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.
Flag | Description
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 a handle to 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 a handle to 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. When the PrintDlgEx function returns, all the HPROPSHEETPAGE handles in the lphPropertyPages array have been destroyed.

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

If both hDevMode and hDevNames are NULL, PrintDlgEx initializes the property sheet using the current default printer. To initialize the property sheet for a different printer, use the wDeviceOffset member of the DEVNAMES structure to specify the name of the printer.

Note that the dmDeviceName member of the DEVMODE structure also specifies a printer name. However, dmDeviceName is limited to 32 characters, and the wDeviceOffset name is not. If the wDeviceOffset and dmDeviceName names are not the same, PrintDlgEx initializes the property sheet using the printer specified by wDeviceOffset.

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

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.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Commdlg.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Common Dialog Box Library Overview, Common Dialog Box Structures, CreateDC, CreateIC, CreatePropertySheetPage, DEVMODE, DEVNAMES, IPrintDialogCallback, IPrintDialogServices, PrintDlgEx


PRINTPAGERANGE

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.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Commdlg.h; include Windows.h.

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_INCLUDEITEM
CDN_INITDONE
CDN_SELCHANGE
CDN_SHAREVIOLATION
CDN_TYPECHANGE


CDM_GETFILEPATH

The CDM_GETFILEPATH message retrieves the path and file name of the selected file in an Explorer-style Open or Save As dialog box. The dialog box must have been created with the OFN_EXPLORER flag; otherwise, the message fails.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CDM_GETFILEPATH,          // message to send
  (WPARAM) wParam,          // size of buffer
  (LPARAM) lParam          // file name buffer (LPTSTR)
);

Parameters

wParam
Specifies the size, in TCHARs, of the lParam buffer. For the ANSI version, this is the number of bytes; for the Unicode version, this is the number of characters.
lParam
Pointer to the buffer that receives the file name and path.

Return Values

If the message succeeds, the return value is the size, in TCHARs, of the file name and path string, including the terminating NULL character. This is either the number of bytes or characters copied to the buffer, or the required buffer size if the buffer is too small.

If an error occurs, the return value is less than zero.

Remarks

The corresponding macro is as follows:

int CommDlg_OpenSave_GetFilePath(hwnd, lparam, wparam);

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.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 dialog box currently has open. The dialog box must have been created with the OFN_EXPLORER flag; otherwise, the message fails.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CDM_GETFOLDERIDLIST,      // message to send
  (WPARAM) wParam,          // size of buffer
  (LPARAM) lParam          // identifier buffer (LPVOID)
);

Parameters

wParam
Specifies the size, in bytes, of the lParam buffer.
lParam
Pointer to the buffer that receives the list of item identifiers.

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 buffer, or the required buffer size if the buffer is too small.

If an error occurs, the return value is less than zero.

Remarks

The corresponding macro is as follows:

int CommDlg_OpenSave_GetFolderIDList(hwnd, lparam, wparam);

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.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 dialog box. The dialog box must have been created with the OFN_EXPLORER flag; otherwise, the message fails.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CDM_GETFOLDERPATH,        // message to send
  (WPARAM) wParam,          // size of buffer
  (LPARAM) lParam          // path buffer (LPTSTR)
);

Parameters

wParam
Specifies the size, in TCHARs, of the lParam buffer. For the ANSI version, this is the number of bytes; for the Unicode version, this is the number of characters.
lParam
Pointer to the buffer that receives the path.

Return Values

If the message succeeds, the return value is the size, in TCHARs, of the path string, including the terminating NULL character. This is either the number of bytes or characters copied to the buffer, or the required buffer size if the buffer is too small.

If an error occurs, the return value is less than zero.

Remarks

The corresponding macro is as follows:

int CommDlg_OpenSave_GetFolderPath(hwnd, lparam, wparam);

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, GetOpenFileName, GetSaveFileName, OPENFILENAME


CDM_GETSPEC

The CDM_GETSPEC message retrieves the file name (not including the path) of the currently selected file in an Explorer-style Open or Save As dialog box. The dialog box must have been created with the OFN_EXPLORER flag; otherwise, the message fails.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CDM_GETSPEC,              // message to send
  (WPARAM) wParam,          // size of buffer
  (LPARAM) lParam          // file name buffer (LPTSTR)
);

Parameters

wParam
Specifies the size, in TCHARs, of the lParam buffer. For the ANSI version, this is the number of bytes; for the Unicode version, this is the number of characters.
lParam
Pointer to the buffer that receives the file name.

Return Values

If the message succeeds, the return value is the size, in TCHARs, of the file name string, including the terminating NULL character. This is either the number of bytes or characters copied to the buffer, or the required buffer size if the buffer is too small.

If an error occurs, the return value is less than zero.

Remarks

The corresponding macro is as follows:

int CommDlg_OpenSave_GetSpec(hwnd, lparam, wparam);

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.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 dialog box. The dialog box must have been created with the OFN_EXPLORER flag; otherwise, the message fails.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CDM_HIDECONTROL,          // message to send
  (WPARAM) wParam,          // control identifier
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Identifier of the control to hide.
lParam
This parameter is not used.

Return Values

This message has no return value.

Remarks

The corresponding macro is as follows:

void CommDlg_OpenSave_HideControl(hwnd, wparam);

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.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 dialog box. The dialog box must have been created with the OFN_EXPLORER flag; otherwise, the message fails.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CDM_SETCONTROLTEXT,       // message to send
  (WPARAM) wParam,          // control identifier
  (LPARAM) lParam          // control text (LPSTR)
);

Parameters

wParam
Identifier of the control to whose text is set.
lParam
Pointer to a null-terminated string specifying the new text for the control.

Return Values

This message has no return value.

Remarks

The corresponding macro is as follows:

void CommDlg_OpenSave_SetControlText(hwnd, lparam, wparam)

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, GetOpenFileName, GetSaveFileName, OPENFILENAME


CDM_SETDEFEXT

The CDM_SETDEFEXT message sets the default file name extension for an Explorer-style Open or Save As dialog box. The dialog box must have been created with the OFN_EXPLORER flag; otherwise, the message fails.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  CDM_SETDEFEXT,            // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // default extension (LPSTR)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to the new file name extension. Must not include the dot (.).

Return Values

This message has no return value.

Remarks

The corresponding macro is as follows:

void CommDlg_OpenSave_SetDefExt(hwnd, lparam)

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.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 dialog box when the user specifies a file name and clicks the OK button.

Your OFNHookProc hook procedure receives this message in the form of a WM_NOTIFY message.

UINT CALLBACK OFNHookProc(
  HWND hdlg,       // handle to child dialog window
  UINT uMsg,       // WM_NOTIFY
  WPARAM wParam,   // not used
  LPARAM lParam    // message information (LPOFNOTIFY)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to an OFNOTIFY structure.

The OFNOTIFY structure contains an NMHDR structure whose code member indicates the CDN_FILEOK notification message.

The OFNOTIFY structure also contains a pointer to an OPENFILENAME structure whose lpstrFile member specifies the address of the selected file name.

Return Values

If the hook procedure returns zero, the dialog box accepts the specified file name and closes.

To reject the specified file name 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.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 dialog box when a new folder is opened.

Your OFNHookProc hook procedure receives this message in the form of a WM_NOTIFY message.

UINT CALLBACK OFNHookProc(
  HWND hdlg,       // handle to child dialog window
  UINT uMsg,       // WM_NOTIFY
  WPARAM wParam,   // not used
  LPARAM lParam    // message information (LPOFNOTIFY)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to an OFNOTIFY structure.

The OFNOTIFY structure contains an NMHDR structure whose code member indicates the CDN_FOLDERCHANGE notification message.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.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 dialog box when the user clicks the Help button.

Your OFNHookProc hook procedure receives this message in the form of a WM_NOTIFY message.

UINT CALLBACK OFNHookProc(
  HWND hdlg,       // handle to child dialog window
  UINT uMsg,       // WM_NOTIFY
  WPARAM wParam,   // not used
  LPARAM lParam    // message information (LPOFNOTIFY)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to an OFNOTIFY structure.

The OFNOTIFY structure contains an NMHDR structure whose code member indicates the CDN_HELP notification message.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, GetOpenFileName, GetSaveFileName, NMHDR, OFNHookProc, OFNOTIFY, OPENFILENAME, WM_NOTIFY


CDN_INCLUDEITEM

The CDN_INCLUDEITEM notification message is sent by an Open or Save As dialog box to determine whether the dialog box should display an item in a shell folder's item list. When the user opens a folder, the dialog box sends a CDN_INCLUDEITEM notification for each item in the folder. The dialog box sends this notification only if the OFN_ENABLEINCLUDENOTIFY flag was set when the dialog box was created.

Your OFNHookProc hook procedure receives this message in the form of a WM_NOTIFY message.

UINT CALLBACK OFNHookProc(
  HWND hdlg,       // handle to child dialog window
  UINT uMsg,       // WM_NOTIFY
  WPARAM wParam,   // not used
  LPARAM lParam    // message information (LPOFNOTIFYEX)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to an OFNOTIFYEX structure.

The OFNOTIFYEX structure contains an NMHDR structure whose code member indicates the CDN_INCLUDEITEM notification message.

The psf member of the OFNOTIFYEX structure is a pointer to an IShellFolder interface for the folder whose items are being enumerated. The pidl member is a pointer to an item identifier list that identifies the item relative to the folder.

Return Values

If the OFNHookProc hook procedure returns zero, the dialog box excludes the item from the list of items.

To include the item, return a nonzero value from the hook procedure.

Remarks

The dialog box always includes items that have both the SFGAO_FILESYSTEM and SFGAO_FILESYSANCESTOR attributes, regardless of the value returned by CDN_INCLUDEITEM.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Commdlg.h; include Windows.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, GetOpenFileName, GetSaveFileName, NMHDR, OFNHookProc, OFNOTIFYEX, WM_NOTIFY


CDN_INITDONE

The CDN_INITDONE notification message is sent by an Explorer-style Open or Save As 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.

UINT CALLBACK OFNHookProc(
  HWND hdlg,       // handle to child dialog window
  UINT uMsg,       // WM_NOTIFY
  WPARAM wParam,   // not used
  LPARAM lParam    // message information (LPOFNOTIFY)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to an OFNOTIFY structure.

The OFNOTIFY structure contains an NMHDR structure whose code member indicates the CDN_INITDONE notification message.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.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 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.

UINT CALLBACK OFNHookProc(
  HWND hdlg,       // handle to child dialog window
  UINT uMsg,       // WM_NOTIFY
  WPARAM wParam,   // not used
  LPARAM lParam    // message information (LPOFNOTIFY)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to an OFNOTIFY structure.

The OFNOTIFY structure contains an NMHDR structure whose code member indicates the CDN_SELCHANGE notification message.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.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 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.

UINT CALLBACK OFNHookProc(
  HWND hdlg,       // handle to child dialog window
  UINT uMsg,       // WM_NOTIFY
  WPARAM wParam,   // not used
  LPARAM lParam    // message information (LPOFNOTIFY)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to an OFNOTIFY structure. The pszFile member of this structure is a pointer 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 message.

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.

Value | Meaning
OFN_SHAREFALLTHROUGH | Causes the dialog box to return the file name without warning the user about the sharing violation.
OFN_SHARENOWARN | Causes the dialog box to reject the file name 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.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 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.

UINT CALLBACK OFNHookProc(
  HWND hdlg,       // handle to child dialog window
  UINT uMsg,       // WM_NOTIFY
  WPARAM wParam,   // not used
  LPARAM lParam    // message information (LPOFNOTIFY)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to an OFNOTIFY structure.

The OFNOTIFY structure contains an NMHDR structure whose code member indicates the CDN_TYPECHANGE notification message.

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

This message has no return value.

Remarks

The system sends this notification only if the dialog box was created using the OFN_EXPLORER value.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.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, CCHookProc, 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.

UINT CALLBACK CCHookProc(
  HWND hdlg,       // handle to child dialog window
  UINT uMsg,       // RegisterWindowMessage(COLOROKSTRING)
  WPARAM wParam,   // not used
  LPARAM lParam    // message information (LPCHOOSECOLOR)
);

Parameters

wParam
This parameter is not used.
lParam
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 of the message sent by the dialog box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.
Unicode: Declared 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, OFNHookProc, when the user specifies a file name and clicks the OK button. The hook procedure can accept the file name and allow the dialog box to close, or reject the file name and force the dialog box to remain open.

Note For Explorer-style Open and Save As dialog boxes, this message has been superseded by the CDN_FILEOK notification message.

UINT CALLBACK OFNHookProc(
  HWND hdlg,       // handle to child dialog window
  UINT uMsg,       // RegisterWindowMessage(FILEOKSTRING)
  WPARAM wParam,   // not used
  LPARAM lParam    // message information (LPOPENFILENAME)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to an OPENFILENAME structure. The lpstrFile member of this structure contains the drive, path, and file name specified by the user.

Return Values

If the hook procedure returns zero, the Open or Save As dialog box accepts the specified file name and closes.

If the hook procedure returns a nonzero value, the Open or Save As dialog box rejects the specified file name 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.
Unicode: Declared 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.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // RegisterWindowMessage(FINDMSGSTRING)
  WPARAM wParam,   // not used
  LPARAM lParam    // message information (LPFINDREPLACE)
);

Parameters

wParam
This parameter is not used.
lParam
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

This message has 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, a handle to 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 one or more 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 selected indicating that the user wants the search to be case-sensitive. If FR_MATCHCASE is not set, the check box is unselected so the search should be case-insensitive.
FR_WHOLEWORD | If set, the Match Whole Word Only check box is selected 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 unselected so you should also search for word fragments that match the search string.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.
Unicode: Declared 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.

Note For Explorer-style Open and Save As dialog boxes, this message has been superseded by the CDN_HELP notification message.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // RegisterWindowMessage(HELPMSGSTRING)
  WPARAM wParam,   // handle to dialog box (HWND)
  LPARAM lParam    // initialization structure (LPVOID)
);

Parameters

wParam
Handle to the common dialog box.
lParam
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

This message has 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.
Unicode: Declared 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.

Note For Explorer-style Open and Save As dialog boxes, this message has been superseded by the CDN_SELCHANGE and CDN_TYPECHANGE messages.

UINT CALLBACK OFNHookProc(
  HWND hdlg,       // handle to child dialog window
  UINT uMsg,       // RegisterWindowMessage(LBSELCHSTRING)
  WPARAM wParam,   // control identifier
  LPARAM lParam    // message information
);

Parameters

wParam
Identifier of the list box or combo box in which the selection changed.
lParam
The low-order word specifies the item number of the selected string in the list box or combo box.

The high-order word specifies the type of selection change. This parameter can be one of the following values.
Value | Description
CD_LBSELCHANGE | The item is the only item selected in a single-selection list box.
CD_LBSELADD | The item is one of the items selected in a multiple-selection list box.
CD_LBSELSUB | The item is no longer selected in a multiple-selection list box.
CD_LBSELNOITEMS | No items exist in a multiple-selection list box.

Return Values

This message has 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.
Unicode: Declared 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, CCHookProc, can send the SETRGBSTRING registered message to the dialog box to set the current color selection.

SendMessage(
  (HWND) hWnd,       // handle to destination window
  UINT uMsg,         // RegisterWindowMessage(SETRGBSTRING)
  (WPARAM) wParam,   // not used; must be zero
  (LPARAM) lParam   // RGB value (COLORREF)
);

Parameters

wParam
This parameter is not used.
lParam
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

This message has no return value.

Remarks

If lParam 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 lParam 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(hdlg, uiSetRGB, 0, (LPARAM) RGB(0, 0, 255));

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.
Unicode: Declared 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, OFNHookProc, if a sharing violation occurs for the selected file when the user clicks the OK button.

Note For Explorer-style Open and Save As dialog boxes, this message has been superseded by the CDN_SHAREVIOLATION notification message.

UINT CALLBACK OFNHookProc(
  HWND hdlg,       // handle to child dialog window
  UINT uMsg,       // RegisterWindowMessage(SHAREVISTRING)
  WPARAM wParam,   // not used
  LPARAM lParam    // message information (LPOPENFILENAME)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to a OPENFILENAME structure. The lpstrFile member of this structure contains the file name 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.

Value | Description
OFN_SHAREFALLTHROUGH | Accept the file name
OFN_SHARENOWARN | Reject the file name but do not warn the user. The application is responsible for displaying a warning message.
OFN_SHAREWARN | Reject the file name 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.
Unicode: Declared as Unicode and ANSI messages.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, CDN_SHAREVIOLATION, OPENFILENAME, RegisterWindowMessage


WM_CHOOSEFONT_GETLOGFONT

An application sends the WM_CHOOSEFONT_GETLOGFONT message to a Font dialog box to retrieve information about the user's current font selections.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_CHOOSEFONT_GETLOGFONT, // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // font data (LPLOGFONT)
);

Parameters

wParam
This parameter is not used.
lParam
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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, CFHookProc, ChooseFont, CHOOSEFONT, LOGFONT, WM_COMMAND


WM_CHOOSEFONT_SETFLAGS

An application sends the WM_CHOOSEFONT_SETFLAGS message to a Font dialog box to set the display options for the dialog box.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_CHOOSEFONT_SETFLAGS,   // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // new settings (LPCHOOSEFONT)
);

Parameters

wParam
This parameter is not used.
lParam
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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Messages, CFHookProc, ChooseFont, CHOOSEFONT


WM_CHOOSEFONT_SETLOGFONT

An application sends the WM_CHOOSEFONT_SETLOGFONT message to a Font dialog box to set the current logical font information.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_CHOOSEFONT_SETLOGFONT, // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // font data (LPLOGFONT)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to a LOGFONT structure that contains information about the current logical font.

Return Values

This message has 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.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, PagePaintHook, that the dialog box is about to draw the envelope-stamp rectangle of the sample page.

UINT CALLBACK PagePaintHook(
  HWND hdlg,       // handle to child dialog window
  UINT uMsg,       // WM_PSD_ENVSTAMPRECT
  WPARAM wParam,   // handle to DC (HDC)
  LPARAM lParam    // envelope-stamp rectangle (LPRECT)
);

Parameters

wParam
Handle to the device context for the sample page.
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 messages to the hook procedure.

A hook procedure receives this message only if the selected paper type is an envelope.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.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.

UINT CALLBACK PagePaintHook(
  HWND hdlg,       // handle to child dialog window
  UINT uMsg,       // WM_PSD_FULLPAGERECT
  WPARAM wParam,   // handle to DC (HDC)
  LPARAM lParam    // page-rectangle dimensions (LPRECT)
);

Parameters

wParam
Handle to the device context for the sample page.
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 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 messages to the hook procedure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.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, PagePaintHook, that the dialog box is about to draw Greek text inside the margin rectangle of the sample page.

UINT CALLBACK PagePaintHook(
  HWND hdlg,       // handle to child dialog window
  UINT uMsg,       // WM_PSD_GREEKTEXTRECT
  WPARAM wParam,   // handle to DC (HDC)
  LPARAM lParam    // Greek text rectangle (LPRECT)
);

Parameters

wParam
Handle to the device context for the sample page.
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 messages to the hook procedure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.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, PagePaintHook, that the dialog box is about to draw the margin rectangle of the sample page.

UINT CALLBACK PagePaintHook(
  HWND hdlg,       // handle to child dialog window
  UINT uMsg,       // WM_PSD_MARGINRECT
  WPARAM wParam,   // handle to DC (HDC)
  LPARAM lParam    // margin rectangle (LPRECT)
);

Parameters

wParam
Handle to the device context for the sample page.
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 messages to the hook procedure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.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.

UINT CALLBACK PagePaintHook(
  HWND hdlg,       // handle to child dialog window
  UINT uMsg,       // WM_PSD_MINMARGINRECT
  WPARAM wParam,   // handle to DC (HDC)
  LPARAM lParam    // minimum margin rectangle (LPRECT)
);

Parameters

wParam
Handle to the device context for the sample page.
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 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 messages to the hook procedure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.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.

UINT CALLBACK PagePaintHook(
  HWND hdlg,       // handle to child dialog window
  UINT uMsg,       // WM_PSD_PAGESETUPDLG
  WPARAM wParam,   // paper size and orientation
  LPARAM lParam    // message information (LPPAGESETUPDLG)
);

Parameters

wParam
The low-order word 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.

The high-order word specifies 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.
Value | Meaning
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)

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.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, PagePaintHook, that the dialog box is about to draw the return address portion of an envelope sample page.

UINT CALLBACK PagePaintHook(
  HWND hdlg,       // handle to child dialog window
  UINT uMsg,       // WM_PSD_YAFULLPAGERECT
  WPARAM wParam,   // handle to DC (HDC)
  LPARAM lParam    // page rectangle dimensions (LPRECT)
);

Parameters

wParam
Handle to the device context for the sample page.
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 messages to the hook procedure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Commdlg.h; include Windows.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.

Interface | Description
IPrintDialogCallback | Enables an application to receive notifications and messages from the PrintDlgEx function while the Print property sheet is displayed.
IPrintDialogServices | Enables an application using the PrintDlgEx function to retrieve information about the currently selected printer.


IPrintDialogCallback

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 the IObjectWithSite interface, 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

Method | Description
QueryInterface | Returns pointers to supported Interfaces.
AddRef | Increments Reference count.
Release | Decrements Reference count.

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.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Commdlg.h; include Windows.h.

See Also

IPrintDialogServices, PrintDlgEx, PRINTDLGEX


IPrintDialogCallback::InitDone

The PrintDlgEx function calls the InitDone method when the system has finished initializing the General page of the Print property sheet.

HRESULT InitDone(void);

Parameters

This method has no parameters.

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.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Commdlg.h; include Windows.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Interfaces, IPrintDialogServices, PrintDlgEx


IPrintDialogCallback::HandleMessage

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 indicates the result to be returned by the dialog box procedure for the message. The value pointed to should be TRUE if you process the message, otherwise it should be FALSE or whatever is an appropriate value according to the message type.

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.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Commdlg.h; include Windows.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Interfaces, EndDialog, PostMessage, PrintDlgEx, PRINTDLGEX, SetWindowLong, WM_COMMAND, WM_CTLCOLORDLG, WM_INITDIALOG, WM_NOTIFY


IPrintDialogCallback::SelectionChange

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(void);

Parameters

This method has no parameters.

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.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Commdlg.h; include Windows.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Interfaces, PrintDlgEx


IPrintDialogServices

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

Method | Description
QueryInterface | Returns pointers to supported Interfaces.
AddRef | Increments Reference count.
Release | Decrements Reference count.

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.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Commdlg.h; include Windows.h.


IPrintDialogServices::GetCurrentDevMode

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.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Commdlg.h; include Windows.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Interfaces, DEVMODE, PrintDlgEx


IPrintDialogServices::GetCurrentPortName

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 TCHARs, of the buffer pointed to by the lpPortName parameter. On output, the variable contains the number of bytes (ANSI) or characters (Unicode), 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.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Commdlg.h; include Windows.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Interfaces, PrintDlgEx


IPrintDialogServices::GetCurrentPrinterName

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 TCHARs, of the buffer pointed to by the lpPrinterName parameter. On output, the variable contains the number of bytes (ANSI) or characters (Unicode), 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.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Commdlg.h; include Windows.h.

See Also

Common Dialog Box Library Overview, Common Dialog Box Interfaces, 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
  • Using Mouse Input
  • Mouse Input Reference


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 solely on the mouse for 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.

This section covers the following topics:

  • Mouse Cursor
  • Mouse Capture
  • Mouse ClickLock
  • Mouse Configuration
  • XBUTTONs
  • Mouse Messages
  • Mouse Sonar
  • Mouse Vanish
  • The Mouse Wheel
  • Window Activation


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

When 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 a handle to 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 mouse 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 a handle to the window.


Mouse ClickLock

The Mouse ClickLock accessibility feature has been added for Windows Me and Whistler. This feature lets a user lock down the primary mouse button after a single click. To an application, the button still appears to be pressed down. To unlock the button, an application can send any mouse message or the user can click any mouse button. This feature lets a user do complex mouse combinations more simply. For example, those with certain physical limitations can highlight text, drag objects, or open menus more easily. For more information, see the following flags and the Remarks in SystemParametersInfo:

  • SPI_GETMOUSECLICKLOCK
  • SPI_SETMOUSECLICKLOCK
  • SPI_GETMOUSECLICKLOCKTIME
  • SPI_SETMOUSECLICKLOCKTIME


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 the others minimally, if at all.

Beginning with Microsoft® Windows® 98 and Microsoft Windows NT® 4.0, the Win32 API also supports a mouse wheel. The mouse wheel can be pressed or rotated. When the mouse wheel is pressed, it acts as the middle (third) button, sending normal middle button messages to your application. When it is rotated, a wheel message is sent to your application. For more information, see The Mouse Wheel section.

Beginning with Microsoft Windows 2000, the Win32 API also supports application-command buttons. These buttons, called X buttons, are designed to allow easier access to an Internet browser, electronic mail, and media services. When an X button is pressed, a WM_APPCOMMAND message is sent to your application. For more information, see the description in the WM_APPCOMMAND message.

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.


XBUTTONs

Beginning with Windows 2000, Microsoft supports the Microsoft IntelliMouse Explorer, which is a mouse with five buttons. In addition to the left, middle, and right buttons there are XBUTTON1 and XBUTTON2 which provide backward and forward navigation for the Internet.

The window manager supports XBUTTON1 and XBUTTON2 through the WM_XBUTTON* and WM_NCXBUTTON* messages. The HIWORD of the WPARAM in these messages contains a flag indicating which X button was pressed. Because these mouse messages also fit between the constants WM_MOUSEFIRST and WM_MOUSELAST, an application can filter all mouse messages with GetMessage or PeekMessage.

In Windows 2000 and later the following APIs support XBUTTON1 and XBUTTON2:

  • WM_APPCOMMAND
  • WM_NCXBUTTONDBLCLK
  • WM_NCXBUTTONDOWN
  • WM_NCXBUTTONUP
  • WM_XBUTTONDBLCLK
  • WM_XBUTTONDOWN
  • WM_XBUTTONUP
  • MOUSEHOOKSTRUCTEX

The following existing APIs have been modified to support the new buttons:

  • mouse_event
  • ShellProc
  • MSLLHOOKSTRUCT
  • MOUSEINPUT
  • WM_PARENTNOTIFY

It is unlikely that a child window in a component application will be able to directly implement commands for the XBUTTON1 and XBUTTON2. So DefWindowProc sends a WM_APPCOMMAND message to a window when an X button is clicked. DefWindowProc also sends the WM_APPCOMMAND message to its parent window. This is similar to the way context menus are invoked with a right click—DefWindowProc sends a WM_CONTEXT message to the menu and also sends it to its parent. Additionally, if DefWindowProc receives a WM_APPCOMMAND message for a top-level window, it calls a shell hook with code HSHELL_APPCOMMAND.

Windows 2000 or later also support the keyboards that have extra keys for browser functions, media functions, application launching, and power management. For more information, see Keyboard Keys for Browsing and Other Functions.


Mouse Messages

The mouse generates an input event when 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.

This section covers the following topics:

  • Client Area Mouse Messages
  • Nonclient Area Mouse Messages
  • The WM_NCHITTEST Message


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.
WM_XBUTTONDBLCLK | Windows 2000 or later: An X mouse button was double-clicked.
WM_XBUTTONDOWN | Windows 2000 or later: An X mouse button was pressed.
WM_XBUTTONUP | Windows 2000 or later: An X mouse button was released.

In addition, an application can call the TrackMouseEvent function to have the system send two other messages. It posts the WM_MOUSEHOVER message when the cursor hovers over the client area for a certain time period. It posts the WM_MOUSELEAVE message when the cursor leaves the client area.

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 specified in client coordinates. In the client coordinate system, all points on the screen are specified 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.
MK_XBUTTON1 | Windows 2000 or later: the first X button is down.
MK_XBUTTON2 | Windows 2000 or later: the second X button 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 exceed 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 specified 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 indicates 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 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 window.
HTMENU | In a menu.
HTMAXBUTTON | In a Maximize button.
HTMINBUTTON | In a 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.


Mouse Sonar

The Mouse Sonar accessibility feature has been added for Windows Me and Whistler. This feature briefly shows several concentric circles around the pointer when the user presses and releases the CTRL key. This feature helps a user locate the mouse pointer on a screen that is cluttered or with resolution set to high, on a poor quality monitor, or for users with impaired vision. For more information, see the following flags in SystemParametersInfo:

  • SPI_GETMOUSESONAR
  • SPI_SETMOUSESONAR


Mouse Vanish

The Mouse Vanish accessibility feature has been added for Windows Me and Whistler. This feature hides the pointer when the user is typing. The mouse pointer reappears when the user moves the mouse. This feature keeps the pointer from obscuring the text being typed, for example, in an e-mail or other document. For more information, see the following flags in SystemParametersInfo:

  • SPI_GETMOUSEVANISH
  • SPI_SETMOUSEVANISH


The Mouse Wheel

The mouse wheel combines the features of a wheel and a mouse button. The wheel has discrete, evenly-spaced notches. When you rotate the wheel, a wheel message is sent to your application as each notch is encountered. The wheel button can also operate as a normal Windows middle (third) button. Pressing and releasing the mouse wheel sends standard WM_MBUTTONUP and WM_MBUTTONDOWN messages. Double clicking the third button sends the standard WM_MBUTTONDBLCLK message.

For Windows 95 and Windows NT 3.51, the mouse wheel is supported through the MSH_MOUSEWHEEL message as part of a separate module that comes with the Microsoft® IntelliMouse® pointing device. For Windows 98 and Windows NT 4.0 and later operating systems, the mouse wheel is supported through the WM_MOUSEWHEEL message.

In most cases, applications handle WM_MOUSEWHEEL and MSH_MOUSEWHEEL transparently. However, the MSH_MOUSEWHEEL and WM_MOUSEWHEEL messages differ in the following significant ways:

  • There is no fwKeys for MSH_MOUSEWHEEL.
  • MSH_MOUSEWHEEL packs the zDelta parameter differently from WM_MOUSEWHEEL.
  • The DefWindowProc function does not perform any special processing for MSH_MOUSEWHEEL.
  • The WM_MOUSEWHEEL message goes first to the focus control and is forwarded to the parent window by the DefWindowProc function. The MSH_MOUSEWHEEL message goes first to the outermost parent and must be forwarded by the application to the focus control.
  • When an application processes the WM_MOUSEWHEEL message, it must return zero. When an application processes the MSH_MOUSEWHEEL message, it must return TRUE.

The following sections outline how each message is handled.

  • The WM_MOUSEWHEEL Message
  • The MSH_MOUSEWHEEL Message


The WM_MOUSEWHEEL Message

For Windows 98 and Windows NT 4.0, support for mouse wheel rotation is provided through the WM_MOUSEWHEEL message.

Rotating the mouse sends the WM_MOUSEWHEEL message to the focus window. 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 a window that processes it is found.

Determining the Number of Scroll Lines

Applications should use the SystemParametersInfo function to retrieve the number of lines a document scrolls for each scroll operation (wheel notch). To retrieve the number of lines, an application makes the following call

SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, pulScrollLines, 0).

The variable "pulScrollLines" points to an unsigned integer value that receives the suggested number of lines to scroll when the mouse wheel is rotated without modifier keys:

  • If this number is 0, no scrolling should occur.
  • If this number is WHEEL_PAGESCROLL, a wheel roll should be interpreted as clicking once in the page down or page up regions of the scroll bar.
  • If the number of lines to scroll is greater than the number of lines viewable, the scroll operation should also be interpreted as a page down or page up operation.

The default value for the number of scroll lines will be 3. If a user changes the number of scroll lines, by using the Mouse Properties sheet in Control Panel, the operating system broadcasts a WM_SETTINGCHANGE message to all top-level windows with SPI_SETWHEELSCROLLLINES specified. When an application receives the WM_SETTINGCHANGE message, it can then get the new number of scroll lines by calling:

 SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, pulScrollLines, 0)

Controls that Scroll

The table below lists the controls with scrolling functionality (including scroll lines set by the user).

Control | Scrolling
Edit Control | Vertical and horizontal.
ListBox Control | Vertical and horizontal.
ComboBox | When not dropped down, each scroll retrieves the next or previous item. When dropped down, each scroll forwards the message to the list box, which scrolls accordingly.
CMD (Command line) | Vertical.
Tree View | Vertical and horizontal.
List View | Vertical and horizontal.
Up/down Scrolls | One item at a time.
Trackbar Scrolls | One item at a time.
Rich Edit 1.0 | Vertical. Note, the Exchange client has its own versions of the list view and tree view controls that do not have wheel support.
Rich Edit 2.0 | From Microsoft® Office 97.

Detecting a Mouse with a Wheel

To determine if a mouse with a wheel is connected, call GetSystemMetrics(SM_MOUSEWHEELPRESENT). A return value of TRUE indicates that the mouse is connected.

The following example is from the window procedure for a multiline edit control:

BOOL ScrollLines(
     PWNDDATA pwndData,   //scrolls the window indicated
     int cLinesToScroll); //number of times

short gcWheelDelta; //wheel delta from roll
PWNDDATA pWndData; //pointer to structure containing
                   //info about the window
UINT gucWheelScrollLines=0;//number of lines to scroll
                           //on a wheel rotation

gucWheelScrollLines=
        SystemParametersInfo(SPI_GETWHEELSCROLLLINES,
                             0,
                             pulScrollLines,
                             0);
.

case WM_MOUSEWHEEL:
    /*
     * Don't handle zoom and datazoom.
     */
    if (wParam & (MK_SHIFT | MK_CONTROL)) {
        goto PassToDefaultWindowProc;
    }

    gcWheelDelta -= (short) HIWORD(wParam);
    if (abs(gcWheelDelta) >=
    WHEEL_DELTA && gucWheelScrollLines > 0) {
        int cLineScroll;

        /*
         * Limit a roll of one (1) WHEEL_DELTA to
         * scroll one (1) page.
         */
        cLineScroll = (int) min(
                (UINT) pWndData->ichLinesOnScreen - 1,
                gucWheelScrollLines);

        if (cLineScroll == 0) {
            cLineScroll++;
        }

        cLineScroll *= (gcWheelDelta / WHEEL_DELTA);
        assert(cLineScroll != 0);

        gcWheelDelta = gcWheelDelta % WHEEL_DELTA;
        return ScrollLines(pWndData, cLineScroll);
    }

    break;


The MSH_MOUSEWHEEL Message

For Windows 95 and Windows NT 3.51, support for the mouse wheel is provided through a separately-running module, MSWheel, which generates a MSH_MOUSEWHEEL message. The MSWheel module, which consists of MSWheel.exe and MSWheel.dll, is installed with the IntelliPoint® software that is shipped with the IntelliMouse pointing device. MSH_WHEELMOUSE is defined as a string in the include file Zmouse.h.

The application calls RegisterWindowMessage to generate the message ID. A message with this ID is posted by MSWheel to the current foreground window when a wheel rotation occurs. The RegisterWindowMessage function defines a unique new window message number. The returned message value can be used when calling the SendMessage or PostMessage function. The header file (ZMouse.h) contains the string to pass RegisterWindowMessage.

Note The case clause of a Switch statement requires a constant, and the wheel message will be a variable. However, you can check for MSH_MOUSEWHEEL in an If statement.

Detecting a Mouse Wheel with the MSWheel Module

To determine whether a mouse wheel is available, an application can either use the HwndMsWheel inline function or it can send a query to the MSWheel module. HwndMsWheel, which is found in Zmouse.h, returns not only the number of scroll lines, but also the registered messages, a handle to the MSWheel window, and a flag that the wheel mouse is supported. If an application sends a query to the MSWheel module, a reply of TRUE indicates that the mouse is connected. Applications can add the following code segment to send the query:

#include zmouse.h

HWND hdlMSHWheel=NULL;
UINT msgMSHWheelSupportActive=NULL;
BOOL fWheelSupport=FALSE;

msgMSHWheelSupportActive =
         RegisterWindowMessage(MSH_WHEELSUPPORT);
hdlMSHWheel = FindWindow(MSH_WHEELMODULE_CLASS,
          MSH_WHEELMODULE_TITLE);
if (hdlMSHWheel && msgMSHWheelSupportActive)
{
         fWheelSupport = (BOOL)SendMessage(hdlMSHWheel,
                              msgMSHWheelSupportActive,
                                                     0,
                                                     0);
}

Processing the MSH_MOUSEWHEEL Message

The MSWheel module posts the wheel message to the foreground window by using the window handle returned from GetForegroundWindow. The foreground window must decide whether to respond to the message or to propagate it to any wheel-enabled controls or active embedded OLE objects.

If the foreground window needs to propagate the wheel message, it can use either PostMessage or SendMessage. For wheel-embedded controls, you must decide whether the application should use the SendMessage function and check the return value.

For embedded OLE applications, use PostMessage. There's no need to check a return value here since the model for an embedded OLE application is that the container sends the message to the server and then forgets about it. It is up to the server application to take action or not.

For OLE servers (including servers with document objects), put the code that handles the wheel message in the window procedure for the window that gets embedded. When passing the message to embedded OLE applications, the recommended call to get the appropriate window handle is IOleInPlaceObject:GetWindow.

An embedded application must ensure that the code for handling the MSH_MOUSEWHEEL message is present in the window procedure for the window that it returns for the IOleInPlaceObject:GetWindow call. Specifically, note that the frame window is not present when an application is embedded, so if the code for handling the message is in the frame window's window procedure, the message won't be handled. For example, with Microsoft® Word and Microsoft® Excel, the document window is the highest level embedded window, so that is where the message handling code is required.

Determining the Number of Scroll Lines with MSWHEEL Module

Users can define the number of lines that are scrolled for each wheel rotation (notch) using a setting in the Wheel tab of the IntelliPoint software (or the Mouse properties sheet in Control Panel).

To get the number of lines that are currently set, an application can use the following code segment to query the MSWheel module:

#include "zmouse.h"

HWND hdlMSHWheel=NULL;
UINT msgMSHWheelGetScrollLines=NULL;
UINT uiMsh_WheelScrollLines;

msgMSHWheelGetScrollLines =
    RegisterWindowMessage(MSH_SCROLL_LINES);
hdlMSHWheel = FindWindow(MSH_WHEELMODULE_CLASS,
                         MSH_WHEELMODULE_TITLE);
if (hdlMSHWheel && msgMSHWheelGetScrollLines)
{
        uiMsh_WheelScrollLines =
          (UINT)SendMessage(hdlMSHWheel,
                            msgMSHWheelGetScrollLines,
                            0,
                            0);
}

As an alternative, an application can use the inline function HwndMsWheel, which is found in ZMouse.h. The inline function returns not only the number of scroll lines, but also the registered messages, a handle to the MSWheel window, and a flag that the wheel mouse is supported.

If a user changes the number of scroll lines, MSWheel broadcasts a message to all windows using the following:

SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, SPI_SETWHEELSCROLLLINES, NULL);

When an application receives this message, it can then send a message to the MSWheel module to get the number of scroll lines, using SendMessage(hdlMSHWheel, msgMSHWheelGetScrollLines, 0, 0).

Note WM_SETTINGCHANGE is equivalent to WM_WININICHANGE. The SDK documentation indicates that WM_SETTINGCHANGE is not supported in Windows NT 3.51, but MSWheel will use the syntax described above for all operating systems.

When setting the number of scroll lines, the user can choose to scroll a page at a time instead of a specific number of lines. In that case, the defined value WHEEL_PAGESCROLL is used. If this is the value returned, the operation performed should be the equivalent of the user clicking the scroll bar to scroll one page at a time.

The scroll line functions are fully available in release 019 of MSWheel.


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
  • Using a Mouse Wheel in a Document with Embedded Objects
  • Retrieving the Number of Mouse Wheel Scroll Lines


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 the position of the mouse cursor 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.

In addition, an application can call the TrackMouseEvent function to have the system send other messages that are useful for tracking the cursor. The system posts the WM_MOUSEHOVER message when the cursor hovers over the client area for a certain time period. It posts the WM_MOUSELEAVE message when the cursor leaves the client area. The WM_NCMOUSEHOVER and WM_NCMOUSELEAVE messages are the corresponding messages for the nonclient areas.


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 to 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 to 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;   // pointer to 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( (UINT) -1);
                    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;
}


Using a Mouse Wheel in a Document with Embedded Objects

This example assumes a Microsoft Word document with various embedded objects:

  • A Microsoft Excel spreadsheet
  • An embedded list box control that scrolls in response to the wheel
  • An embedded text box control that does not respond to the wheel

The MSH_MOUSEWHEEL message is always sent to the main window in Microsoft Word. This is true even if the embedded spreadsheet is active. The following table explains how the MSH_MOUSEWHEEL message is handled according to the focus.

Focus is on | Handling is as follows
Microsoft Word document | Microsoft Word scrolls the document window.
Embedded Microsoft Excel spreadsheet | Microsoft Word posts the message to Microsoft Excel. You must decide if the embedded application should respond to the message or not.
Embedded control | It is up to the application to send the message to an embedded control that has the focus and check the return code to see if the control handled it. If the control did not handle it, then the application should scroll the document window. For example, if the user clicked a list box and then rolled the wheel, that control would scroll in response to a wheel rotation. If the user clicked a text box and then rotated the wheel, the whole document would scroll.

This following example shows how an application might handle the two wheel messages.

/************************************************
* this code deals with MSH_MOUSEWHEEL
*************************************************/
#include "zmouse.h"

//
// Mouse Wheel rotation stuff, only define if we are
// on a version of the OS that does not support
// WM_MOUSEWHEEL messages.
//
#ifndef WM_MOUSEWHEEL
#define WM_MOUSEWHEEL WM_MOUSELAST+1
    // Message ID for IntelliMouse wheel
#endif

UINT uMSH_MOUSEWHEEL = 0;   // Value returned from
                            // RegisterWindowMessage()

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

INT WINAPI WinMain(
         HINSTANCE hInst,
         HINSTANCE hPrevInst,
         LPSTR lpCmdLine,
         INT nCmdShow)
{
    MSG msg;
    BOOL bRet;

    if (!InitInstance(hInst, nCmdShow))
        return FALSE;

    //
    // The new IntelliMouse uses a Registered message to transmit
    // wheel rotation info. So register for it!

    uMSH_MOUSEWHEEL =
     RegisterWindowMessage(MSH_MOUSEWHEEL);
    if ( !uMSH_MOUSEWHEEL )
    {
        MessageBox(NULL,"
                   RegisterWindowMessag Failed!",
                   "Error",MB_OK);
        return msg.wParam;
    }

    while (( bRet = GetMessage(&msg, NULL, 0, 0)) != 0)
    {
        if (bRet == -1)
        {
            // handle the error and possibly exit
        }
        else
        {
            if (!TranslateAccelerator(ghwndApp,
                                      ghaccelTable,
                                      &msg))
            {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
        }
    }

    return msg.wParam;
}

/************************************************
* this code deals with WM_MOUSEWHEEL
*************************************************/
LONG APIENTRY MainWndProc(
    HWND hwnd,
    UINT msg,
    WPARAM wParam,
    LPARAM lParam)
{
    static int nZoom = 0;

    switch (msg)
    {
        //
        // Handle Mouse Wheel messages generated
        // by the operating systems that have built-in
        // support for the WM_MOUSEWHEEL message.
        //

        case WM_MOUSEWHEEL:
            ((short) HIWORD(wParam)< 0) ? nZoom-- : nZoom++;

            //
            // Do other wheel stuff...
            //

            break;

        default:
            //
            // uMSH_MOUSEWHEEL is a message registered by
            // the mswheel dll on versions of Windows that
            // do not support the new message in the OS.

            if( msg == uMSH_MOUSEWHEEL )
            {
               ((int)wParam < 0) ? nZoom-- : nZoom++;

                //
                // Do other wheel stuff...
                //
                break;
            }

            return DefWindowProc(hwnd,
                                 msg,
                                 wParam,
                                 lParam);
    }

    return 0L;
}


Retrieving the Number of Mouse Wheel Scroll Lines

The following code allows an application to retrieve the number of scroll lines in any 32-bit Windows operating system, for both Windows 98 and Windows NT 4.0. For only those operating systems that support the wheel natively, such as Windows NT 4.0, SystemParametersInfo is recommended.

/* SPI_GETWHEELSCROLLLINES
   is defined in winuser.h beginning with NT4.0 SDK.
   The API SystemParametersInfo has been updated for the scrolllines
   functionality.
*/

#ifndef SPI_GETWHEELSCROLLLINES
#define SPI_GETWHEELSCROLLLINES   104
#endif

#include "zmouse.h"

/*********************************************************
* FUNCTION: GetNumScrollLines
* Purpose : An OS independant method to retrieve the
*           number of wheel scroll lines
* Params  : none
* Returns : UINT:  Number of scroll lines where WHEEL_PAGESCROLL
*           indicates to scroll a page at a time.
*********************************************************/
UINT GetNumScrollLines(void)
{
   HWND hdlMsWheel;
   UINT ucNumLines=3;  // 3 is the default
   OSVERSIONINFO osversion;
   UINT uiMsh_MsgScrollLines;

   memset(&osversion, 0, sizeof(OSVERSIONINFO));
   osversion.dwOSVersionInfoSize =sizeof(OSVERSIONINFO);
   GetVersionEx(&osversion);

   // In Windows 9x & WinNT3.51 query Mswheel for the
   // number of scroll lines and in WinNT 4.0 and later,
   // use SystemParametersInfo API

   if ((osversion.dwPlatformId ==
                        VER_PLATFORM_WIN32_WINDOWS) ||
       ( (osversion.dwPlatformId ==
                      VER_PLATFORM_WIN32_NT) &&
         (osversion.dwMajorVersion < 4) )   )
   {
        hdlMsWheel = FindWindow(MSH_WHEELMODULE_CLASS,
                                MSH_WHEELMODULE_TITLE);
        if (hdlMsWheel)
        {
           uiMsh_MsgScrollLines = RegisterWindowMessage
                                     (MSH_SCROLL_LINES);
           if (uiMsh_MsgScrollLines)
                ucNumLines = (int)SendMessage(hdlMsWheel,
                                    uiMsh_MsgScrollLines,
                                                       0,
                                                       0);
        }
   }
   else if ( (osversion.dwPlatformId ==
                         VER_PLATFORM_WIN32_NT) &&
             (osversion.dwMajorVersion >= 4) )
   {
      SystemParametersInfo(SPI_GETWHEELSCROLLLINES,
                                          0,
                                    &ucNumLines, 0);
   }
   return(ucNumLines);
}


Mouse Input Reference

The following elements are associated with mouse input:

  • Mouse Input Functions
  • Mouse Input Structures
  • Mouse Input Messages
  • Mouse Input Macros


Mouse Input Functions

The following functions are used with mouse input.

Function | Description
DragDetect | Captures the mouse and tracks its movement until the user performs one or more specified actions.
GetCapture | Gets a handle to the window that has captured the mouse.
GetDoubleClickTime | Gets the double-click time for the mouse.
GetMouseMovePointsEx | Gets the previous coordinates of the mouse or pen.
GetLastInputInfo | Gets the time of the last input event.
mouse_event | Synthesizes mouse motion and button clicks.
ReleaseCapture | Releases the mouse capture and restores mouse input processing.
SetCapture | Sets the mouse capture to a window.
SetDoubleClickTime | Sets the double-click time for the mouse.
SwapMouseButton | Reverses the left- and right-mouse buttons.
TrackMouseEvent or _TrackMouseEvent | Posts messages when a mouse leaves a window or hovers over a window.


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,   // handle to window
  POINT pt     // initial position
);

Parameters

hwnd
[in] Handle to the window receiving mouse input.
pt
[in] 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 down the left button , the return value is nonzero.

If the user did not move the mouse outside of the drag rectangle while holding down the left button , the return value is zero.

Remarks

The system metrics for the drag rectangle are configurable, allowing for larger or smaller drag rectangles.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Mouse Input Overview, Mouse Input Functions, GetSystemMetrics


GetCapture

The GetCapture function retrieves a handle to 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 a handle to 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 means the current thread has not captured the mouse. However, it is possible that another thread or process has captured the mouse.

Windows 98 and Windows NT 4.0 SP3 and later: To get a handle to the capture window on another thread, use the GetGUIThreadInfo function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Mouse Input Overview, Mouse Input Functions, GetGUIThreadInfo, 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Mouse Input Overview, Mouse Input Functions, SetDoubleClickTime


GetMouseMovePointsEx

The GetMouseMovePointsEx function retrieves a history of up to 64 previous coordinates of the mouse or pen.

int GetMouseMovePointsEx(
  UINT cbSize                // size of mouse move point
  LPMOUSEMOVEPOINT lppt,     // current mouse move point
  LPMOUSEMOVEPOINT lpptBuf,  // buffer to store points
  int nBufPoints,            // points the buffer can store
  DWORD resolution           // resolution of the points
);

Parameters

cbSize
[in] Specifies the size, in bytes, of the MOUSEMOVEPOINT structure.
lppt
[in] Pointer to a MOUSEMOVEPOINT structure containing valid mouse coordinates (in screen coordinates). It may also contain a time stamp.

The GetMouseMovePointsEx 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 GetMouseMovePointsEx 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
[in] Pointer to a buffer that will receive the points. It should be at least cbSize*nBuffPoints in size.
nBufPoints
[in] Specifies the number of points to retrieve.
resolution
[in] 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_HIGH_RESOLUTION_POINTS | Retrieves high resolution points. Points can range from zero to 65,535 (0xFFFF) in both x- and y-coordinates. This is the resolution provided by absolute coordinate pointing devices such as drawing tablets.

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 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 GetMouseMovePointsEx 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 GetMouseMovePointsEx function will return points that eventually were dispatched not only to the calling thread but also to other threads.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows Me.
Header: Declared in Winuser.h; include Windows.h.
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/2000 or later: This function has been superseded. Use SendInput instead.

VOID mouse_event(
  DWORD dwFlags,         // motion and click options
  DWORD dx,              // horizontal position or change
  DWORD dy,              // vertical position or change
  DWORD dwData,          // wheel movement
  ULONG_PTR dwExtraInfo  // application-defined information
);

Parameters

dwFlags
[in] Specifies various aspects of mouse motion and button clicking. This parameter can be certain combinations 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/2000 or later: Specifies that the wheel has been moved, if the mouse has a wheel. The amount of movement is specified in dwData
MOUSEEVENTF_XDOWN | Windows 2000 or later: Specifies that an X button was pressed.
MOUSEEVENTF_XUP | Windows 2000 or later: Specifies that an X button was released.

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

You cannot specify both MOUSEEVENTF_WHEEL and either MOUSEEVENTF_XDOWN or MOUSEEVENTF_XUP simultaneously in the dwFlags parameter, because they both require use of the dwData field.

dx
[in] 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 specified as the mouse's actual x-coordinate; relative data is specified 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
[in] 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 specified as the mouse's actual y-coordinate; relative data is specified as the number of mickeys moved.
dwData
[in] If dwFlags contains 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.

Windows 2000 or later: If dwFlags contains MOUSEEVENTF_XDOWN or MOUSEEVENTF_XUP, then dwData specifies which X buttons were pressed or released. This value may be any combination of the following flags.
Value | Meaning
XBUTTON1 | Set if the first X button was pressed or released.
XBUTTON2 | Set if the second X button was pressed or released.

If dwFlags is not MOUSEEVENTF_WHEEL, MOUSEEVENTF_XDOWN, or MOUSEEVENTF_XUP, then dwData should be zero.

dwExtraInfo
[in] Specifies an additional 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 specified 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 application in Control Panel. 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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.

For an example, see Drawing Lines with the Mouse.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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. SetCapture captures mouse input either when the mouse is over the capturing window, or when the mouse button was pressed while the mouse was over the capturing window and the button is still down. 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 to window
);

Parameters

hWnd
[in] Handle to the window in the current thread that is to capture the mouse.

Return Values

The return value is a handle to 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.

When the mouse is captured, menu hotkeys and other keyboard accelerators do not work.

Windows 95: Calling SetCapture causes the window that is losing the mouse capture to receive a WM_CAPTURECHANGED message.

For an example, see Drawing Lines with the Mouse.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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  // tracking information
);

Parameters

lpEventTrack
[in/out] Pointer to a TRACKMOUSEEVENT structure that contains tracking information.

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 function can post the following messages.

Message | Meaning
WM_NCMOUSEHOVER | Windows 98, Windows 2000: The same meaning as WM_MOUSEHOVER except this is for the nonclient area of the window.
WM_NCMOUSELEAVE | Windows 98, Windows 2000: The same meaning as WM_MOUSELEAVE except this is for the nonclient area of the window.
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 reenters 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.

Note The _TrackMouseEvent function calls TrackMouseEvent if it exists, otherwise _TrackMouseEvent emulates TrackMouseEvent. The _TrackMouseEvent function is in commctrl.h and is exported by COMCTRL32.DLL.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Mouse Input Overview, Mouse Input Functions, SystemParametersInfo, _TrackMouseEvent, TRACKMOUSEEVENT


_TrackMouseEvent

The _TrackMouseEvent function posts messages when the mouse pointer leaves a window or hovers over a window for a specified amount of time. This function calls TrackMouseEvent if it exists, otherwise it emulates it.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 3.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 3.0 or later).
Header: Declared in Commctrl.h.
Library: Use Comctl32.lib.

See Also

Mouse Input Overview, Mouse Input Functions, SystemParametersInfo, TrackMouseEvent, TRACKMOUSEEVENT


Mouse Input Structures

The following structures are used with mouse input.

LASTINPUTINFO
MOUSEMOVEPOINT
TRACKMOUSEEVENT


MOUSEMOVEPOINT

The MOUSEMOVEPOINT structure contains information about the mouse's location in screen coordinates.

typedef struct tagMOUSEMOVEPOINT {
  int       x;
  int       y;
  DWORD     time;
  ULONG_PTR dwExtraInfo;
} MOUSEMOVEPOINT, *PMOUSEMOVEPOINT;

Members

x
Specifies the x-coordinate of the mouse.
y
Specifies the y-coordinate of the mouse.
time
Specifies the time stamp of the mouse coordinate.
dwExtraInfo
Specifies extra information associated with this coordinate.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows Me.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Structures, GetMouseMovePointsEx


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_NONCLIENT | Windows 98/Me, Windows 2000 or later: The caller wants hover and leave notification for the nonclient areas. Notification is delivered as WM_NCMOUSEHOVER and WM_NCMOUSELEAVE messages.
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 time-out returned is always the actual time-out and not HOVER_DEFAULT, if HOVER_DEFAULT was specified during the original TrackMouseEvent request.

hwndTrack
Specifies a handle to the window to track.
dwHoverTime
Specifies the hover time-out (if TME_HOVER was specified in dwFlags), in milliseconds. Can be HOVER_DEFAULT, which means to use the system default hover time-out.

Remarks

The system default hover time-out is initially the menu drop-down time, which is 400 milliseconds. You can call SystemParametersInfo and use SPI_GETMOUSEHOVERTIME to retrieve the default hover time-out.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Structures, SystemParametersInfo,
TrackMouseEvent

Microsoft Platform SDK, February 2001 Edition.
This content last built on Thursday, February 01, 2001.


Mouse Input Messages

The following messages are used with mouse input.

WM_APPCOMMAND
WM_CAPTURECHANGED
WM_LBUTTONDBLCLK
WM_LBUTTONDOWN
WM_LBUTTONUP
WM_MBUTTONDBLCLK
WM_MBUTTONDOWN
WM_MBUTTONUP
WM_MOUSEACTIVATE
WM_MOUSEHOVER
WM_MOUSELEAVE
WM_MOUSEMOVE
WM_MOUSEWHEEL
WM_NCHITTEST
WM_NCLBUTTONDBLCLK
WM_NCLBUTTONDOWN
WM_NCLBUTTONUP
WM_NCMBUTTONDBLCLK
WM_NCMBUTTONDOWN
WM_NCMBUTTONUP
WM_NCMOUSEHOVER
WM_NCMOUSELEAVE
WM_NCMOUSEMOVE
WM_NCRBUTTONDBLCLK
WM_NCRBUTTONDOWN
WM_NCRBUTTONUP
WM_NCXBUTTONDBLCLK
WM_NCXBUTTONDOWN
WM_NCXBUTTONUP
WM_RBUTTONDBLCLK
WM_RBUTTONDOWN
WM_RBUTTONUP
WM_XBUTTONDBLCLK
WM_XBUTTONDOWN
WM_XBUTTONUP


WM_APPCOMMAND

The WM_APPCOMMAND message notifies a window that the user generated an application command event, for example, by clicking an application command button using the mouse or typing an application command key on the keyboard.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_APPCOMMAND
  WPARAM wParam,   // handle to window (DWORD)
  LPARAM lParam    // command, device, and virtual keys
);

Parameters

wParam
Handle to the window where the user clicked the button or pressed the key. This can be a child window of the window receiving the message. For more information about processing this message, see the Remarks section.
lParam
Use the following code to crack the lParam parameter.
cmd  = GET_APPCOMMAND_LPARAM(lParam);
uDevice = GET_DEVICE_LPARAM(lParam);
dwKeys = GET_KEYSTATE_LPARAM(lParam);

Where cmd indicates the application command. This parameter can be one of the following values.
Value | Meaning
APPCOMMAND_BASS_BOOST | Toggle the bass boost on and off.
APPCOMMAND_BASS_DOWN | Decrease the bass.
APPCOMMAND_BASS_UP | Increase the bass.
APPCOMMAND_BROWSER_BACKWARD | Navigate backward.
APPCOMMAND_BROWSER_FAVORITES | Open favorites.
APPCOMMAND_BROWSER_FORWARD | Navigate forward.
APPCOMMAND_BROWSER_HOME | Navigate home.
APPCOMMAND_BROWSER_REFRESH | Refresh page.
APPCOMMAND_BROWSER_SEARCH | Open search.
APPCOMMAND_BROWSER_STOP | Stop download.
APPCOMMAND_CLOSE | Whistler: Close the window (not the application).
APPCOMMAND_COPY | Whistler: Copy the selection.
APPCOMMAND_CORRECTION_LIST | Whistler: Brings up the correction list when a word is incorrectly identified during speech input.
APPCOMMAND_CUT | Whistler: Cut the selection.
APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE | Whistler: Toggles between two modes of speech input: dictation and command/control (giving commands to an application or accessing menus).
APPCOMMAND_FIND | Whistler: Open the Find dialog.
APPCOMMAND_FORWARD_MAIL | Whistler: Forward a mail message.
APPCOMMAND_HELP | Whistler: Open the Help dialog.
APPCOMMAND_LAUNCH_APP1 | Start App1.
APPCOMMAND_LAUNCH_APP2 | Start App2.
APPCOMMAND_LAUNCH_MAIL | Open mail.
APPCOMMAND_MEDIA_NEXTTRACK | Go to next track.
APPCOMMAND_MEDIA_PLAY_PAUSE | Play or pause playback.
APPCOMMAND_MEDIA_PREVIOUSTRACK | Go to previous track.
APPCOMMAND_MEDIA_SELECT | Go to Media Select mode.
APPCOMMAND_MEDIA_STOP | Stop playback.
APPCOMMAND_MIC_ON_OFF_TOGGLE | Whistler: Toggle the microphone.
APPCOMMAND_MICROPHONE_VOLUME_DOWN | Whistler: Increase microphone volume.
APPCOMMAND_MICROPHONE_VOLUME_MUTE | Whistler: Mute the microphone.
APPCOMMAND_MICROPHONE_VOLUME_UP | Whistler: Decrease microphone volume.
APPCOMMAND_NEW | Whistler: Create a new window.
APPCOMMAND_OPEN | Whistler: Open a window.
APPCOMMAND_PASTE | Whistler: Paste
APPCOMMAND_PRINT | Whistler: Print current document.
APPCOMMAND_REDO | Whistler: Redo last action.
APPCOMMAND_REPLY_TO_MAIL | Whistler: Reply to a mail message.
APPCOMMAND_SAVE | Whistler: Save current document.
APPCOMMAND_SEND_MAIL | Whistler: Send a mail message.
APPCOMMAND_SPELL_CHECK | Whistler: Initiate a spell check.
APPCOMMAND_TREBLE_DOWN | Decrease the treble.
APPCOMMAND_TREBLE_UP | Increase the treble.
APPCOMMAND_UNDO | Whistler: Undo last action.
APPCOMMAND_VOLUME_DOWN | Lower the volume.
APPCOMMAND_VOLUME_MUTE | Mute the volume.
APPCOMMAND_VOLUME_UP | Raise the volume.

Where uDevice indicates the input device that generated the input event. It can be one of the following values.
Value | Meaning
FAPPCOMMAND_KEY | User pressed a key.
FAPPCOMMAND_MOUSE | User clicked a mouse button.
FAPPCOMMAND_OEM | An unidentified hardware source generated the event. It could be a mouse or a keyboard event.

Where dwKeys indicates whether various virtual keys are down. It can be one or more 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.
MK_XBUTTON1 | The first X button is down.
MK_XBUTTON2 | The second X button is down.

Return Values

If an application processes this message, it should return TRUE. For more information about processing the return value, see the Remarks section.

Remarks

DefWindowProc generates the WM_APPCOMMAND message when it processes the WM_XBUTTONUP or WM_NCXBUTTONUP message, or when the user types an application command key.

If a child window does not process this message and instead calls DefWindowProc, DefWindowProc will send the message to its parent window. If a top level window does not process this message and instead calls DefWindowProc, DefWindowProc will call a shell hook with the hook code equal to HSHELL_APPCOMMAND.

To get the coordinates of the cursor if the message was generated by a button click on the mouse, the application can call GetMessagePos. An application can test whether the message was generated by the mouse by checking whether lParam contains FAPPCOMMAND_MOUSE.

Unlike other windows messages, an application should return TRUE from this message if it processes it. Doing so will allow software that simulates this message on Windows systems earlier than Windows 2000 to determine whether the window procedure processed the message or called DefWindowProc to process it.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows Me.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, GET_APPCOMMAND_LPARAM, GET_DEVICE_LPARAM, GET_KEYSTATE_LPARAM, ShellProc, WM_XBUTTONUP, WM_NCXBUTTONUP


WM_CAPTURECHANGED

The WM_CAPTURECHANGED message is sent to the window that is losing the mouse capture.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_CAPTURECHANGED
  WPARAM wParam,   // not used
  LPARAM lParam    // handle to window (HWND)
);

Parameters

wParam
This parameter is not used.
lParam
Handle to the window 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_LBUTTONDBLCLK
  WPARAM wParam,   // key indicator
  LPARAM lParam    // horizontal and vertical position
);

Parameters

wParam
Indicates whether various virtual keys are down. This parameter can be one or more of the following values.
Value | Description
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.
MK_XBUTTON1 | Windows 2000 or later: The first X button is down.
MK_XBUTTON2 | Windows 2000 or later: The second X button is down.

lParam
The low-order word specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

The high-order word 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

Use the following code to obtain the horizontal and vertical position:

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

You can also use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

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 a sequence of four messages: WM_LBUTTONDOWN, WM_LBUTTONUP, WM_LBUTTONDBLCLK, and WM_LBUTTONUP.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, GET_X_LPARAM, GET_Y_LPARAM, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_LBUTTONDOWN
  WPARAM wParam,   // key indicator
  LPARAM lParam    // horizontal and vertical position
);

Parameters

wParam
Indicates whether various virtual keys are down. This parameter can be one or more of the following values.
Value | Description
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.
MK_XBUTTON1 | Windows 2000 or later: The first X button is down.
MK_XBUTTON2 | Windows 2000 or later: The second X button is down.

lParam
The low-order word specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

The high-order word 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

Use the following code to obtain the horizontal and vertical position:

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

You can also use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

To detect that the ALT key was pressed, check whether GetKeyState(VK_MENU) < 0. Note, this must not be GetAsyncKeyState.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, GET_X_LPARAM, GET_Y_LPARAM, GetCapture, GetKeyState, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_LBUTTONUP
  WPARAM wParam,   // key indicator
  LPARAM lParam    // horizontal and vertical position
);

Parameters

wParam
Indicates whether various virtual keys are down. This parameter can be one or more of the following values.
Value | Description
MK_CONTROL | The CTRL key 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.
MK_XBUTTON1 | Windows 2000 or later: The first X button is down.
MK_XBUTTON2 | Windows 2000 or later: The second X button is down.

lParam
The low-order word specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

The high-order word 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

Use the following code to obtain the horizontal and vertical position:

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

You can also use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, GET_X_LPARAM, GET_Y_LPARAM, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_MBUTTONDBLCKL
  WPARAM wParam,   // key indicator
  LPARAM lParam    // horizontal and vertical position
);

Parameters

wParam
Indicates whether various virtual keys are down. This parameter can be one or more of the following values.
Value | Description
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.
MK_XBUTTON1 | Windows 2000 or later: The first X button is down.
MK_XBUTTON2 | Windows 2000 or later: The second X button is down.

lParam
The low-order word specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

The high-order word 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

Use the following code to obtain the horizontal and vertical position:

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

You can also use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

Only windows that have the CS_DBLCLKS style can receive WM_MBUTTONDBLCLK messages, which the system generates 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_MBUTTONDOWN, WM_MBUTTONUP, WM_MBUTTONDBLCLK, and WM_MBUTTONUP again.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, GET_X_LPARAM, GET_Y_LPARAM, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_MBUTTONDOWN
  WPARAM wParam,   // key indicator
  LPARAM lParam    // horizontal and vertical position
);

Parameters

wParam
Indicates whether various virtual keys are down. This parameter can be one or more of the following values.
Value | Description
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.
MK_XBUTTON1 | Windows 2000 or later: The first X button is down.
MK_XBUTTON2 | Windows 2000 or later: The second X button is down.

lParam
The low-order word specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

The high-order word 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

Use the following code to obtain the horizontal and vertical position:

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

You can also use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

To detect that the ALT key was pressed, check whether GetKeyState(VK_MENU) < 0. Note, this must not be GetAsyncKeyState.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, GET_X_LPARAM, GET_Y_LPARAM, GetCapture, GetKeyState, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_MBUTTONUP
  WPARAM wParam,   // key indicator
  LPARAM lParam    // horizontal and vertical position
);

Parameters

wParam
Indicates whether various virtual keys are down. This parameter can be one or more of the following values.
Value | Description
MK_CONTROL | The CTRL key is down.
MK_LBUTTON | The left mouse button is down.
MK_RBUTTON | The right mouse button is down.
MK_SHIFT | The SHIFT key is down.
MK_XBUTTON1 | Windows 2000 or later: The first X button is down.
MK_XBUTTON2 | Windows 2000 or later: The second X button is down.

lParam
The low-order word specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

The high-order word 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

Use the following code to obtain the horizontal and vertical position:

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

You can also use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, GET_X_LPARAM, GET_Y_LPARAM, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_MOUSEACTIVATE
  WPARAM wParam,   // handle to parent (HWND)
  LPARAM lParam    // hit-test value and message
);

Parameters

wParam
Handle to the top-level parent window of the window being activated.
lParam
The low-order word 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.

The high-order word 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.

Remarks

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, HIWORD, LOWORD, WM_NCHITTEST


WM_MOUSEHOVER

The WM_MOUSEHOVER message is posted to a window when the cursor hovers over the client area of the window for the period of time specified in a prior call to TrackMouseEvent.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_MOUSEHOVER
  WPARAM wParam,   // key indicator
  LPARAM lParam    // horizontal and vertical position
);

Parameters

wParam
Indicates whether various virtual keys are down. This parameter can be one or more of the following values.
Value | Description
MK_CONTROL | The CTRL key is depressed.
MK_LBUTTON | The left mouse button is depressed.
MK_MBUTTON | The middle mouse button is depressed.
MK_RBUTTON | The right mouse button is depressed.
MK_SHIFT | The SHIFT key is depressed.
MK_XBUTTON1 | Windows 2000 or later: The first X button is down.
MK_XBUTTON2 | Windows 2000 or later: The second X button is down.

lParam
The low-order word specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

The high-order word 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

Hover tracking stops when WM_MOUSEHOVER is generated. The application must call TrackMouseEvent again if it requires further tracking of mouse hover behavior.

Use the following code to obtain the horizontal and vertical position:

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

You can also use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, GET_X_LPARAM, GET_Y_LPARAM, GetCapture, MAKEPOINTS, POINTS, SetCapture, TrackMouseEvent, TRACKMOUSEEVENT, WM_MOUSEHOVER


WM_MOUSELEAVE

The WM_MOUSELEAVE message is posted to a window when the cursor leaves the client area of the window specified in a prior call to TrackMouseEvent.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_MOUSELEAVE
  WPARAM wParam,   // not used
  LPARAM lParam    // not used
);

Parameters

This message has no parameters.

Return Values

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

Remarks

All tracking requested by TrackMouseEvent is canceled when this message is generated. The application must call TrackMouseEvent when the mouse reenters its window if it requires further tracking of mouse hover behavior.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, GetCapture, SetCapture, TrackMouseEvent, TRACKMOUSEEVENT, WM_NCMOUSELEAVE


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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_MOUSEMOVE
  WPARAM wParam,   // key indicators
  LPARAM lParam    // horizontal and vertical position
);

Parameters

wParam
Indicates whether various virtual keys are down. This parameter can be one or more of the following values.
Value | Description
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.
MK_XBUTTON1 | Windows 2000 or later: The first X button is down.
MK_XBUTTON2 | Windows 2000 or later: The second X button is down.

lParam
The low-order word specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

The high-order word 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

Use the following code to obtain the horizontal and vertical position:

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

You can also use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, GET_X_LPARAM, GET_Y_LPARAM, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_MOUSEWHEEL
  WPARAM wParam,   // key indicator and wheel rotation
  LPARAM lParam    // horizontal and vertical position
);

Parameters

wParam
The low-order word indicates whether various virtual keys are down. This parameter can be one or more of the following values.
Value | Description
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.
MK_XBUTTON1 | Windows 2000 or later: The first X button is down.
MK_XBUTTON2 | Windows 2000 or later: The second X button is down.

The high-order word indicates the distance 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.

lParam
The low-order word specifies the x-coordinate of the pointer, relative to the upper-left corner of the screen.

The high-order word specifies the y-coordinate of the pointer, relative to the upper-left corner of the screen.

Return Values

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

Remarks

Use the following code to crack the wParam parameter:

fwKeys = GET_KEYSTATE_WPARAM(wParam);
zDelta = GET_WHEEL_DELTA_WPARAM(wParam);

Use the following code to obtain the horizontal and vertical position:

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

You can also use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

The wheel rotation 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 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.

Windows 95 and Windows NT 3.51: Support for the mouse wheel is provided through a separately-running module, MSWheel, that generates a MSH_MOUSEWHEEL message. The MSWheel module, which consists of MSWheel.exe and MSWheel.dll, is installed with the IntelliPoint software that is shipped with the IntelliMouse® pointing device. In addition, MSH_MOUSEWHEEL is defined in the header file (ZMouse.h) that an application must use to implement support for the wheel via the MSWheel module.

MSH_MOUSEWHEEL
zDelta = (int) wParam; // wheel rotation
xPos = LOWORD(lParam); // horizontal position of pointer
yPos = HIWORD(lParam); // vertical position of pointer

Note, there is no fwKeys for MSH_MOUSEWHEEL. Otherwise, the parameters are exactly the same as for WM_MOUSEWHEEL.

It is up to the application to forward MSH_MOUSEWHEEL to any embedded objects or controls. The application is required to send the message to an active embedded OLE application. It is optional that the application sends it to a wheel-enabled control with focus. If the application does send the message to a control, it can check the return value to see if the message was processed. Controls are required to return a value of TRUE if they process the message.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, GET_KEYSTATE_WPARAM, GET_X_LPARAM, GET_Y_LPARAM, GET_WHEEL_DELTA_WPARAM, GetSystemMetrics, HIWORD, LOWORD, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NCHITTEST
  WPARAM wParam,   // not used
  LPARAM lParam    // horizontal and vertical position
);

Parameters

wParam
This parameter is not used.
lParam
The low-order word specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the screen.

The high-order word 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 a Maximize button.
HTMINBUTTON | In a 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 window 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

Use the following code to obtain the horizontal and vertical position:

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

You can also use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, GET_X_LPARAM, GET_Y_LPARAM, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NCLBUTTONDBLCLK
  WPARAM wParam,   // hit-test value
  LPARAM lParam    // cursor position
);

Parameters

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

You can also use the GET_X_LPARAM and GET_Y_LPARAM macros to extract the values of the x- and y- coordinates from lParam.

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

By default, the DefWindowProc function tests the specified 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.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, GET_X_LPARAM, GET_Y_LPARAM, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NCLBUTTONDOWN
  WPARAM wParam,   // hit-test value
  LPARAM lParam    // cursor position
);

Parameters

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

The DefWindowProc function tests the specified point to find the location of the cursor and performs the appropriate action. If appropriate, DefWindowProc sends the WM_SYSCOMMAND message to the window.

You can also use the GET_X_LPARAM and GET_Y_LPARAM macros to extract the values of the x- and y- coordinates from lParam.

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, GET_X_LPARAM, GET_Y_LPARAM, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NCLBUTTONUP
  WPARAM wParam,   // hit-test value
  LPARAM lParam    // cursor position
);

Parameters

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

The DefWindowProc function tests the specified 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.

You can also use the GET_X_LPARAM and GET_Y_LPARAM macros to extract the values of the x- and y- coordinates from lParam.

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

If it is appropriate to do so, the system sends the WM_SYSCOMMAND message to the window.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, GET_X_LPARAM, GET_Y_LPARAM, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NCMBUTTONDBLCLK
  WPARAM wParam,   // hit-test value
  LPARAM lParam    // cursor position
);

Parameters

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

You can also use the GET_X_LPARAM and GET_Y_LPARAM macros to extract the values of the x- and y- coordinates from lParam.

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

If it is appropriate to do so, the system sends the WM_SYSCOMMAND message to the window.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, GET_X_LPARAM, GET_Y_LPARAM, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NCMBUTTONDOWN
  WPARAM wParam,   // hit-test value
  LPARAM lParam    // cursor position
);

Parameters

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

You can also use the GET_X_LPARAM and GET_Y_LPARAM macros to extract the values of the x- and y- coordinates from lParam.

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

If it is appropriate to do so, the system sends the WM_SYSCOMMAND message to the window.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, GET_X_LPARAM, GET_Y_LPARAM, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NCMBUTTONUP
  WPARAM wParam,   // hit-test value
  LPARAM lParam    // cursor position
);

Parameters

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

You can also use the GET_X_LPARAM and GET_Y_LPARAM macros to extract the values of the x- and y- coordinates from lParam.

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

If it is appropriate to do so, the system sends the WM_SYSCOMMAND message to the window.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, GET_X_LPARAM, GET_Y_LPARAM, MAKEPOINTS, POINTS, WM_NCHITTEST, WM_NCMBUTTONDBLCLK, WM_NCMBUTTONDOWN, WM_SYSCOMMAND


WM_NCMOUSEHOVER

The WM_NCMOUSEHOVER message is posted to a window when the cursor hovers over the nonclient area of the window for the period of time specified in a prior call to TrackMouseEvent.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NCMOUSEHOVER
  WPARAM wParam,   // hit-test value
  LPARAM lParam    // cursor position
);

Parameters

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

Hover tracking stops when this message is generated. The application must call TrackMouseEvent again if it requires further tracking of mouse hover behavior.

You can also use the GET_X_LPARAM and GET_Y_LPARAM macros to extract the values of the x- and y- coordinates from lParam.

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, GET_X_LPARAM, GET_Y_LPARAM, MAKEPOINTS, POINTS, TrackMouseEvent , TRACKMOUSEEVENT, WM_NCHITTEST, WM_MOUSEHOVER


WM_NCMOUSELEAVE

The WM_NCMOUSELEAVE message is posted to a window when the cursor leaves the nonclient area of the window specified in a prior call to TrackMouseEvent.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NCMOUSELEAVE
  WPARAM wParam,   // not used
  LPARAM lParam    // not used
);

Parameters

This message has no parameters.

Return Values

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

Remarks

All tracking requested by TrackMouseEvent is canceled when this message is generated. The application must call TrackMouseEvent when the mouse reenters its window if it requires further tracking of mouse hover behavior.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, TrackMouseEvent , TRACKMOUSEEVENT, WM_SYSCOMMAND, WM_MOUSELEAVE


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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NCMOUSEMOVE
  WPARAM wParam,   // hit-test value
  LPARAM lParam    // cursor position
);

Parameters

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

You can also use the GET_X_LPARAM and GET_Y_LPARAM macros to extract the values of the x- and y- coordinates from lParam.

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, GET_X_LPARAM, GET_Y_LPARAM, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NCRBUTTONDBLCLK
  WPARAM wParam,   // hit-test value
  LPARAM lParam    // cursor position
);

Parameters

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

You can also use the GET_X_LPARAM and GET_Y_LPARAM macros to extract the values of the x- and y- coordinates from lParam.

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

If it is appropriate to do so, the system sends the WM_SYSCOMMAND message to the window.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, GET_X_LPARAM, GET_Y_LPARAM, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NCRBUTTONDOWN
  WPARAM wParam,   // hit-test value
  LPARAM lParam    // cursor position
);

Parameters

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

You can also use the GET_X_LPARAM and GET_Y_LPARAM macros to extract the values of the x- and y- coordinates from lParam.

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

If it is appropriate to do so, the system sends the WM_SYSCOMMAND message to the window.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, GET_X_LPARAM, GET_Y_LPARAM, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NCRBUTTONUP
  WPARAM wParam,   // hit-test value
  LPARAM lParam    // cursor position
);

Parameters

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

You can also use the GET_X_LPARAM and GET_Y_LPARAM macros to extract the values of the x- and y- coordinates from lParam.

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

If it is appropriate to do so, the system sends the WM_SYSCOMMAND message to the window.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, GET_X_LPARAM, GET_Y_LPARAM, MAKEPOINTS, POINTS, WM_NCHITTEST, WM_NCRBUTTONDBLCLK, WM_NCRBUTTONDOWN, WM_SYSCOMMAND


WM_NCXBUTTONDBLCLK

The WM_NCXBUTTONDBLCLK message is posted when the user double-clicks the first or second X button while the cursor is in 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NCXBUTTONDBLCLK
  WPARAM wParam,   // hit-test value and button value
  LPARAM lParam    // cursor position
);

Parameters

wParam
The low-order word specifies the hit-test value returned by the DefWindowProc function from processing the WM_NCHITTEST message. For a list of hit-test values, see WM_NCHITTEST.

The high-order word indicates which button was double-clicked. It can be one of the following values.
Value | Meaning
XBUTTON1 | The first X button was double-clicked..
XBUTTON2 | The second X button was double-clicked.

lParam
Pointer to 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 TRUE. For more information about processing the return value, see the Remarks section.

Remarks

Use the following code to crack the wParam parameter.

nHittest = GET_NCHITTEST_WPARAM(wParam);
fwButton = GET_XBUTTON_WPARAM(wParam);

You can also use the following code to get the x- and y-coordinates from lParam:

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

By default, the DefWindowProc function tests the specified point to get the position of the cursor and performs the appropriate action. If appropriate, it sends the WM_SYSCOMMAND message to the window.

A window need not have the CS_DBLCLKS style to receive WM_NCXBUTTONDBLCLK messages. The system generates a WM_NCXBUTTONDBLCLK message when the user presses, releases, and again presses an X button within the system's double-click time limit. Double-clicking one of these buttons actually generates four messages: WM_NCXBUTTONDOWN, WM_NCXBUTTONUP, WM_NCXBUTTONDBLCLK, and WM_NCXBUTTONUP again.

Unlike the WM_NCLBUTTONDBLCLK, WM_NCMBUTTONDBLCLK, and WM_NCRBUTTONDBLCLK messages, an application should return TRUE from this message if it processes it. Doing so will allow software that simulates this message on Windows systems earlier than Windows 2000 to determine whether the window procedure processed the message or called DefWindowProc to process it.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows Me.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, GET_X_LPARAM, GET_Y_LPARAM, MAKEPOINTS, POINTS, WM_NCHITTEST, WM_NCXBUTTONDOWN, WM_NCXBUTTONUP, WM_SYSCOMMAND


WM_NCXBUTTONDOWN

The WM_NCXBUTTONDOWN message is posted when the user presses the first or second X button while the cursor is in 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NCXBUTTONDOWN
  WPARAM wParam,   // hit-test value and button value
  LPARAM lParam    // cursor position
);

Parameters

wParam
The low-order word specifies the hit-test value returned by the DefWindowProc function from processing the WM_NCHITTEST message. For a list of hit-test values, see WM_NCHITTEST.

The high-order word indicates which button was pressed. It can be one of the following values.
Value | Meaning
XBUTTON1 | The first X button was pressed.
XBUTTON2 | The second X button was pressed.

lParam
Pointer to 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 TRUE. For more information about processing the return value, see the Remarks section.

Remarks

Use the following code to crack the wParam parameter.

nHittest = GET_NCHITTEST_WPARAM(wParam);
fwButton = GET_XBUTTON_WPARAM(wParam);

You can also use the following code to get the x- and y-coordinates from lParam:

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

By default, the DefWindowProc function tests the specified point to get the position of the cursor and performs the appropriate action. If appropriate, it sends the WM_SYSCOMMAND message to the window.

Unlike the WM_NCLBUTTONDOWN, WM_NCMBUTTONDOWN, and WM_NCRBUTTONDOWN messages, an application should return TRUE from this message if it processes it. Doing so will allow software that simulates this message on Windows systems earlier than Windows 2000 to determine whether the window procedure processed the message or called DefWindowProc to process it.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows Me.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, GET_X_LPARAM, GET_Y_LPARAM , MAKEPOINTS, POINTS, WM_NCHITTEST, WM_NCXBUTTONDBLCLK, WM_NCXBUTTONUP, WM_SYSCOMMAND


WM_NCXBUTTONUP

The WM_NCXBUTTONUP message is posted when the user releases the first or second X button while the cursor is in 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NCXBUTTONUP
  WPARAM wParam,   // hit-test value and button value
  LPARAM lParam    // cursor position
);

Parameters

wParam
The low-order word specifies the hit-test value returned by the DefWindowProc function from processing the WM_NCHITTEST message. For a list of hit-test values, see WM_NCHITTEST.

The high-order word indicates which button was released. It can be one of the following values.
Value | Meaning
XBUTTON1 | The first X button was released.
XBUTTON2 | The second X button was released.

lParam
Pointer to 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 TRUE. For more information about processing the return value, see the Remarks section.

Remarks

Use the following code to crack the wParam parameter.

nHittest = GET_NCHITTEST_WPARAM(wParam);
fwButton = GET_XBUTTON_WPARAM(wParam);

You can also use the following code to get the x- and y-coordinates from lParam:

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

By default, the DefWindowProc function tests the specified point to get the position of the cursor and performs the appropriate action. If appropriate, it sends the WM_SYSCOMMAND message to the window.

Unlike the WM_NCLBUTTONUP, WM_NCMBUTTONUP, and WM_NCRBUTTONUP messages, an application should return TRUE from this message if it processes it. Doing so will allow software that simulates this message on Windows systems earlier than Windows 2000 to determine whether the window procedure processed the message or called DefWindowProc to process it.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows Me.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, GET_X_LPARAM, GET_Y_LPARAM, MAKEPOINTS, POINTS, WM_NCHITTEST, WM_NCXBUTTONDBLCLK, WM_NCXBUTTONDOWN, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_RBUTTONDBLCLK
  WPARAM wParam,   // key indicators
  LPARAM lParam    // horizontal and vertical position
);

Parameters

wParam
Indicates whether various virtual keys are down. This parameter can be one or more of the following values.
Value | Description
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.
MK_XBUTTON1 | Windows 2000 or later: The first X button is down.
MK_XBUTTON2 | Windows 2000 or later: The second X button is down.

lParam
The low-order word specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

The high-order word 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.

Use the following code to obtain the horizontal and vertical position:

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

You can also use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, GET_X_LPARAM, GET_Y_LPARAM, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_RBUTTONDOWN
  WPARAM wParam,   // key indicators
  LPARAM lParam    // horizontal and vertical position
);

Parameters

wParam
Indicates whether various virtual keys are down. This parameter can be one or more of the following values.
Value | Description
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.
MK_XBUTTON1 | Windows 2000 or later: The first X button is down.
MK_XBUTTON2 | Windows 2000 or later: The second X button is down.

lParam
The low-order word specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

The high-order word 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

Use the following code to obtain the horizontal and vertical position:

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

You can also use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

To detect that the ALT key was pressed, check whether GetKeyState(VK_MENU) < 0. Note, this must not be GetAsyncKeyState.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, GET_X_LPARAM, GET_Y_LPARAM, GetCapture, GetKeyState, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_RBUTTONUP
  WPARAM wParam,   // key indicators
  LPARAM lParam    // horizontal and vertical position
);

Parameters

wParam
Indicates whether various virtual keys are down. This parameter can be one or more of the following values.
Value | Description
MK_CONTROL | The CTRL key is down.
MK_LBUTTON | The left mouse button is down.
MK_MBUTTON | The middle mouse button is down.
MK_SHIFT | The SHIFT key is down.
MK_XBUTTON1 | Windows 2000 or later: The first X button is down.
MK_XBUTTON2 | Windows 2000 or later: The second X button is down.

lParam
The low-order word specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

The high-order word 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

Use the following code to obtain the horizontal and vertical position:

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

You can also use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, GET_X_LPARAM, GET_Y_LPARAM, GetCapture, MAKEPOINTS, POINTS, SetCapture, WM_RBUTTONDBLCLK, WM_RBUTTONDOWN


WM_XBUTTONDBLCLK

The WM_XBUTTONDBLCLK message is posted when the user double-clicks the first or second X button while the cursor is in the client area of a window. If the mouse is not captured, the messge is posted to the window beneath the cursor. Otherwise, the message is posted to the window that has captured the mouse.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_XBUTTONDBLCLK
  WPARAM wParam,   // key indicators and button value
  LPARAM lParam    // horizontal and vertical position
);

Parameters

wParam
The low-order word indicates whether various virtual keys are down. It can be one or more 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.
MK_XBUTTON1 | The first X button is down.
MK_XBUTTON2 | The second X button is down.

The high-order word indicates which button was double-clicked. It can be one of the following values.
Value | Meaning
XBUTTON1 | The first X button was double-clicked.
XBUTTON2 | The second X button was double-clicked.

lParam
The low-order word specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

The high-order word 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 TRUE. For more information about processing the return value, see the Remarks section.

Remarks

Use the following code to crack the wParam parameter:

fwKeys = GET_KEYSTATE_WPARAM (wParam);
fwButton = GET_XBUTTON_WPARAM (wParam);

Use the following code to obtain the horizontal and vertical position:

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

You can also use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

Only windows that have the CS_DBLCLKS style can receive WM_XBUTTONDBLCLK messages, which the system generates whenever the user presses, releases, and again presses an X button within the system's double-click time limit. Double-clicking one of these buttons actually generates four messages: WM_XBUTTONDOWN, WM_XBUTTONUP, WM_XBUTTONDBLCLK, and WM_XBUTTONUP again.

Unlike the WM_LBUTTONDBLCLK, WM_MBUTTONDBLCLK, and WM_RBUTTONDBLCLK messages, an application should return TRUE from this message if it processes it. Doing so will allow software that simulates this message on Windows systems earlier than Windows 2000 to determine whether the window procedure processed the message or called DefWindowProc to process it.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows Me.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, DefWindowProc, GET_KEYSTATE_WPARAM, GET_X_LPARAM, GET_XBUTTON_WPARAM, GET_Y_LPARAM, GetCapture, GetDoubleClickTime, SetCapture, SetDoubleClickTime, MAKEPOINTS, POINTS, WM_XBUTTONDOWN, WM_XBUTTONUP


WM_XBUTTONDOWN

The WM_XBUTTONDOWN message is posted when the user presses the first or second X button while the cursor is in the client area of a window. If the mouse is not captured, the messge is posted to the window beneath the cursor. Otherwise, the message is posted to the window that has captured the mouse.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_XBUTTONDOWN
  WPARAM wParam,   // key indicators and button value
  LPARAM lParam    // horizontal and vertical position
);

Parameters

wParam
The low-order word indicates whether various virtual keys are down. It can be one or more 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.
MK_XBUTTON1 | The first X button is down.
MK_XBUTTON2 | The second X button is down.

The high-order word indicates which button was pressed. It can be one of the following values.
Value | Meaning
XBUTTON1 | The first X button was pressed.
XBUTTON2 | The second X button was pressed.

lParam
The low-order word specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

The high-order word 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 TRUE. For more information about processing the return value, see the Remarks section.

Remarks

Use the following code to crack the wParam parameter:

fwKeys = GET_KEYSTATE_WPARAM (wParam);
fwButton = GET_XBUTTON_WPARAM (wParam);

Use the following code to obtain the horizontal and vertical position:

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

You can also use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

Unlike the WM_LBUTTONDOWN, WM_MBUTTONDOWN, and WM_RBUTTONDOWN messages, an application should return TRUE from this message if it processes it. Doing so will allow software that simulates this message on Windows systems earlier than Windows 2000 to determine whether the window procedure processed the message or called DefWindowProc to process it.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows Me.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, GET_KEYSTATE_WPARAM, GET_X_LPARAM, GET_XBUTTON_WPARAM, GET_Y_LPARAM, GetCapture, MAKEPOINTS, POINTS, SetCapture, WM_XBUTTONDBLCLK, WM_XBUTTONUP


WM_XBUTTONUP

The WM_XBUTTONUP message is posted when the user releases the first or second X 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_XBUTTONUP
  WPARAM wParam,   // key indicators and button released
  LPARAM lParam    // horizontal and vertical position
);

Parameters

wParam
The low-order word indicates whether various virtual keys are down. It can be one or more 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.
MK_XBUTTON1 | The first X button is down.
MK_XBUTTON2 | The second X button is down.

The high-order word indicates which button was released. It can be one of the following values.
Value | Meaning
XBUTTON1 | The first X button was released.
XBUTTON2 | The second X button was released.

lParam
The low-order word specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

The high-order word 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 TRUE. For more information about processing the return value, see the Remarks section.

Remarks

Use the following code to crack the wParam parameter:

fwKeys = GET_KEYSTATE_WPARAM (wParam);
fwButton = GET_XBUTTON_WPARAM (wParam);

Use the following code to obtain the horizontal and vertical position:

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);

You can also use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

Unlike the WM_LBUTTONUP, WM_MBUTTONUP, and WM_RBUTTONUP messages, an application should return TRUE from this message if it processes it. Doing so will allow software that simulates this message on Windows systems earlier than Windows 2000 to determine whether the window procedure processed the message or called DefWindowProc to process it.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows Me.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Messages, GET_KEYSTATE_WPARAM, GET_X_LPARAM, GET_XBUTTON_WPARAM, GET_Y_LPARAM, GetCapture, MAKEPOINTS, POINTS, SetCapture, WM_XBUTTONDBLCLK, WM_XBUTTONDOWN


Mouse Input Macros

The following macros are used with mouse input.

GET_APPCOMMAND_LPARAM
GET_DEVICE_LPARAM
GET_FLAGS_LPARAM
GET_KEYSTATE_LPARAM
GET_KEYSTATE_WPARAM
GET_MOUSEORKEY_LPARAM
GET_NCHITTEST_WPARAM
GET_XBUTTON_WPARAM
GET_WHEEL_DELTA_WPARAM


GET_APPCOMMAND_LPARAM

The GET_APPCOMMAND_LPARAM macro retrieves the application command from the specified LPARAM value.

short GET_APPCOMMAND_LPARAM(
  LPARAM lParam
);

Parameters

lParam
Specifies the value to be converted.

Return Values

The return value is the bits of the high-order word representing the application command. It can be one of the following values.

Value | Meaning
APPCOMMAND_BASS_BOOST | Toggle the bass boost on and off.
APPCOMMAND_BASS_DOWN | Decrease the bass.
APPCOMMAND_BASS_UP | Increase the bass.
APPCOMMAND_BROWSER_BACKWARD | Navigate backward.
APPCOMMAND_BROWSER_FAVORITES | Open favorites.
APPCOMMAND_BROWSER_FORWARD | Navigate forward.
APPCOMMAND_BROWSER_HOME | Navigate home.
APPCOMMAND_BROWSER_REFRESH | Refresh page.
APPCOMMAND_BROWSER_SEARCH | Open search.
APPCOMMAND_BROWSER_STOP | Stop download.
APPCOMMAND_LAUNCH_APP1 | Start App1.
APPCOMMAND_LAUNCH_APP2 | Start App2.
APPCOMMAND_LAUNCH_MAIL | Open mail.
APPCOMMAND_MEDIA_NEXTTRACK | Go to next track.
APPCOMMAND_MEDIA_PLAY_PAUSE | Play or pause playback.
APPCOMMAND_MEDIA_PREVIOUSTRACK | Go to previous track.
APPCOMMAND_MEDIA_SELECT | Go to Media Select mode.
APPCOMMAND_MEDIA_STOP | Stop playback.
APPCOMMAND_MICROPHONE_VOLUME_DOWN | Whistler: Increase microphone volume.
APPCOMMAND_MICROPHONE_VOLUME_MUTE | Whistler: Mute the microphone.
APPCOMMAND_MICROPHONE_VOLUME_UP | Whistler: Decrease microphone volume.
APPCOMMAND_TREBLE_DOWN | Decrease the treble.
APPCOMMAND_TREBLE_UP | Increase the treble.
APPCOMMAND_VOLUME_DOWN | Lower the volume.
APPCOMMAND_VOLUME_MUTE | Mute the volume.
APPCOMMAND_VOLUME_UP | Raise the volume.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Macros


GET_DEVICE_LPARAM

The GET_DEVICE_LPARAM macro retrieves the input device type from the specified LPARAM value.

This macro is identical to the GET_MOUSEORKEY_LPARAM macro.

WORD GET_DEVICE_LPARAM(
  LPARAM lParam
);

Parameters

lParam
Specifies the value to be converted.

Return Values

The return value is the bit of the high-order word representing the input device type. It can be one of the following values.

Value | Meaning
FAPPCOMMAND_KEY | User pressed a.
FAPPCOMMAND_MOUSE | User clicked a mouse button.
FAPPCOMMAND_OEM | An undentified hardware source generated the event. It could be a mouse or a keyboard event.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Macros, GET_MOUSEORKEY_LPARAM


GET_FLAGS_LPARAM

The GET_FLAGS_LPARAM macro retrieves the state of certain virtual keys from the specified LPARAM value.

This macro is identical to the GET_KEYSTATE_LPARAM macro.

int GET_FLAGS_LPARAM(
  LPARAM lParam
);

Parameters

lParam
Specifies the value to be converted.

Return Values

The return value is the low-order word representing the virtual key state. It can be one 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.
MK_XBUTTON1 | The first X button is down.
MK_XBUTTON2 | The second X button is down.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Macros, GET_KEYSTATE_LPARAM


GET_KEYSTATE_LPARAM

The GET_KEYSTATE_LPARAM macro retrieves the state of certain virtual keys from the specified LPARAM value.

This macro is identical to the GET_FLAGS_LPARAM macro.

int GET_KEYSTATE_LPARAM(
  LPARAM lParam
);

Parameters

lParam
Specifies the value to be converted.

Return Values

The return value is the low-order word representing the virtual key state. It can be one 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.
MK_XBUTTON1 | The first X button is down.
MK_XBUTTON2 | The second X button is down.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Macros, GET_FLAGS_LPARAM


GET_KEYSTATE_WPARAM

The GET_KEYSTATE_WPARAM macro retrieves the state of certain virtual keys from the specified WPARAM value.

int GET_KEYSTATE_WPARAM(
  WPARAM wParam
);

Parameters

wParam
Specifies the value to be converted.

Return Values

The return value is the low-order word representing the virtual key state. It can be one 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.
MK_XBUTTON1 | The first X button is down.
MK_XBUTTON2 | The second X button is down.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Macros


GET_MOUSEORKEY_LPARAM

The GET_MOUSEORKEY_LPARAM macro retrieves the input device type from the specified LPARAM value.

This macro is identical to the GET_DEVICE_LPARAM macro.

WORD GET_MOUSEORKEY_LPARAM(
  LPARAM lParam
);

Parameters

lParam
Specifies the value to be converted.

Return Values

The return value is the bit of the high-order word representing the input device type. It can be one of the following values.

Value | Meaning
FAPPCOMMAND_KEY | User pressed a key.
FAPPCOMMAND_MOUSE | User clicked a mouse button.
FAPPCOMMAND_OEM | An undentified hardware source generated the event. It could be a mouse or a keyboard event.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Macros, GET_DEVICE_LPARAM


GET_NCHITTEST_WPARAM

The GET_NCHITTEST_WPARAM macro retrieves the hit-test value from the specified WPARAM value.

short GET_NCHITTEST_WPARAM(
  WPARAM wParam
);

Parameters

wParam
Specifies the value to be converted.

Return Values

The return value is the low-order word representing the hit-test value. For a list of hit-test values, see WM_NCHITTEST.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Macros


GET_XBUTTON_WPARAM

The GET_XBUTTON_WPARAM macro retrieves the state of certain buttons from the specified WPARAM value.

int GET_XBUTTON_WPARAM(
  WPARAM wParam
);

Parameters

wParam
Specifies the value to be converted.

Return Values

The high-order word indicates which button was released. It can be either of the following values.

Value | Meaning
XBUTTON1 | The first X button was released.
XBUTTON2 | The second X button was released.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Macros


GET_WHEEL_DELTA_WPARAM

The GET_WHEEL_DELTA_WPARAM macro retrieves the wheel-delta value from the specified WPARAM value.

short GET_WHEEL_DELTA_WPARAM(
  WPARAM wParam
);

Parameters

wParam
Specifies the value to be converted.

Return Values

The return value is the high-order word representing the wheel-delta value. It 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Mouse Input Overview, Mouse Input Macros


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
  • Using Keyboard Accelerators
  • Keyboard Accelerator Reference


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.

This section covers the following topics.

  • Accelerator Tables
  • Accelerator-Table Creation
  • Accelerator Keystroke Assignments
  • Accelerators and Menus
  • UI State


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 specified 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 specified 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. However, 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. Thus, using the ASCII "C" character defines the accelerator as ALT+C rather than ALT+c. However, case-sensitive accelerators can 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.


UI State

Windows 2000 enables applications to hide or show various features in the Windows user interface (UI). These settings are known as the UI state. The UI state includes the following settings:

  • focus indicators (such as focus rectangles on buttons)
  • keyboard accelerators (indicated by underlines in control labels)

A window can send messages to request a change in the UI state, can query the UI state, or enforce a certain state for its child windows. These messages are as follows.

Message | Description
WM_CHANGEUISTATE | Indicates that the UI state should change.
WM_QUERYUISTATE | Retrieves the UI state for a window.
WM_UPDATEUISTATE | Changes the UI state.

By default, all child windows of a top-level window are created with the same UI state as their parent.

The system handles the UI state for controls in dialog boxes. At dialog box creation, the system initializes the UI state accordingly. All child controls inherit this state. After the dialog box is created, the system monitors the user's keystrokes. If the UI state settings are hidden and the user navigates using the keyboard, the system updates the UI state. For example, if the user presses the Tab key to move the focus to the next control, the system calls WM_CHANGEUISTATE to make the focus indicators visible. If the user presses the Alt key, the system calls WM_CHANGEUISTATE to make the keyboard accelerators visible.

If a control supports navigation between the UI elements it contains, it can update its own UI state. The control can call WM_QUERYUISTATE to retrieve and cache the initial UI state. Whenever the control receives an WM_UPDATEUISTATE message, it can update its UI state and send a WM_CHANGEUISTATE message to its parent. Each window will continue to send the message to its parent until it reaches the top-level window. The top-level window sends the WM_UPDATEUISTATE message to the windows in the window tree. If a window does not pass on the WM_CHANGEUISTATE message, it will not reach the top-level window and the UI state will not be updated.


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.

This section covers the following topics.

  • Creating the Accelerator-Table Resource
  • Loading the Accelerator-Table Resource
  • Calling the TranslateAccelerator Function
  • Processing WM_COMMAND Messages
  • Destroying the Accelerator-Table Resource
  • Creating User-Editable Accelerators


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.

MSG msg;
BOOL bRet;

while ( (bRet = GetMessage(&msg, (HWND) NULL, 0, 0)) != 0)
{
    if (bRet == -1)
    {
        // handle the error and possibly exit
    }
    else
    {
        // Check for accelerator keystrokes.

        if (!TranslateAccelerator(
                hwndMain,      // handle to receiving window
                haccel,        // handle to active accelerator table
                &msg))         // 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 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. Note, however, that this is not true for an accelerator table created at run time. For more information, see Destroying a Run-Time Accelerator Table.


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
    BOOL bRet;          // for return value of GetMessage
    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 ((bRet = GetMessage(&msg, NULL, NULL, NULL)) != 0)
    {
        if (bRet == -1)
        {
            // handle the error and possibly exit
        }
        else
        {
            // Check for accelerator keystrokes.

            if (!TranslateAccelerator(
                    hwndMain,  // handle to receiving window
                    haccel,    // handle to active accelerator table
                    &msg))         // 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.

This section covers the following topics.

  • Creating a Run-Time Accelerator Table
  • Processing Accelerators
  • Destroying a Run-Time Accelerator Table
  • Creating User-Editable Accelerators


Creating a Run-Time 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 a pointer to 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 a Run-Time 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;     // pointer to 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.

Function | Description
CopyAcceleratorTable | Copies the specified accelerator table.
CreateAcceleratorTable | Creates an accelerator table.
DestroyAcceleratorTable | Destroys an accelerator table.
LoadAccelerators | Loads the specified accelerator table.
TranslateAccelerator | Processes accelerator keys for menu commands.


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
  LPACCEL lpAccelDst, // information buffer
  int cAccelEntries   // number of entries in buffer
);

Parameters

hAccelSrc
[in] Handle to the accelerator table to copy.
lpAccelDst
[out] Pointer to an array of ACCEL structures that receives the accelerator-table information.
cAccelEntries
[in] 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.

For an example, see Creating User-Editable Accelerators.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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,  // accelerator data array
  int cEntries     // number of entries in array
);

Parameters

lpaccl
[in] Pointer to an array of ACCEL structures that describes the accelerator table.
cEntries
[in] 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.

For an example, see Creating User-Editable Accelerators.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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
[in] 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.

For an example, see Creating User-Editable Accelerators.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 module
  LPCTSTR lpTableName   // accelerator table name
);

Parameters

hInstance
[in] Handle to the module whose executable file contains the accelerator table to load.
lpTableName
[in] Pointer to a null-terminated string that contains the name of 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. To create this value, use the MAKEINTRESOURCE macro.

Return Values

If the function succeeds, the return value is a 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.

For an example, see Creating Accelerators for Font Attributes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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        // message information
);

Parameters

hWnd
[in] Handle to the window whose messages are to be translated.
hAccTable
[in] Handle to the 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
[in] Pointer to an MSG structure that contains message information retrieved from the calling thread's message queue 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 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.

For an example, see Creating Accelerators for Font Attributes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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 {
    BYTE   fVirt;
    WORD   key;
    WORD   cmd;
} ACCEL, *LPACCEL;

Members

fVirt
Specifies the accelerator behavior. This member can be one or more 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 a character code.

key
Specifies the accelerator key. This member can be either a virtual-key code or a 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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_CHANGEUISTATE
WM_INITMENU
WM_INITMENUPOPUP
WM_MENUCHAR
WM_MENUSELECT
WM_QUERYUISTATE
WM_SYSCHAR
WM_SYSCOMMAND
WM_UPDATEUISTATE


WM_CHANGEUISTATE

An application sends the WM_CHANGEUISTATE message to indicate that the user interface (UI) state should be changed.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_CHANGEUISTATE,         // message to send
  (WPARAM) wParam,          // action
  (LPARAM) lParam          // not used; must be NULL
);

Parameters

wParam
The low-order word specifies the action to be taken. This member can be one of the following values.
Value | Meaning
UIS_CLEAR | The UI state element specified by the high-order word should be hidden.
UIS_INITIALIZE | The UI state element specified by the high-order word should be changed based on the last input event. For more information, see Remarks.
UIS_SET | The UI state element specified by the high-order word should be visible.

The high-order word specifies which UI state elements are affected or the style of the control. This member can be one or more of the following values.
Flag | Meaning
UISF_HIDEACCEL | Keyboard accelerators.
UISF_HIDEFOCUS | Focus indicators.
UISF_ACTIVE | Whistler: A control should be drawn in the style used for active controls.

lParam
This parameter is not used and must be NULL.

Remarks

A window should send this message to itself or its parent when it must change the UI state elements of all windows in the same hierarchy. The window procedure must let DefWindowProc process this message so that the entire window tree has a consistent UI state. When the top-level window receives the WM_CHANGEUISTATE message, it sends a WM_UPDATEUISTATE message with the same parameters to all child windows. When the system processes the WM_UPDATEUISTATE message, it makes the change in the UI state.

If the low-order word of wParam is UIS_INITIALIZE, the system will send the WM_UPDATEUISTATE message with a UI state based on the last input event. For example, if the last input came from the mouse, the system will hide the keyboard cues. And, if the last input came from the keyboard, the system will show the keyboard cues. If the state that results from processing WM_CHANGEUISTATE is the same as the old state, DefWindowProc does not send this message.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Keyboard Accelerators Overview, Keyboard Accelerator Messages, DefWindowProc, HIWORD, LOWORD, WM_QUERYUISTATE, WM_UPDATEUISTATE


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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_INITMENU
  WPARAM wParam,   // handle to menu (HMENU)
  LPARAM lParam    // not used
);

Parameters

wParam
Handle to the menu to be initialized.
lParam
This parameter is not used.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_INITMENUPOPUP
  WPARAM wParam,   // handle to menu (HMENU)
  LPARAM lParam    // item position and indicator
);

Parameters

wParam
Handle to the drop-down menu or submenu.
lParam
The low-order word specifies the zero-based relative position of the menu item that opens the drop-down menu or submenu.

The high-order word indicates whether the drop-down menu is the window 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Keyboard Accelerators Overview, Keyboard Accelerator Messages, HIWORD, LOWORD, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_MENUCHAR
  WPARAM wParam,   // character code (TCHAR), type
  LPARAM lParam    // handle to menu (HMENU)
);

Parameters

wParam
The low-order word specifies the character code that corresponds to the key the user pressed.

The high-order word specifies the active menu type. This parameter can be one of the following values.
Value | Meaning
MF_POPUP | A drop-down menu, submenu, or shortcut menu.
MF_SYSMENU | The window menu.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Keyboard Accelerators Overview, Keyboard Accelerator Messages, HIWORD, LOWORD


WM_MENUSELECT

The WM_MENUSELECT message is sent to a menu's owner window when the user selects a menu item.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_MENUSELECT
  WPARAM wParam,   // menu item (UINT) and flags (UINT)
  LPARAM lParam    // handle to menu (HMENU)
);

Parameters

wParam
The low-order word specifies the menu item or submenu index. 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 index of the drop-down menu or submenu in the main menu, and the lParam parameter contains the handle to the main (clicked) menu; use the GetSubMenu function to get the menu handle to the drop-down menu or submenu.

The high-order word specifies one or more menu flags. This parameter can be one or more 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. The lParam parameter contains a handle to the menu associated with the message.

lParam
Handle to the menu that was clicked.

Return Values

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

Remarks

If the high-order word of wParam contains 0xFFFF and the lParam parameter contains NULL, the system has closed the menu.

Do not use the value –1 for the high-order word of wParam, because this value is specified as (UINT) HIWORD(wParam). If the value is 0xFFFF, it would be interpreted as 0x0000FFFF, not –1, because of the cast to a UINT.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Keyboard Accelerators Overview, Keyboard Accelerator Messages, GetSubMenu, HIWORD, LOWORD


WM_QUERYUISTATE

An application sends the WM_QUERYUISTATE message to retrieve the user interface (UI) state for a window.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_QUERYUISTATE,          // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

The return value is NULL if the focus indicators and the keyboard accelerators are visible. Otherwise, the return value can be one or more of the following values.

Value | Meaning
UISF_HIDEFOCUS | Focus indicators are hidden.
UISF_HIDEACCEL | Keyboard accelerators are hidden.
UISF_ACTIVE | Whistler: A control should be drawn in the style used for active controls.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Keyboard Accelerators Overview, Keyboard Accelerator Messages, WM_CHANGEUISTATE, WM_UPDATEUISTATE


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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_SYSCHAR
  WPARAM wParam,   // character code (TCHAR)
  LPARAM lParam    // key data
);

Parameters

wParam
Specifies the character code of the window menu key.
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 lParam parameter.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_SYSCOMMAND
  WPARAM wParam,   // system command type
  LPARAM lParam    // horizontal and vertical position
);

Parameters

wParam
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 lParam parameter identifies the window to activate.
SC_HSCROLL | Scrolls horizontally.
SC_KEYMENU | Retrieves the window menu as a result of a keystroke. For more information, see the Remarks section.
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.

The lParam parameter can have the following values:

1 - the display is going to low power
2 - 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.

lParam
The low-order word specifies the horizontal position of the cursor, in screen coordinates, if a window menu command is chosen with the mouse. Otherwise, this parameter is not used.

The high-order word 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 mnemonic.

Return Values

An application should return zero if it processes this message.

Remarks

To obtain the position coordinates in screen coordinates, use the following code:

xPos = GET_X_LPARAM(lParam);    // horizontal position
yPos = GET_Y_LPARAM(lParam);    // vertical position

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 wParam parameter are used internally by the system. To obtain the correct result when testing the value of wParam, an application must combine the value 0xFFF0 with the wParam 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.

If the wParam is SC_KEYMENU, lParam contains the character code of the key that is used with the ALT key to display the popup menu. For example, pressing ALT+F to display the File popup will cause a WM_SYSCOMMAND with wParam equal to SC_KEYMENU and lParam equal to 'f'.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Keyboard Accelerators Overview, Keyboard Accelerator Messages, AppendMenu, DefWindowProc, GET_X_LPARAM, GET_Y_LPARAM, GetSystemMenu, InsertMenu, ModifyMenu, WM_COMMAND


WM_UPDATEUISTATE

An application sends the WM_UPDATEUISTATE message to change the user interface (UI) state for the specified window and all its child windows.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_UPDATEUISTATE,         // message to send
  (WPARAM) wParam,          // action
  (LPARAM) lParam          // not used; must be NULL
);

Parameters

wParam
The low-order word specifies the action to be performed. This parameter can be one of the following values.
Value | Meaning
UIS_CLEAR | The UI state element specified by the high-order word should be hidden.
UIS_INITIALIZE | The UI state element specified by the high-order word should be changed based on the last input event. For more information, see Remarks.
UIS_SET | The UI state element specified by the high-order word should be visible.

The high-order word specifies which UISTATE elements are affected or the style of the control. This parameter can be one or more of the following values.
Flag | Meaning
UISF_HIDEACCEL | Keyboard accelerators.
UISF_HIDEFOCUS | Focus indicators.
UISF_ACTIVE | Whistler: A control should be drawn in the style used for active controls.

lParam
This parameter is not used.

Remarks

A windows should send this message to change the UI state of all its child windows. In contrast to the WM_CHANGEUISTATE message, which is a notification, when DefWindowProc processes the WM_UPDATEUISTATE message it changes the UI state and propagates the changes to all child windows.

The DefWindowProc function updates the UI state according to the wParam value. If the UI state is modified, the function sends the message to all the immediate child windows. DefWindowProc also sends this message when it receives a WM_CHANGEUISTATE message notifying the system that a child window intends to modify the UI state.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Keyboard Accelerators Overview, Keyboard Accelerator Messages, DefWindowProc, WM_CHANGEUISTATE, WM_QUERYUISTATE


Keyboard Input

This overview describes how the system generates keyboard input and how an application receives and processes that input.

  • About Keyboard Input
  • Using Keyboard Input
  • Keyboard Input Reference


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.

This section covers the following topics:

  • Keyboard Input Model
  • Keyboard Focus and Activation
  • Keystroke Messages
  • Character Messages
  • Key Status
  • Keystroke and Character Translations
  • Hot-Key Support
  • Simulating Input
  • Languages, Locales, and Keyboard Layouts


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

To block keyboard and mouse input events from reaching applications, use BlockInput. Note, the BlockInput function will not interfere with the asynchronous keyboard input-state table. This means that calling the SendInput function while input is blocked will change the asynchronous keyboard input-state table.


Keystroke Messages

Pressing a key causes a WM_KEYDOWN or WM_SYSKEYDOWN message to be placed in the thread message queue attached to the window that has the keyboard focus. Releasing a key causes a WM_KEYUP or WM_SYSKEYUP message to be 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.

This section covers the following topics:

  • System and Nonsystem Keystrokes
  • Virtual-Key Codes Described
  • Keystroke Message Flags


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

This section covers the following topics:

  • Nonsystem Character Messages
  • Dead-Character Messages


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.

In addition, Rich Edit 3.0 supports the HexToUnicode IME, which allows a user to convert between hexadecimal and Unicode characters by using hot keys. This means that when Rich Edit 3.0 is incorporated into an application, the application will inherit the features the HexToUnicode IME. For more information, see HexToUnicode IME.


Hot-Key Support

The Microsoft® 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 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.


Keyboard Keys for Browsing and Other Functions

With Microsoft® Windows® 2000 and Windows Me, Microsoft Corporation is introducing support for the new keyboards with extra keys intended for browser functions, media functions, application launching, and power management. The WM_APPCOMMAND supports the extra keyboard keys and is new in Windows 2000. In addition, the ShellProc function is modified to support the extra keyboard keys:

It is unlikely that a child window in a component application will be able to directly implement commands for these extra keyboard keys. So when one of these keys is pressed, DefWindowProc will send a WM_APPCOMMAND message to a window. DefWindowProc will also bubble the WM_APPCOMMAND message to its parent window. This is similar to the way context menus are invoked with the right mouse button, which is that DefWindowProc sends a WM_CONTEXT message on a right button click, and bubbles it to its parent. Additionally, if DefWindowProc receives a WM_APPCOMMAND message for a top-level window, it will call a shell hook with code HSHELL_APPCOMMAND.

Windows 2000 also supports the Microsoft IntelliMouse® Explorer, which is a mouse with five buttons. The two extra buttons support forward and backward browser navigation. For more information, see XBUTTONs.


Simulating Input

To simulate an uninterrupted series of user input events, use the SendInput function. The function accepts three parameters. The first parameter, cInputs, indicates the number of input events that will be simulated. The second parameter, rgInputs, is an array of INPUT structures, each describing a type of input event and additional information about that event. The last parameter, cbSize, accepts the size of the INPUT structure, in bytes.

The SendInput function works by injecting a series of simulated input events into a device's input stream. The effect is similar to calling the keybd_event or mouse_event function repeatedly, except that the system ensures that no other input events intermingle with the simulated events. When the call completes, the return value indicates the number of input events successfully played. If this value is zero, then input was blocked.

The SendInput function does not reset the keyboard's current state. Therefore, if the user has any keys pressed when you call this function, they might interfere with the events that this function generates. If you are concerned about possible interference, check the keyboard's state with the GetAsyncKeyState function and correct as necessary.


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

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 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 attached to 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 noncharacter 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.

MSG msg;
BOOL bRet;

while (( bRet = GetMessage(&msg, (HWND) NULL, 0, 0)) != 0)
{
    if (bRet == -1);
    {
        // handle the error and possibly exit
    }
    else
    {
        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; // 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((UINT) -1);
                    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((UINT) -1);
                    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.

Function | Description
ActivateKeyboardLayout | Sets the input locale identifier for the calling thread or the current process.
BlockInput | Blocks keyboard and mouse input events from reaching applications.
EnableWindow | Enables or disables mouse and keyboard input to the specified window or control.
GetActiveWindow | Retrieves the window handle to the active window attached to the calling thread's message queue.
GetAsyncKeyState | 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.
GetFocus | Retrieves the handle to the window that has the keyboard focus.
GetKeyboardLayout | Retrieves the active input locale identifier for the specified thread.
GetKeyboardLayoutList | Retrieves the input locale identifiers corresponding to the current set of input locales in the system.
GetKeyboardLayoutName | Retrieves the name of the active input locale identifier.
GetKeyboardState | Copies the status of the 256 virtual keys to the specified buffer.
GetKeyNameText | Retrieves a string that represents the name of a key.
GetKeyState | Retrieves the status of the specified virtual key.
GetLastInputInfo | Retrieves the time of the last input event.
IsWindowEnabled | Determines whether the specified window is enabled for mouse and keyboard input.
keybd_event | Synthesizes a keystroke.
LoadKeyboardLayout | Loads a new input locale identifier.
MapVirtualKey | Translates (maps) a virtual-key code into a scan code or character value, or translates a scan code into a virtual-key code.
MapVirtualKeyEx | Translates (maps) a virtual-key code into a scan code or character value, or translates a scan code into a virtual-key code.
OemKeyScan | Maps OEM ASCII codes 0 through 0x0FF into the OEM scan codes and shift states.
RegisterHotKey | Defines a system-wide hot key.
SendInput | Synthesizes keystrokes, mouse motions, and button clicks.
SetActiveWindow | Activates a window.
SetFocus | Sets the keyboard focus to the specified window.
SetKeyboardState | Copies a 256-byte array of keyboard key states into the calling thread's keyboard input-state table.
ToAscii | Translates the specified virtual-key code and keyboard state to the corresponding character or characters.
ToAsciiEx | Translates the specified virtual-key code and keyboard state to the corresponding character or characters.
ToUnicode | Translates the specified virtual-key code and keyboard state to the corresponding Unicode character or characters.
ToUnicodeEx | Translates the specified virtual-key code and keyboard state to the corresponding Unicode character or characters.
UnloadKeyboardLayout | Unloads an input locale identifier.
UnregisterHotKey | Frees a hot key previously registered by the calling thread.
VkKeyScan | Translates a character to the corresponding virtual-key code and shift state for the current keyboard.
VkKeyScanEx | Translates a character to the corresponding virtual-key code and shift state.

Obsolete Functions

This function is provided only for compatibility with 16-bit versions of Windows.

GetKBCodePage


ActivateKeyboardLayout

The ActivateKeyboardLayout function sets the input locale identifier (formerly called the keyboard layout handle) for the calling thread or the current process. The input locale identifier specifies a locale as well as the physical layout of the keyboard.

HKL ActivateKeyboardLayout(
  HKL hkl,     // input locale identifier
  UINT Flags   // input locale identifier options
);

Parameters

hkl
[in] Input locale identifier to be activated.

Windows 95/98/Me: This parameter can be obtained using LoadKeyboardLayout or GetKeyboardLayoutList, or it can be one of the values in the table that follows.

Windows NT: The input locale identifier 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 locale identifier in the circular list of loaded locale identifiers maintained by the system.
HKL_PREV | Selects the previous locale identifier in the circular list of loaded locale identifiers maintained by the system.

Flags
[in] Specifies how the input locale identifier 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 locale identifiers is reordered by moving the locale identifier to the head of the list. If this bit is not set, the list is rotated without a change of order.

For example, if a user had an English locale identifier active, as well as having French, German, and Spanish locale identifiers loaded (in that order), then activating the German locale identifier with the KLF_REORDER bit set would produce the following order: German, English, French, Spanish. Activating the German locale identifier without the KLF_REORDER bit set would produce the following order: German, Spanish, English, French.

If less than three locale identifiers are loaded, the value of this flag is irrelevant.

KLF_RESET Windows 2000 or later: If set but KLF_SHIFTLOCK is not set, the Caps Lock state is turned off by pressing the Caps Lock key again. If set and KLF_SHIFTLOCK is also set, the Caps Lock state is turned off by pressing either SHIFT key.

These two methods are mutually exclusive, and the setting persists as part of the User's profile in the registry.
KLF_SETFORPROCESS | Windows 2000 or later: Activates the specified locale identifier for the entire process and sends the WM_INPUTLANGCHANGE message to the current thread's Focus or Active window.
KLF_SHIFTLOCK | Windows 2000 or later: This is used with KLF_RESET. See KLF_RESET for an explanation.
KLF_UNLOADPREVIOUS | This flag is unsupported. Use the UnloadKeyboardLayout function instead.

Return Values

Windows NT 3.51 and earlier: The return value is of type BOOL. If the function succeeds, it is nonzero. If the function fails, it is zero.

Windows 95/98, Windows NT 4.0 and later: The return value is of type HKL. If the function succeeds, the return value is the previous input locale identifier. Otherwise, it is zero.

To get extended error information, use the GetLastError function.

Remarks

This function only affects the layout for the current process or thread.

This function is not restricted to keyboard layouts. The hkl parameter is actually an input locale identifier. This is a broader concept than a keyboard layout, since it can also encompass a speech-to-text converter, an IME, or any other form of input. Several input locale identifiers can be loaded at any one time, but only one is active at a time. Loading multiple input locale identifiers makes it possible to rapidly switch between them.

Windows 95/98/Me: An application can create a valid input locale identifier by setting the high word to zero and the low word to a locale identifier. Using such an input locale identifier changes the input language without affecting the physical layout.

When multiple input method editors (IMEs) are allowed for each locale, passing an input locale identifier in which the high word (the device handle) is zero activates the first IME in the list belonging to the locale.

Windows 2000 or later: The KLF_RESET and KLF_SHIFTLOCK flags alter the method by which the Caps Lock state is turned off. By default, the Caps Lock state is turned off by hitting the Caps Lock key again. If only KLF_RESET is set, the default state is reestablished. If KLF_RESET and KLF_SHIFTLOCK are set, the Caps Lock state is turned off by pressing either Caps Lock key. This feature is used to conform to local keyboard behavior standards as well as for personal preferences.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, LoadKeyboardLayout, GetKeyboardLayoutName, UnloadKeyboardLayout


BlockInput

The BlockInput function blocks keyboard and mouse input events from reaching applications.

BOOL BlockInput(
  BOOL fBlockIt  // block option
);

Parmeters

fBlockIt
[in] Specifies the function's purpose. If this parameter is TRUE, keyboard and mouse input events are blocked. If this parameter is FALSE, keyboard and mouse events are unblocked. Note that only the thread that blocked input can successfully unblock input.

Return Values

If the function succeeds, the return value is nonzero.

If input is already blocked, the return value is zero. To get extended error information, call GetLastError.

Remarks

When input is blocked, real physical input from the mouse or keyboard will not affect the the input queue's synchronous key state (reported by GetKeyState and GetKeyboardState), nor will it affect the asynchronous key state (reported by GetAsyncKeyState). However, the thread that is blocking input can affect both of these key states by calling SendInput. No other thread can do this.

The system will unblock input in the following cases:

  • The thread that blocked input unexpectedly exits without calling BlockInput with fBlock set to FALSE. In this case, the system cleans up properly and re-enables input.
  • Windows 95/98/Me: The system displays the Close Program/Fault dialog box. This can occur if the thread faults or if the user presses CTRL+ALT+DEL.
  • Windows 2000 or later: The user presses CTRL+ALT+DEL or the system invokes the Hard System Error modal message box (for example, when a program faults or a device fails).

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winable.h.
Library: Use User32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, GetAsyncKeyState, GetKeyboardState, GetKeyState, SendInput


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   // enable or disable input
);

Parameters

hWnd
[in] Handle to the window to be enabled or disabled.
bEnable
[in] 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 window is being disabled, the system sends a WM_CANCELMODE message. If the enabled state of a window is changing, the system sends a WM_ENABLE message after the WM_CANCELMODE message. (These messages are sent before EnableWindow returns.) If a window is already disabled, 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 attached to 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 attached to the calling thread's message queue. Otherwise, the return value is NULL.

Remarks

To get the handle to the foreground window, you can use GetForegroundWindow.

Windows 98 and Windows NT 4.0 SP3 and later: To get the window handle to the active window in the message queue for another thread, use GetGUIThreadInfo.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, GetForegroundWindow, GetGUIThreadInfo, 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
[in] Specifies one of 256 possible virtual-key codes. For more information, see Virtual-Key Codes.

Windows NT/2000 or later: 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. However, you should not rely on this last behavior; for more information, see the Remarks.

Windows NT/2000 or later: The return value is zero for the following cases:

  • The current desktop is not the active desktop
  • The foreground thread belongs to another process and the desktop does not allow the hook or the journal record.

Windows 95/98/Me: The return value is the global asynchronous key state for each virtual key. The system does not check which thread 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.

Although the least significant bit of the return value indicates whether the key has been pressed since the last query, due to the pre-emptive multitasking nature of Win32, another application can call GetAsyncKeyState and receive the "recently pressed" bit instead of your application. The behavior of the least significant bit of the return value is retained strictly for compatibility with 16-bit Windows applications (which are non-preemptive) and should not be relied upon.

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/2000 or later: 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 attached to 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

GetFocus returns the window with the keyboard focus for the current thread's message queue. If GetFocus returns NULL, another thread's queue may be attached to 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.

Windows 98 and Windows NT 4.0 SP3 and later: To get the window with the keyboard focus on the foreground queue or the queue of another thread, use the GetGUIThreadInfo function.

For an example, see Creating a Combo-box Toolbar.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, AttachThreadInput, GetForegroundWindow, GetGUIThreadInfo, SetFocus, WM_KILLFOCUS, WM_SETFOCUS


GetKBCodePage

The GetKBCodePage function returns the current code page.

Note This function is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should use the GetOEMCP function to retrieve the OEM code-page identifier for the system.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, GetACP, GetOEMCP


GetKeyboardLayout

The GetKeyboardLayout function retrieves the active input locale identifier (formerly called the keyboard layout) for the specified thread. If the idThread parameter is zero, the input locale identifier for the active thread is returned.

HKL GetKeyboardLayout(
  DWORD idThread  // thread identifier
);

Parameters

idThread
[in] Identifies the thread to query or is zero for the current thread.

Return Values

The return value is the input locale identifier 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.

Remarks

The input locale identifier is a broader concept than a keyboard layout, since it can also encompass a speech-to-text converter, an IME, or any other form of input.

Since the keyboard layout can be dynamically changed, applications that cache information about the current keyboard layout should process the WM_INPUTLANGCHANGE message to be informed of changes in the input language.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, ActivateKeyboardLayout, CreateThread, LoadKeyboardLayout , WM_INPUTLANGCHANGE


GetKeyboardLayoutList

The GetKeyboardLayoutList function retrieves the input locale identifiers (formerly called keyboard layout handles) corresponding to the current set of input locales in the system. The function copies the identifiers to the specified buffer.

UINT GetKeyboardLayoutList(
  int nBuff,       // size of array
  HKL FAR *lpList  // array of input locale identifiers
);

Parameters

nBuff
[in] Specifies the maximum number of handles that the buffer can hold.
lpList
[out] Pointer to the buffer that receives the array of input locale identifiers.

Return Values

If the function succeeds, the return value is the number of input locale identifiers 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 input locale identifiers.

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

Remarks

The input locale identifier is a broader concept than a keyboard layout, since it can also encompass a speech-to-text converter, an IME, or any other form of input.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, GetKeyboardLayout


GetKeyboardLayoutName

The GetKeyboardLayoutName function retrieves the name of the active input locale identifier (formerly called the keyboard layout).

BOOL GetKeyboardLayoutName(
  LPTSTR pwszKLID   // input locale identifier name
);

Parameters

pwszKLID
[out] Pointer to the buffer (of at least KL_NAMELENGTH characters in length) that receives the name of the input locale identifier, 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

The input locale identifier is a broader concept than a keyboard layout, since it can also encompass a speech-to-text converter, an IME, or any other form of input.

Windows NT/2000 or later: GetKeyboardLayoutName receives the name of the active input locale identifier for the system.

Windows 95: GetKeyboardLayoutName receives the name of the active input locale identifier for the calling thread.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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   // array of status data
);

Parameters

lpKeyState
[in] 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 through 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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,  // buffer for key name
  int nSize         // maximum length of key name
);

Parameters

lParam
[in] 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
[out] Pointer to a buffer that will receive the key name.
nSize
[in] Specifies the maximum length, in TCHARs, 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 TCHARs, 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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
[in] 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 specified 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 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.

For an example, see Displaying Keyboard Input.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, GetAsyncKeyState, GetKeyboardState, MapVirtualKey, SetKeyboardState


GetLastInputInfo

The GetLastInputInfo function retrieves the time of the last input event.

BOOL GetLastInputInfo(
  PLASTINPUTINFO plii   // last input event
);

Parameters

plii
[out] Pointer to a LASTINPUTINFO structure that receives the time of the last input event.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Remarks

This is useful for input idle detection.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, LASTINPUTINFO


IsWindowEnabled

The IsWindowEnabled function determines whether the specified window is enabled for mouse and keyboard input.

BOOL IsWindowEnabled(
  HWND hWnd   // handle to window
);

Parameters

hWnd
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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/2000 or later: This function has been superseded. Use SendInput instead.

VOID keybd_event(
  BYTE bVk,               // virtual-key code
  BYTE bScan,             // hardware scan code
  DWORD dwFlags,          // function options
  ULONG_PTR dwExtraInfo   // additional keystroke data
);

Parameters

bVk
[in] Specifies a virtual-key code. The code must be a value in the range 1 to 254. For a complete list, see Virtual-Key Codes.
bScan
This parameter is not used.
dwFlags
[in] Specifies various aspects of function operation. This parameter can be one or more of the following values.
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
[in] Specifies an additional value associated with the key stroke.

Return Values

This function has no return value.

Remarks

An application can simulate a press of the PRINTSCRN 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.

Windows NT: The keybd_event function can toggle the NUM LOCK, CAPS LOCK, and SCROLL LOCK keys.

Windows 95: The keybd_event function can toggle only the CAPS LOCK and SCROLL LOCK keys. It cannot toggle the NUM LOCK key.

The following sample program toggles the NUM LOCK light (on Windows NT only) by using keybd_event() with a virtual key of VK_NUMLOCK. It takes a Boolean value that indicates whether the light should be turned off (FALSE) or on (TRUE). The same technique can be used for the CAPS LOCK key (VK_CAPITAL) and the SCROLL LOCK key (VK_SCROLL).

   #include <windows.h>

   void SetNumLock( BOOL bState )
   {
      BYTE keyState[256];

      GetKeyboardState((LPBYTE)&keyState);
      if( (bState && !(keyState[VK_NUMLOCK] & 1)) ||
          (!bState && (keyState[VK_NUMLOCK] & 1)) )
      {
      // Simulate a key press
         keybd_event( VK_NUMLOCK,
                      0x45,
                      KEYEVENTF_EXTENDEDKEY | 0,
                      0 );

      // Simulate a key release
         keybd_event( VK_NUMLOCK,
                      0x45,
                      KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP,
                      0);
      }
   }

   void main()
   {
      SetNumLock( TRUE );
   }

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, GetAsyncKeyState, GetKeyState, keybd_event, MapVirtualKey, SetKeyboardState


LoadKeyboardLayout

The LoadKeyboardLayout function loads a new input locale identifier (formerly called the keyboard layout) into the system. Several input locale identifiers can be loaded at a time, but only one per process is active at a time. Loading multiple input locale identifiers makes it possible to rapidly switch between them.

HKL LoadKeyboardLayout(
  LPCTSTR pwszKLID,  // input locale identifier
  UINT Flags         // input locale identifier options
);

Parameters

pwszKLID
[in] Pointer to the buffer that specifies the name of the input locale identifier 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
[in] Specifies how the input locale identifier is to be loaded. This parameter can be one of the following values.
Value | Meaning
KLF_ACTIVATE | If the specified input locale identifier is not already loaded, the function loads and activates the input locale identifier for the current thread.
KLF_NOTELLSHELL | Prevents a ShellProc hook procedure from receiving an HSHELL_LANGUAGE hook code when the new input locale identifier is loaded. This value is typically used when an application loads multiple input locale identifiers one after another. Applying this value to all but the last input locale identifier delays the shell's processing until all input locale identifiers have been added.
KLF_REORDER | Moves the specified input locale identifier to the head of the input locale identifier list, making that locale identifier the active locale identifier for the current thread. This value reorders the input locale identifier list even if KLF_ACTIVATE is not provided.
KLF_REPLACELANG | Windows 95/98, Windows NT 4.0, and Windows 2000 or later: If the new input locale identifier has the same language identifier as a current input locale identifier, the new input locale identifier replaces the current one as the input locale identifier for that language. If this value is not provided and the input locale identifiers have the same language identifiers, the current input locale identifier is not replaced and the function returns NULL.
KLF_SUBSTITUTE_OK | Substitutes the specified input locale identifier with another locale 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 locale. 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 input locale identifiers to ensure that the user's preference is selected.
KLF_SETFORPROCESS | Windows 2000 or later:: This flag is valid only with KLF_ACTIVATE. Activates the specified input locale identifier for the entire process and sends the WM_INPUTLANGCHANGE message to the current thread's Focus or Active window. Typically, LoadKeyboardLayout activates an input locale identifier only for the current thread.
KLF_UNLOADPREVIOUS | This flag is unsupported. Use the UnloadKeyboardLayout function instead.

Return Values

If the function succeeds, the return value is the input locale identifier to the locale matched with the requested name. If no matching locale is available, the return value is NULL. To get extended error information, call GetLastError.

Remarks

This function only affects the layout for the current process or thread.

The input locale identifier is a broader concept than a keyboard layout, since it can also encompass a speech-to-text converter, an IME, or any other form of input.

An application can and will typically load the default input locale identifier 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 locale or IME, it should read the registry to determine the specific input locale identifier to pass to LoadKeyboardLayout. In this case, a request to activate the default input locale identifier for a locale will activate the first matching one. A specific IME should be activated using an explicit input locale identifier returned from GetKeyboardLayout, GetKeyboardLayoutList, or LoadKeyboardLayout.

Windows 95/98/Me: If an input locale identifier is to be loaded with the same language as a previously loaded input locale identifier and the KLF_REPLACELANG flag is not set, the call fails. Only one loaded locale may be associated with a language. (It is acceptable for multiple IMEs to be loaded with associations to the same language.)

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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.

To specify a handle to the keyboard layout to use for translating the specified code, use the MapVirtualKeyEx function.

UINT MapVirtualKey(
  UINT uCode,     // virtual-key code or scan code
  UINT uMapType   // translation to perform
);

Parameters

uCode
[in] 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
[in] 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 | Windows NT/2000 or later: 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.

Windows NT/2000 or later: 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Keyboard Input Overview, Keyboard Input Functions, GetAsyncKeyState, GetKeyboardState, GetKeyState, MapVirtualKeyEx, 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 an input locale identifier.

UINT MapVirtualKeyEx(
  UINT uCode,     // virtual-key code or scan code
  UINT uMapType,  // translation to perform
  HKL dwhkl       // input locale identifier
);

Parameters

uCode
[in] 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
[in] 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 | Windows NT/2000 or later: 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
[in] Input locale identifier to use for translating the specified code. This parameter can be any input locale identifier 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

The input locale identifier is a broader concept than a keyboard layout, since it can also encompass a speech-to-text converter, an IME, or any other form of input.

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.

Windows NT/2000 or later: 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Keyboard Input Overview, Keyboard Input Functions, GetAsyncKeyState, GetKeyboardState, GetKeyState, LoadKeyboardLayout, 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
[in] Specifies the ASCII value of the OEM character.

Return Values

The low-order word of the return value contains the scan code of the OEM character, and the high-order word contains the shift state, which can be a combination of the following 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 –1.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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,         // handle to window
  int id,            // hot key identifier
  UINT fsModifiers,  // key-modifier options
  UINT vk            // virtual-key code
);

Parameters

hWnd
[in] 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
[in] 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
[in] 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
[in] 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 NT4 and Windows 2000 or later: The F12 key is reserved for use by the debugger at all times, so it should not be registered as a hot key. Even when you are not debugging an application, F12 is reserved in case a kernel-mode debugger or a just-in-time debugger is resident.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
  int cbSize        // size of structure
);

Parameters

nInputs
[in] Specifies the number of structures in the pInputs array.
pInputs
[in] Pointer to an array of INPUT structures. Each structure represents an event to be inserted into the keyboard or mouse input stream.
cbSize
[in] Specifies the size, in bytes, 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. If the function returns zero, the input was already blocked by another thread.

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.

This function does not reset the keyboard's current state. Any keys that are already pressed when the function is called might interfere with the events that this function generates. To avoid this problem, check the keyboard's state with the GetAsyncKeyState function and correct as necessary.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP3 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, INPUT, GetAsyncKeyState, keybd_event, mouse_event


SetActiveWindow

The SetActiveWindow function activates a window. The window must be attached to the calling thread's message queue.

HWND SetActiveWindow(
  HWND hWnd   // handle to window
);

Parameters

hWnd
[in] 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 its application is in the foreground when the system activates the window.

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.

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 attached to another thread's message queue.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 attached to the calling thread's message queue.

HWND SetFocus(
  HWND hWnd   // handle to window
);

Parameters

hWnd
[in] 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 attached to 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 attached to another thread's message queue.

For an example, see Initializing a Dialog Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 of virtual-key codes
);

Parameters

lpKeyState
[in] 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 (or the Japanese KANA) indicator lights on the keyboard. These can be set or cleared using SendInput to simulate keystrokes.

Windows NT: The keybd_event function can also toggle the NUM LOCK, CAPS LOCK, and SCROLL LOCK keys.

Windows 95: The keybd_event function can toggle only the CAPS LOCK and SCROLL LOCK keys. It cannot toggle the NUM LOCK key.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, GetAsyncKeyState, GetKeyboardState, GetKeyState, keybd_event, MapVirtualKey, SendInput


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 keyboard layout handle.

To specify a handle to the keyboard layout to use to translate the specified code, use the ToAsciiEx function.

int ToAscii(
  UINT uVirtKey,           // virtual-key code
  UINT uScanCode,          // scan code
  CONST PBYTE lpKeyState,  // key-state array
  LPWORD lpChar,           // buffer for translated key
  UINT uFlags              // active-menu option
);

Parameters

uVirtKey
[in] Specifies the virtual-key code to be translated.
uScanCode
[in] 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
[in] 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
[out] Pointer to the buffer that receives the translated character or characters.
uFlags
[in] 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).

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, OemKeyScan, ToAsciiEx, 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 input locale identifier.

int ToAsciiEx(
  UINT uVirtKey,           // virtual-key code
  UINT uScanCode,          // scan code
  CONST PBYTE lpKeyState,  // key-state array
  LPWORD lpChar,           // buffer for translated key
  UINT uFlags,             // active-menu option
  HKL dwhkl                // input locale identifier
);

Parameters

uVirtKey
[in] Specifies the virtual-key code to be translated.
uScanCode
[in] 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
[in] 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 SCOLL LOCK keys is ignored.

lpChar
[out] Pointer to the buffer that receives the translated character or characters.
uFlags
[in] Specifies whether a menu is active. This parameter must be 1 if a menu is active, zero otherwise.
dwhkl
[in] Input locale identifier to use to translate the code. This parameter can be any input locale identifier 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 input locale identifier is a broader concept than a keyboard layout, since it can also encompass a speech-to-text converter, an IME, or any other form of input.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, LoadKeyboardLayout, MapVirtualKeyEx, ToUnicodeEx, VkKeyScan


ToUnicode

The ToUnicode function translates the specified virtual-key code and keyboard state to the corresponding Unicode character or characters.

To specify a handle to the keyboard layout to use to translate the specified code, use the ToUnicodeEx function.

int ToUnicode(
  UINT wVirtKey,          // virtual-key code
  UINT wScanCode,         // scan code
  CONST PBYTE lpKeyState, // key-state array
  LPWSTR pwszBuff,        // translated key buffer
  int cchBuff,            // size of translated key buffer
  UINT wFlags             // function options
);

Parameters

wVirtKey
[in] Specifies the virtual-key code to be translated.
wScanCode
[in] 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
[in] 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
[out] Pointer to the buffer that receives the translated Unicode character or characters. Note, however, that this buffer may be returned without being NULL-terminated even though the variable name suggests that it is NULL-terminated.
cchBuff
[in] Specifies the size, in wide characters, of the buffer pointed to by the pwszBuff parameter.
wFlags
[in] Specifies the behavior of the function. If bit 0 is set, 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. However, the buffer may contain more characters than the return value specifies. When this happens, any extra characters are invalid and should be ignored.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, ToAscii, ToUnicodeEx, 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
  CONST PBYTE lpKeyState, // key-state array
  LPWSTR pwszBuff,        // translated key buffer
  int cchBuff,            // size of translated key buffer
  UINT wFlags,            // function options
  HKL dwhkl               // input locale identifier
);

Parameters

wVirtKey
[in] Specifies the virtual-key code to be translated.
wScanCode
[in] 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
[in] 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
[out] Pointer to the buffer that receives the translated Unicode character or characters. Note, however, that this buffer may be returned without being NULL-terminated even though the variable name suggests that it is NULL-terminated.
cchBuff
[in] Specifies the size, in wide characters, of the buffer pointed to by the pwszBuff parameter.
wFlags
[in] Specifies the behavior of the function. If bit 0 is set, a menu is active. Bits 1 through 31 are reserved.
dwhkl
[in] Input locale identifier used to translate the specified code. This parameter can be any input locale identifier 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. However, the buffer may contain more characters than the return value specifies. When this happens, any extra characters are invalid and should be ignored.

Remarks

The input locale identifier is a broader concept than a keyboard layout, since it can also encompass a speech-to-text converter, an IME, or any other form of input.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Keyboard Input Overview, Keyboard Input Functions, LoadKeyboardLayout, ToAsciiEx, VkKeyScan


UnloadKeyboardLayout

The UnloadKeyboardLayout function unloads an input locale identifier (formerly called a keyboard layout).

BOOL UnloadKeyboardLayout(
  HKL hkl   // input locale identifier
);

Parameters

hkl
[in] Input locale identifier 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 input locale identifier was passed.
  • The input locale identifier was preloaded.
  • The input locale identifier is in use.

To get extended error information, call GetLastError.

Remarks

The input locale identifier is a broader concept than a keyboard layout, since it can also encompass a speech-to-text converter, an IME, or any other form of input.

Windows 95: UnloadKeyboardLayout cannot unload the system default input locale identifier. 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/2000 or later: UnloadKeyboardLayout can unload the system default input locale identifier.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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,  // handle to window
  int id      // hot key identifier
);

Parameters

hWnd
[in] 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
[in] 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.

For an example, see Displaying Keyboard Input.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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 input locale identifier.

SHORT VkKeyScanEx(
  TCHAR ch,  // character to translate
  HKL dwhkl  // input locale identifier
);

Parameters

ch
[in] Specifies the character to be translated into a virtual-key code.
dwhkl
[in] Input locale identifier used to translate the character. This parameter can be any input locale identifier 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

The input locale identifier is a broader concept than a keyboard layout, since it can also encompass a speech-to-text converter, an IME, or any other form of input.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Keyboard Input Overview, Keyboard Input Functions, GetAsyncKeyState, GetKeyboardState, GetKeyNameText, GetKeyState, LoadKeyboardLayout, SetKeyboardState, ToAsciiEx


Keyboard Input Structures

The following structures are used for keyboard input.

HARDWAREINPUT
INPUT
KEYBDINPUT
LASTINPUTINFO
MOUSEINPUT


HARDWAREINPUT

The HARDWAREINPUT structure contains information about a simulated message generated by an input device other than a keyboard or mouse.

typedef struct tagHARDWAREINPUT {
  DWORD   uMsg;
  WORD    wParamL;
  WORD    wParamH;
} HARDWAREINPUT, *PHARDWAREINPUT;

Members

uMsg
Value specifying the message generated by the input hardware.
wParamL
Specifies the low-order word of the lParam parameter for uMsg.
wParamH
Specifies the high-order word of the lParam parameter for uMsg.

Requirements

Windows NT/2000 or later: Unsupported .
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Keyboard Input Overview, Keyboard Input Structures, INPUT, SendInput


INPUT

The INPUT structure is used by SendInput to store information for synthesizing input events such as keystrokes, mouse movement, and mouse clicks.

typedef struct tagINPUT {
  DWORD   type;
  union {
      MOUSEINPUT      mi;
      KEYBDINPUT      ki;
      HARDWAREINPUT   hi;
  };
} INPUT, *PINPUT;

Members

type
Specifies the type of the input event. This member 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/98/Me: The event is from input hardware other than a keyboard or mouse. Use the hi structure of the union.

mi
A MOUSEINPUT structure that contains information about a simulated mouse event.
ki
A KEYBDINPUT structure that contains information about a simulated keyboard event.
hi
Windows 95/98/Me: A HARDWAREINPUT structure that contains information about a simulated event from input hardware other than a keyboard or mouse.

Remarks

This structure contains information identical to that used in the parameter list of the keybd_event or mouse_event function.

Windows 2000 or later: INPUT_KEYBOARD supports nonkeyboard input methods, such as handwriting recognition or voice recognition, as if it were text input by using the KEYEVENTF_UNICODE flag. For more information, see the remarks section of KEYBDINPUT.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP3 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Keyboard Input Overview, Keyboard Input Structures, GetMessageExtraInfo, SendInput, SystemParametersInfo, keybd_event, mouse_event, HARDWARE, KEYBDINPUT, MOUSEINPUT


KEYBDINPUT

The KEYBDINPUT structure contains information about a simulated keyboard event.

typedef struct tagKEYBDINPUT {
  WORD      wVk;
  WORD      wScan;
  DWORD     dwFlags;
  DWORD     time;
  ULONG_PTR dwExtraInfo;
} KEYBDINPUT, *PKEYBDINPUT;

Members

wVk
Specifies a virtual-key code. The code must be a value in the range 1 to 254. The Winuser.h header file provides macro definitions (VK_*) for each value. If the dwFlags member specifies KEYEVENTF_UNICODE, wVk must be 0.
wScan
Specifies a hardware scan code for the key. If dwFlags specifies KEYEVENTF_UNICODE, wScan specifies a Unicode character which is to be sent to the foreground application.
dwFlags
Specifies various aspects of a keystroke. This member can be certain combinations of the following 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.
KEYEVENTF_SCANCODE | If specified, wScan identifies the key and wVK is ignored.
KEYEVENTF_UNICODE | Windows 2000 or later: If specified, the system synthesizes a VK_PACKET keystroke. The wVk parameter must be zero. This flag can only be combined with the KEYEVENTF_KEYUP flag. For more information, see the Remarks section.

time
Time stamp for the event, in milliseconds. If this parameter is zero, the system will provide its own time stamp.
dwExtraInfo
Specifies an additional value associated with the keystroke. Use the GetMessageExtraInfo function to obtain this information.

Remarks

Windows 2000 or later: INPUT_KEYBOARD supports nonkeyboard-input methods—such as handwriting recognition or voice recognition—as if it were text input by using the KEYEVENTF_UNICODE flag. If KEYEVENTF_UNICODE is specified, SendInput sends a WM_KEYDOWN or WM_KEYUP message to the foreground thread's message queue with wParam equal to VK_PACKET. Once GetMessage or PeekMessage obtains this message, passing the message to TranslateMessage posts a WM_CHAR message with the Unicode character originally specified by wScan. This Unicode character will automatically be converted to the appropriate ANSI value if it is posted to an ANSI window.

Windows 2000 or later: Set the KEYEVENTF_SCANCODE flag to define keyboard input in terms of the scan code. This is useful to simulate a physical keystroke regardless of which keyboard is currently being used. The virtual key value of a key may alter depending on the current keyboard layout or what other keys were pressed, but the scan code will always be the same.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP3 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Keyboard Input Overview, Keyboard Input Structures, GetMessageExtraInfo, INPUT, SendInput


LASTINPUTINFO

The LASTINPUTINFO structure contains the time of the last input.

typedef struct tagLASTINPUTINFO {
  UINT cbSize;
  DWORD dwTime;
} LASTINPUTINFO, *PLASTINPUTINFO;

Members

cbSize
Must be set to sizeof(LASTINPUTINFO).
dwTime
Tick count when the last input event was received.

Remarks

This function is useful for input idle detection. For more information on tick counts, see GetTickCount.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Keyboard Input Overview, Keyboard Input Structures, GetLastInputInfo , GetTickCount


MOUSEINPUT

The MOUSEINPUT structure contains information about a simulated mouse event.

typedef struct tagMOUSEINPUT {
  LONG    dx;
  LONG    dy;
  DWORD   mouseData;
  DWORD   dwFlags;
  DWORD   time;
  ULONG_PTR   dwExtraInfo;
} MOUSEINPUT, *PMOUSEINPUT;

Members

dx
Specifies the absolute position of the mouse, or the amount of motion since the last mouse event was generated, depending on the value of the dwFlags member. Absolute data is specified as the x coordinate of the mouse; relative data is specified as the number of pixels moved.
dy
Specifies the absolute position of the mouse, or the amount of motion since the last mouse event was generated, depending on the value of the dwFlags member. Absolute data is specified as the y coordinate of the mouse; relative data is specified 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.

Windows 2000 or later: If dwFlags contains MOUSEEVENTF_XDOWN or MOUSEEVENTF_XUP, then mouseData specifies which X buttons were pressed or released. This value may be any combination of the following flags.
Value | Meaning
XBUTTON1 | Set if the first X button is pressed or released.
XBUTTON2 | Set if the second X button is pressed or released.

If dwFlags does not contain MOUSEEVENTF_WHEEL, MOUSEEVENTF_XDOWN, or MOUSEEVENTF_XUP, 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, dx and dy 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_VIRTUALDESK | Windows 2000 or later: Maps coordinates to the entire desktop. Must be used with MOUSEEVENTF_ABSOLUTE.
MOUSEEVENTF_WHEEL | Windows NT/2000 or later: Specifies that the wheel was moved, if the mouse has a wheel. The amount of movement is specified in mouseData.
MOUSEEVENTF_XDOWN | Windows 2000 or later: Specifies that an X button was pressed.
MOUSEEVENTF_XUP | Windows 2000 or later: Specifies that an X button was released.

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.

You cannot specify both the MOUSEEVENTF_WHEEL flag and either MOUSEEVENTF_XDOWN or MOUSEEVENTF_XUP flags simultaneously in the dwFlags parameter, because they both require use of the mouseData field.

time
Time stamp for the event, in milliseconds. If this parameter is 0, the system will provide its own time stamp.
dwExtraInfo
Specifies an additional value associated with the mouse event. An application calls GetMessageExtraInfo to obtain this extra information.

Remarks

If the mouse has moved, indicated by MOUSEEVENTF_MOVE, dx and dy specify information about that movement. The information is specified 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. In a multimonitor system, the coordinates map to the primary monitor.

Windows 2000 or later: If MOUSEEVENTF_VIRTUALDESK is specified, the coordinates map to the entire virtual desktop.

If the MOUSEEVENTF_ABSOLUTE value is not specified, dx and dy specify movement 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. You can obtain and set these values using the SystemParametersInfo function.

The system applies two tests to the specified relative mouse movement. 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 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 system doubles the distance that resulted from applying the first threshold test. It is thus possible for the system to multiply specified relative mouse movement along the x or y axis by up to four times.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP3 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Keyboard Input Overview, Keyboard Input Structures, GetMessageExtraInfo, INPUT, SendInput, SystemParametersInfo


Keyboard Input Messages

The following messages are used to receive and process keyboard input.

WM_ACTIVATE
WM_APPCOMMAND
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_UNICHAR


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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_ACTIVATE
  WPARAM wParam,   // activation and minimization options
  LPARAM lParam    // handle to window (HWND)
);

Parameters

wParam
The low-order word 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.

The high-order word specifies the minimized state of the window being activated or deactivated. A nonzero value indicates the window is minimized.

lParam
Handle to the window being activated or deactivated, depending on the value of the wParam parameter. If the low-order word of wParam is WA_INACTIVE, lParam is the handle to the window being activated. If the low-order word of wParam is WA_ACTIVE or WA_CLICKACTIVE, lParam 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.

Remarks

If the window is being activated and is not minimized, the DefWindowProc function sets the keyboard focus to the window. If the window is activated by a mouse click, it also receives a WM_MOUSEACTIVATE message.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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. The WM_CHAR message contains the character code of the key that was pressed.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_CHAR
  WPARAM wParam,   // character code (TCHAR)
  LPARAM lParam    // key data
);

Parameters

wParam
Specifies the character code of the key.
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 autorepeated 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 lParam 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 lParam parameter.

Whistler: The WM_UNICHAR message is the same as WM_CHAR, except it is designed to send or post Unicode characters to ANSI windows.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Keyboard Input Overview, Keyboard Input Messages, TranslateMessage, WM_KEYDOWN, WM_UNICHAR


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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_DEADCHAR
  WPARAM wParam,   // character code (TCHAR)
  LPARAM lParam    // key data
);

Parameters

wParam
Specifies the character code generated by the dead key.
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 autorepeated 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 lParam 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 lParam parameter.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_GETHOTKEY,             // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_HOTKEY
  WPARAM wParam,   // hot key identifier
  LPARAM lParam    // options and virtual-key code
);

Parameters

wParam
Specifies the identifier of the hot key that generated the message. If the message was generated by a system-defined hot key, this 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.

lParam
The low-order word specifies the keys that were to be pressed in combination with the key specified by the high-order word to generate the WM_HOTKEY message. This word can be one or more 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.

The high-order word 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_SETHOTKEY and WM_GETHOTKEY messages relate to window activation hot keys.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_KEYDOWN
  WPARAM wParam,   // virtual-key code
  LPARAM lParam    // key data
);

Parameters

wParam
Specifies the virtual-key code of the nonsystem key.
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 autorepeated 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 zero if the key is up.
31 | Specifies the transition state. The value is always zero for a WM_KEYDOWN message.

Return Values

An application should return zero if it processes this message.

Remarks

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.

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

Windows 2000 or later: Applications must pass wParam to TranslateMessage without altering it at all.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Keyboard Input Overview, Keyboard Input Messages, DefWindowProc, TranslateMessage,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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_KEYUP
  WPARAM wParam,   // virtual-key code
  LPARAM lParam    // key data
);

Parameters

wParam
Specifies the virtual-key code of the nonsystem key.
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 autorepeated 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.

Remarks

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.

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

Windows 2000 or later: Applications must pass wParam to TranslateMessage without altering it at all.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Keyboard Input Overview, Keyboard Input Messages, DefWindowProc, TranslateMessage, WM_KEYDOWN, WM_SYSCOMMAND


WM_KILLFOCUS

The WM_KILLFOCUS message is sent to a window immediately before it loses the keyboard focus.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_KILLFOCUS
  WPARAM wParam,   // handle to window (HWND)
  LPARAM lParam    // not used
);

Parameters

wParam
Handle to the window that receives the keyboard focus. This parameter can be NULL.
lParam
This parameter is not used.

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.

While processing this message, do not make any function calls that display or activate a window. This causes the thread to yield control and can cause the application to stop responding to messages. For more information, see Message Deadlocks.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_SETFOCUS
  WPARAM wParam,   // handle to window (HWND)
  LPARAM lParam    // not used
);

Parameters

wParam
Handle to the window that has lost the keyboard focus. This parameter can be NULL.
lParam
This parameter is not used.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,             // handle to destination window
  WM_SETHOTKEY,            // message to send
  (WPARAM) wParam,         // virtual-key code and modifiers
  (LPARAM) lParam         // not used; must be zero
);

Parameters

wParam
The low-order word specifies the virtual-key code to associate with the window.

The high-order word can be one or more of the following values.
Value | Meaning
HOTKEYF_ALT | ALT key
HOTKEYF_CONTROL | CTRL key
HOTKEYF_EXT | Extended key
HOTKEYF_SHIFT | SHIFT key

Setting wParam to NULL removes the hot key associated with a window.

lParam
This parameter is not used.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_SYSDEADCHAR
  WPARAM wParam,   // character code (TCHAR)
  LPARAM lParam    // key data
);

Parameters

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.
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 autorepeated 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 lParam parameter.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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 lParam parameter.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_SYSKEYDOWN
  WPARAM wParam,   // virtual-key code
  LPARAM lParam    // key data
);

Parameters

wParam
Specifies the virtual-key code of the key being pressed.
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 autorepeated 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.

Remarks

The DefWindowProc function examines the specified key and generates a WM_SYSCOMMAND message if the key is either TAB or ENTER.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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 lParam parameter.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_SYSKEYUP
  WPARAM wParam,   // virtual-key code
  LPARAM lParam    // key data
);

Parameters

wParam
Specifies the virtual-key code of the key being released.
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 autorepeated 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 zero.
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 zero 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.

Remarks

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.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Keyboard Input Overview, Keyboard Input Messages, DefWindowProc, TranslateAccelerator, WM_SYSCOMMAND, WM_SYSKEYDOWN


WM_UNICHAR

[This is preliminary documentation and subject to change.]

The WM_UNICHAR message is posted to the window with the keyboard focus when a WM_KEYDOWN message is translated by the TranslateMessage function. The WM_UNICHAR message contains the character code of the key that was pressed.

The WM_UNICHAR message is equivalent to WM_CHAR, but it is designed to send or post Unicode characters to ANSI windows.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_UNICHAR
  WPARAM wParam,   // character code (TCHAR)
  LPARAM lParam    // key data
);

Parameters

wParam
Specifies the character code of the key.

If wParam is UNICODE_NOCHAR and the application processes this message, then return TRUE. The DefWindowProc will return FALSE (the default).

If wParam is not UNICODE_NOCHAR, return FALSE. The Unicode DefWindowProc posts a WM_CHAR message with the same parameters and the ANSI DefWindowProc posts either one or two WM_CHAR messages with the corresponding ANSI character(s).

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 autorepeated 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 lParam 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_UNICHAR 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 lParam parameter.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Keyboard Input Overview, Keyboard Input Messages, TranslateMessage, WM_CHAR, WM_KEYDOWN


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)
VK_XBUTTON1 | 05 | Windows 2000 or later: X1 mouse button
VK_XBUTTON2 | 06 | Windows 2000 or later: X2 mouse button
— | 07 | Undefined
VK_BACK | 08 | BACKSPACE key
VK_TAB | 09 | TAB key
— | 0A–0B | Reserved
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
VK_KANA | 15 | IME Kana mode
VK_HANGUEL | 15 | IME Hanguel mode (maintained for compatibility; use VK_HANGUL)
VK_HANGUL | 15 | IME Hangul mode
— | 16 | Undefined
VK_JUNJA | 17 | IME Junja mode
VK_FINAL | 18 | IME final mode
VK_HANJA | 19 | IME Hanja mode
VK_KANJI | 19 | IME Kanji mode
— | 1A | Undefined
VK_ESCAPE | 1B | ESC key
VK_CONVERT | 1C | IME convert
VK_NONCONVERT | 1D | IME nonconvert
VK_ACCEPT | 1E | IME accept
VK_MODECHANGE | 1F | IME mode change request
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
VK_PRINT | 2A | PRINT key
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
 | 30 | 0 key
 | 31 | 1 key
 | 32 | 2 key
 | 33 | 3 key
 | 34 | 4 key
 | 35 | 5 key
 | 36 | 6 key
 | 37 | 7 key
 | 38 | 8 key
 | 39 | 9 key
— | 3A–40 | Undefined
 | 41 | A key
 | 42 | B key
 | 43 | C key
 | 44 | D key
 | 45 | E key
 | 46 | F key
 | 47 | G key
 | 48 | H key
 | 49 | I key
 | 4A | J key
 | 4B | K key
 | 4C | L key
 | 4D | M key
 | 4E | N key
 | 4F | O key
 | 50 | P key
 | 51 | Q key
 | 52 | R key
 | 53 | S key
 | 54 | T key
 | 55 | U key
 | 56 | V key
 | 57 | W key
 | 58 | X key
 | 59 | Y key
 | 5A | Z key
VK_LWIN | 5B | Left Windows key (Microsoft® Natural® keyboard)
VK_RWIN | 5C | Right Windows key (Natural keyboard)
VK_APPS | 5D | Applications key (Natural keyboard)
— | 5E | Reserved
VK_SLEEP | 5F | Computer Sleep key
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–96 | OEM specific
— | 97–9F | Unassigned
VK_LSHIFT | A0 | Left SHIFT key
VK_RSHIFT | A1 | Right SHIFT key
VK_LCONTROL | A2 | Left CONTROL key
VK_RCONTROL | A3 | Right CONTROL key
VK_LMENU | A4 | Left MENU key
VK_RMENU | A5 | Right MENU key
VK_BROWSER_BACK | A6 | Windows 2000 or later: Browser Back key
VK_BROWSER_FORWARD | A7 | Windows 2000 or later: Browser Forward key
VK_BROWSER_REFRESH | A8 | Windows 2000 or later: Browser Refresh key
VK_BROWSER_STOP | A9 | Windows 2000 or later: Browser Stop key
VK_BROWSER_SEARCH | AA | Windows 2000 or later: Browser Search key
VK_BROWSER_FAVORITES | AB | Windows 2000 or later: Browser Favorites key
VK_BROWSER_HOME | AC | Windows 2000 or later: Browser Start and Home key
VK_VOLUME_MUTE | AD | Windows 2000 or later: Volume Mute key
VK_VOLUME_DOWN | AE | Windows 2000 or later: Volume Down key
VK_VOLUME_UP | AF | Windows 2000 or later: Volume Up key
VK_MEDIA_NEXT_TRACK | B0 | Windows 2000 or later: Next Track key
VK_MEDIA_PREV_TRACK | B1 | Windows 2000 or later: Previous Track key
VK_MEDIA_STOP | B2 | Windows 2000 or later: Stop Media key
VK_MEDIA_PLAY_PAUSE | B3 | Windows 2000 or later: Play/Pause Media key
VK_LAUNCH_MAIL | B4 | Windows 2000 or later: Start Mail key
VK_LAUNCH_MEDIA_SELECT | B5 | Windows 2000 or later: Select Media key
VK_LAUNCH_APP1 | B6 | Windows 2000 or later: Start Application 1 key
VK_LAUNCH_APP2 | B7 | Windows 2000 or later: Start Application 2 key
— | B8-B9 | Reserved
VK_OEM_1 | BA | Windows 2000 or later: For the US standard keyboard, the ';:' key
VK_OEM_PLUS | BB | Windows 2000 or later: For any country/region, the '+' key
VK_OEM_COMMA | BC | Windows 2000 or later: For any country/region, the ',' key
VK_OEM_MINUS | BD | Windows 2000 or later: For any country/region, the '-' key
VK_OEM_PERIOD | BE | Windows 2000 or later: For any country/region, the '.' key
VK_OEM_2 | BF | Windows 2000 or later: For the US standard keyboard, the '/?' key
VK_OEM_3 | C0 | Windows 2000 or later: For the US standard keyboard, the '`~' key
— | C1–D7 | Reserved
— | D8–DA | Unassigned
VK_OEM_4 | DB | Windows 2000 or later: For the US standard keyboard, the '[{' key
VK_OEM_5 | DC | Windows 2000 or later: For the US standard keyboard, the '\|' key
VK_OEM_6 | DD | Windows 2000 or later: For the US standard keyboard, the ']}' key
VK_OEM_7 | DE | Windows 2000 or later: For the US standard keyboard, the 'single-quote/double-quote' key
VK_OEM_8 | DF |
— | E0 | Reserved
 | E1 | OEM specific
VK_OEM_102 | E2 | Windows 2000 or later: Either the angle bracket key or the backslash key on the RT 102-key keyboard
 | E3–E4 | OEM specific
VK_PROCESSKEY | E5 | Windows 95/98, Windows NT 4.0, Windows 2000 or later: IME PROCESS key
 | E6 | OEM specific
VK_PACKET | E7 | Windows 2000 or later: Used to pass Unicode characters as if they were keystrokes. The VK_PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods. For more information, see Remark in KEYBDINPUT, SendInput, WM_KEYDOWN, and WM_KEYUP
— | 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 menu items. A dialog box usually contains one or more controls (child windows) with which the user enters text, chooses options, or directs the action. For more information, see the following topics:

  • About Dialog Boxes
  • Using Dialog Boxes
  • Dialog Box Reference

The Microsoft® Win32® API also provides predefined dialog boxes that support common menu items such as Open and Print. Applications that use these menu items should use the common dialog boxes to prompt for this user input, regardless of the type of application. For more information about using common dialog boxes in your applications, see Common Dialog Box Library.


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. It includes the following topics:

  • When to Use a Dialog Box
  • Dialog Box Owner Window
  • Message Boxes
  • Modal Dialog Boxes
  • Modeless Dialog Boxes
  • Dialog Box Templates
  • Dialog Box Procedures
  • Dialog Box Keyboard Interface
  • Dialog Box Settings
  • Custom Dialog Boxes


When to Use a Dialog Box

Most applications use dialog boxes to prompt for additional information for menu items that require user input. Using a dialog box is the only recommended way for an application to retrieve the input. For example, a typical Open menu item requires the name of a file to open, so an application should use a dialog box to prompt the user for the name. In such cases, the application creates the dialog box when the user clicks the menu item and destroys the dialog box immediately after the user supplies the information.

Many applications also use dialog boxes to display information or options while the user works in another window. For example, word processing applications often use a dialog box with a text-search option. While the application searches for the text, the dialog box remains on the screen. The user can then return to the dialog box and search for the same word again; or the user can change the entry in the dialog box and search for a new word. Applications that use dialog boxes in this way typically create one when the user clicks the menu item and continue to display it for as long as the application runs or until the user explicitly closes the dialog box.

To support the different ways applications use dialog boxes, 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 menu items that require additional information before they can proceed. A modeless dialog box allows the user to supply information and return to the previous task without closing the dialog box. Modal dialog boxes are simpler to manage than modeless dialog boxes because they are created, perform their task, and are destroyed by calling a single function.

To create either a modal or modeless dialog box, an application must supply a dialog box template to describe the dialog box style and content; the application must also supply a dialog box procedure to carry out tasks. The dialog box template is a binary description 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.


Dialog Box Owner Window

Most dialog boxes have an owner window (or more simply, an owner). When creating the dialog box, the application sets the owner by specifying the owner's window handle. The system uses the owner to determine the position of the dialog box in the Z order so that the dialog box is always positioned above its owner. Also, the system can send messages to the window procedure of the owner, notifying it of events in the dialog box.

The system automatically hides or destroys the dialog box whenever its owner is hidden or destroyed. This means the dialog box procedure requires no special processing to detect changes to the state of the owner window.

Because the typical dialog box is used in conjunction with a menu item, the owner window is usually the window containing the menu. Although it is possible to create a dialog box that has no owner, it is not recommended. For example, when a modal dialog box has no owner, the system does not disable any of the application's other windows and allows the user to continue to carry out work in the other windows, defeating the purpose of the modal dialog box.

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. Note that currently there is no difference between how MessageBox and MessageBoxEx work.

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 window 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 a handle to 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 clicks Close from the dialog box's window menu or clicks 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 window 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 a handle to 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 clicking 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 Templates

A dialog box template is binary data that describes the dialog box, defining its height, width, style, and the controls it contains. To create a dialog box, the system either loads a dialog box template from the resources in the application's executable file or uses the template passed to it in global memory by the application. In either case, the application must supply a template when creating a dialog box.

A developer creates template resources by using a resource compiler or a dialog box editor. A resource compiler converts a text description into a binary resource, and a dialog box editor saves an interactively constructed dialog box as a binary resource.

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
  • Dialog Box Measurements
  • Dialog Box Controls
  • Dialog Box Window Menu
  • Dialog Box Fonts
  • Templates in Memory


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 specified in the template to the CreateWindowEx function when creating the dialog box. The system may pass one or more extended styles depending on the specified dialog box styles. For example, when the template specifies DS_MODALFRAME, the system uses WS_EX_DLGMODALFRAME when creating the dialog box.

Most dialog boxes are pop-up windows that have a window menu and a title bar. Therefore, the typical template specifies the WS_POPUP, WS_SYSMENU, and WS_CAPTION styles. The template also specifies a border style: WS_BORDER for modeless dialog boxes, and DS_MODALFRAME for modal dialog boxes. A template may specify a window type other than pop-up (such as WS_OVERLAPPED) if it creates a customized window instead of a dialog box.

The system always displays a modal dialog box regardless of whether the WS_VISIBLE style is specified. When the template for a modeless dialog box specifies the WS_VISIBLE style, the system automatically displays the dialog box when it is created. Otherwise, the application is responsible for displaying the dialog box by using the ShowWindow function.

The following table lists the dialog box styles that you can specify when you create a dialog box. You can use these styles in calls to the CreateWindow and CreateWindowEx functions, in the style member of the DLGTEMPLATE and DLGTEMPLATEEX structures, and in the STYLE statement of a dialog box definition in a resource file.

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 applications compiled for Windows NT 3.51. The system automatically applies the three-dimensional look to dialog boxes created by applications compiled for Windows 95/98 and later versions of Windows NT.
DS_ABSALIGN | Indicates that the coordinates of the dialog box are screen coordinates. If this style is not specified, the coordinates are client coordinates.
DS_CENTER | Centers the dialog box in the working area of the monitor that contains the owner window. If no owner window is specified, the dialog box is centered in the working area of a monitor determined by the system. The working area is the area not obscured by the taskbar or any appbars.
DS_CENTERMOUSE | Centers the dialog box on the mouse cursor.
DS_CONTEXTHELP Includes a question mark in the title bar of the dialog box. When the user clicks the question mark, the cursor changes to a question mark with a pointer. If the user then clicks a control in the dialog box, the control receives a WM_HELP message. The control should pass the message to the dialog box procedure, which should call the 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. This is a monospace font compatible with the System font in 16-bit versions of Windows earlier than 3.0.
DS_LOCALEDIT | Applies to 16-bit applications only. This style directs edit controls in the dialog box to allocate memory from the application's data segment. Otherwise, edit controls allocate storage from a global memory object.
DS_MODALFRAME | Creates a dialog box with a modal dialog-box frame that can be combined with a title bar and window menu by specifying the WS_CAPTION and WS_SYSMENU styles.
DS_NOFAILCREATE | Windows 95/98/Me: Creates the dialog box even if errors occur — for example, if a child window cannot be created or if the system cannot create a special data segment for an edit control.
DS_NOIDLEMSG | Suppresses WM_ENTERIDLE messages that the system would otherwise send to the owner of the dialog box while the dialog box is displayed.
DS_SETFONT Indicates that the header of the dialog box template (either standard or extended) contains additional data specifying the font to use for text in the client area and controls of the dialog box. If possible, the system selects a font according to the specified font data. The system passes a handle to the font to the dialog box and to each control by sending them the WM_SETFONT message. For descriptions of the format of this font data, see DLGTEMPLATE and DLGTEMPLATEEX.

If neither DS_SETFONT nor DS_SHELLFONT is specified, the dialog box template does not include the font data.
DS_SETFOREGROUND Causes the system to use the SetForegroundWindow function to bring the dialog box to the foreground. This style is useful for modal dialog boxes that require immediate attention from the user regardless of whether the owner window is the foreground window.

Windows 98/Me, Windows 2000 or later: The system restricts which processes can set the foreground window. For more information, see Foreground and Background Windows.

DS_SHELLFONT Indicates that the dialog box should use the system font. The typeface member of the extended dialog box template must be set to MS Shell Dlg. Otherwise, this style has no effect. It is also recommended that you use the DIALOGEX resource, rather than the DIALOG resource. For more information, see Dialog Box Fonts.

The system selects a font using the font data specified in the pointsize, weight, and italic members. The system passes a handle to the font to the dialog box and to each control by sending them the WM_SETFONT message. For descriptions of the format of this font data, see DLGTEMPLATEEX.

If neither DS_SHELLFONT nor DS_SETFONT is specified, the extended dialog box template does not include the font data.
DS_SYSMODAL This style is obsolete and is included for compatibility with 16-bit versions of Windows. If you specify this style, the system creates the dialog box with the WS_EX_TOPMOST style. This style does not prevent the user from accessing other windows on the desktop.

Do not combine this style with the DS_CONTROL style.


Dialog Box Measurements

Every dialog box template contains measurements that specify the position, width, and height of the dialog box and the controls it contains. These measurements are device independent, so an application can use a single template to create the same dialog box for all types of display devices. This ensures that a dialog box will have the same proportions and appearance on all screens despite differing resolutions and aspect ratios between screens.

The measurements in a dialog box template are specified in dialog template units. To convert measurements from dialog template units to screen units (pixels), use the MapDialogRect function, which takes into account the font used by the dialog box and correctly converts a rectangle from dialog template units into pixels. For dialog boxes that use the system font, you can use the GetDialogBaseUnits function to perform the conversion calculations yourself, although using MapDialogRect is simpler.

The template must specify the initial coordinates of the upper left corner of the dialog box. Usually the coordinates are relative to the upper left corner of the owner window's client area. When the template specifies the DS_ABSALIGN style or the dialog box has 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 specified in the template. The template should specify the appropriate number, type, and order of controls to ensure that the user can enter the input needed to complete the task associated with the dialog box.

For each control, the template specifies style values that define the appearance and operation of the control. Every control is a child window and therefore must have the WS_CHILD style. To ensure that the control is visible when the dialog box is displayed, each control must also have the WS_VISIBLE style. Other commonly used window styles are WS_BORDER for controls that have optional borders, WS_DISABLED for controls that should be disabled when the dialog box is initially created, and WS_TABSTOP and WS_GROUP for controls that can be accessed using the keyboard. The WS_TABSTOP and WS_GROUP styles are used in conjunction with the dialog keyboard interface described later in this topic.

The template may also specify control styles specific to the control's window class. For example, a template that specifies a button control must give a button control style such as BS_PUSHBUTTON or BS_CHECKBOX. The system passes the control styles to the control window procedure through the WM_CREATE message, allowing the procedure to adapt the appearance and operation of the control.

The system converts the position coordinates and the width and height measurements from dialog base units to pixels, before passing these to CreateWindowEx. When the system creates a control, it specifies the dialog box as the parent window. This means the system always interprets the position coordinates of the control as client coordinates, relative to the upper left corner of the dialog box's client area.

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 specified 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 task associated with the dialog box, the template should specify two push buttons, labeled OK and Cancel, with control identifiers of IDOK and IDCANCEL, respectively.

A template also specifies optional text and creation data for a control. The text typically provides labels for button controls or specifies the initial content of a static text control. The creation data is one or more bytes of data that the system passes to the control window procedure when creating the control. Creation data is useful for controls that require more information about their initial content or style than is specified by other data. For example, an application can use creation data to set the initial setting and range for a scroll bar control.


Dialog Box Window Menu

The system gives a dialog box a window menu when the template specifies the WS_SYSMENU style. To prevent inappropriate input, the system automatically disables all items in the menu except Move and Close. The user can click Move to move the dialog box. When the user clicks Close, the system sends a WM_COMMAND message to the dialog box procedure with the wParam parameter set to IDCANCEL. This is identical to the message sent by the Cancel button when the user clicks it. The recommended action for this message is to close the dialog box and cancel the requested task.

Although other menus in dialog boxes are not recommended, a dialog box template can specify a menu by supplying the identifier or the name of a menu resource. In this case, the system loads the resource and creates the menu for the dialog box. Applications typically use menu identifiers or names in templates when using the templates to create custom windows rather than dialog boxes.


Dialog Box Fonts

The system uses the average character width of the dialog box font to calculate the position and dimensions of the dialog box. By default, the system draws all text in a dialog box using the SYSTEM_FONT font.

To specify a font for a dialog box other than the default, you must create the dialog box using a dialog box template. In a template resource, use the FONT statement. In a dialog box template, set the DS_SETFONT or DS_SHELLFONT style and specify a point size and a typeface name. Even if a dialog box template specifies a font in this manner, the system always uses the system font for the dialog box title and dialog box menus.

When the dialog box has the DS_SETFONT or DS_SHELLFONT style, the system sends a WM_SETFONT message to the dialog box procedure and to each control as it creates the control. The dialog box procedure is responsible for saving the font handle passed with the WM_SETFONT message and selecting the handle into the display device context whenever it writes text to the window. Predefined controls do this by default.

Windows 2000 or later: Windows 2000 uses a different system font than Windows NT 4.0 and Windows 95/98. To have your application use the system font no matter which system it is running on, use DS_SHELLFONT with the typeface MS Shell Dlg, and use the DIALOGEX resource instead of the DIALOG resource. The system maps this typeface such that your dialog box will use the Tahoma font on Windows 2000 and the MS Sans Serif font on earlier systems. Note that DS_SHELLFONT has no effect if the typeface is not MS Shell Dlg.


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 of the dialog box window when the system sends a WM_HELP message.
  • If the dialog box has the DS_SETFONT or DS_SHELLFONT style, the header specifies the font weight and indicates whether the font is italic.

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 for the control when the system sends a WM_HELP message.


Dialog Box Procedures

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 TRUE if it processes a message or FALSE if it does not.

Every dialog box procedure has the following form:

BOOL CALLBACK DlgProc(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 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 a pointer to 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 specified 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 specified 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 clicks 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 window menu, and the user clicks a menu item. In particular, the system sends a WM_COMMAND message with the wParam parameter set to IDCANCEL whenever the user clicks Close in the dialog box's window 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_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 to 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 to 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 a handle to 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 Win32-based applications that specify the DS_LOCALEDIT style) and frees any application-defined font (applies to dialog boxes that specify the DS_SETFONT or DS_SHELLFONT 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 a handle to the control having the input focus if the dialog box is being hidden, then calls DefWindowProc to complete the default action.
WM_SYSCOMMAND | Saves a handle to 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 specified 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 specified 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 WS_TABSTOP style specifies the controls to which the user can move by pressing the TAB key or SHIFT+TAB keys.

When the user presses TAB or SHIFT+TAB, the system first determines whether these keys are processed by the control that currently has the input focus. 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.

If the search for the next control with the WS_TABSTOP style encounters a window with the WS_EX_CONTROLPARENT style, the system recursively searches the window's children.

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.

If the search for the next control in the group encounters a window with the WS_EX_CONTROLPARENT style, the system recursively searches the window's children.

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 specified 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 specified 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 specified 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 search for a control with a matching mnemonic encounters a window with the WS_EX_CONTROLPARENT style, the system recursively searches the window's children.

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. For more information, see the following topics:

  • Radio Buttons and Check Boxes
  • Dialog Box Edit Controls
  • List Boxes, Combo Boxes, and Directory Listings
  • Dialog Box Control Messages


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 specified 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 specified 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 specify the window procedure for a specified 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 a pointer to 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 clicks Delete Item 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 menu 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 specifies 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 operation or cancel it. The following statements define the dialog box procedure.

char szItemName[80]; // receives name of item to delete.

BOOL CALLBACK DeleteItemProc(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 a pointer to 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 clicks Go To 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 menu 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 clicks the OK button. The procedure destroys the dialog box when the user clicks 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, 0,0) != 0 && GetMessage(&msg, (HWND) NULL, 0, 0) != -1)
{
    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 task.

                    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 clicks 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 clicks 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 task. 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 task itself or send a message to the owner window, directing it to carry out the operation.


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 specified 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 Windows 95/98 and Windows NT/Windows 2000 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 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.

Function | Description
CreateDialog | Creates a modeless dialog box from a dialog box template resource.
CreateDialogIndirect | Creates a modeless dialog box from a dialog box template in memory.
CreateDialogIndirectParam | Creates a modeless dialog box from a dialog box template in memory.
CreateDialogParam | Creates a modeless dialog box from a dialog box template resource.
DefDlgProc | Calls the default dialog box window procedure to provide default processing for any window messages that a dialog box with a private window class does not process.
DialogBox | Creates a modal dialog box from a dialog box template resource.
DialogBoxIndirect | Creates a modal dialog box from a dialog box template in memory.
DialogBoxIndirectParam | Creates a modal dialog box from a dialog box template in memory.
DialogBoxParam | Creates a modal dialog box from a dialog box template resource.
DialogProc | An application-defined callback function used with the CreateDialog and DialogBox families of functions.
EndDialog | Destroys a modal dialog box.
GetDialogBaseUnits | Retrieves the system's dialog base units.
GetDlgCtrlID | Retrieves the identifier of the specified control.
GetDlgItem | Retrieves a handle to a control in the specified dialog box.
GetDlgItemInt | Translates the text of a specified control in a dialog box into an integer value.
GetDlgItemText | Retrieves the title or text associated with a control in a dialog box.
GetNextDlgGroupItem | Retrieves a handle to the first control in a group of controls that precedes (or follows) the specified control.
GetNextDlgTabItem | Retrieves a handle to the first control that has the WS_TABSTOP style that precedes (or follows) the specified control.
IsDialogMessage | Determines whether a message is intended for the specified dialog box.
MapDialogRect | Converts the specified dialog box units to screen units (pixels).
MessageBox | Creates, displays, and operates a message box.
MessageBoxEx | Creates, displays, and operates a message box.
MessageBoxIndirect | Creates, displays, and operates a message box.
SendDlgItemMessage | Sends a message to the specified control in a dialog box.
SetDlgItemInt | Sets the text of a control in a dialog box to the string representation of a specified integer value.
SetDlgItemText | Sets the title or text of a control in a dialog box.


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 module
  LPCTSTR lpTemplate,   // dialog box template name
  HWND hWndParent,      // handle to owner window
  DLGPROC lpDialogFunc  // dialog box procedure
);

Parameters

hInstance
[in] Handle to the module whose executable file contains the dialog box template.
lpTemplate
[in] Specifies the dialog box template. This parameter is either the pointer to a null-terminated character string that specifies the name of the dialog box template or an integer value that specifies the resource identifier of the dialog box template. If the parameter specifies a resource identifier, its high-order word must be zero and its low-order word must contain the identifier. You can use the MAKEINTRESOURCE macro to create this value.
hWndParent
[in] Handle to the window that owns the dialog box.
lpDialogFunc
[in] 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 or DS_SHELLFONT style) to the dialog box procedure. The function displays the dialog box if the template specifies the WS_VISIBLE style. Finally, CreateDialog returns the window handle to the dialog box.

After CreateDialog returns, the application displays the dialog box (if it is not already displayed) by using the ShowWindow function. The application destroys the dialog box by using the DestroyWindow function. To support keyboard navigation and other dialog box functionality, the message loop for the dialog box must call the IsDialogMessage function.

Windows 95/98/Me: 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.

For an example, see Creating a Modeless Dialog Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Dialog Boxes Overview, Dialog Box Functions, CreateDialogIndirect, CreateDialogIndirectParam, CreateDialogParam, CreateWindowEx, DestroyWindow, DialogBox, DialogProc, IsDialogMessage, 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 module
  LPCDLGTEMPLATE lpTemplate,  // dialog box template
  HWND hWndParent,            // handle to owner window
  DLGPROC lpDialogFunc        // dialog box procedure
);

Parameters

hInstance
[in] Handle to the module that creates the dialog box.
lpTemplate
[in] 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
[in] Handle to the window that owns the dialog box.
lpDialogFunc
[in] 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 or DS_SHELLFONT 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. To support keyboard navigation and other dialog box functionality, the message loop for the dialog box must call the IsDialogMessage 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 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 95/98 and Windows NT/Windows 2000, use the MultiByteToWideChar function to generate these Unicode strings.

Windows 95/98/Me: 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Dialog Boxes Overview, Dialog Box Functions, CreateDialog, CreateDialogIndirectParam, CreateDialogParam, CreateWindowEx, DestroyWindow, DialogProc, DLGITEMTEMPLATE, DLGITEMTEMPLATEEX, DLGTEMPLATE, DLGTEMPLATEEX, IsDialogMessage, 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 module
  LPCDLGTEMPLATE lpTemplate,  // dialog box template
  HWND hWndParent,            // handle to owner window
  DLGPROC lpDialogFunc,       // dialog box procedure
  LPARAM lParamInit           // initialization value
);

Parameters

hInstance
[in] Handle to the module that will create the dialog box.
lpTemplate
[in] Pointer to a global memory object that contains the template 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
[in] Handle to the window that owns the dialog box.
lpDialogFunc
[in] Pointer to the dialog box procedure. For more information about the dialog box procedure, see DialogProc.
lParamInit
[in] 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 or DS_SHELLFONT 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. To support keyboard navigation and other dialog box functionality, the message loop for the dialog box must call the IsDialogMessage 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 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 95/98 and Windows NT/Windows 2000, use the MultiByteToWideChar function to generate these Unicode strings.

Windows 95/98/Me: 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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 WM_INITDIALOG message. An application can use this value to initialize dialog box controls.

HWND CreateDialogParam(
  HINSTANCE hInstance,     // handle to module
  LPCTSTR lpTemplateName,  // dialog box template
  HWND hWndParent,         // handle to owner window
  DLGPROC lpDialogFunc,    // dialog box procedure
  LPARAM dwInitParam       // initialization value
);

Parameters

hInstance
[in] Handle to the module whose executable file contains the dialog box template.
lpTemplateName
[in] Specifies the dialog box template. This parameter is either the pointer to a null-terminated character string that specifies the name of the dialog box template or an integer value that specifies the resource identifier of the dialog box template. If the parameter specifies a resource identifier, its high-order word must be zero and low-order word must contain the identifier. You can use the MAKEINTRESOURCE macro to create this value.
hWndParent
[in] Handle to the window that owns the dialog box.
lpDialogFunc
[in] Pointer to the dialog box procedure. For more information about the dialog box procedure, see DialogProc.
dwInitParam
[in] 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 or DS_SHELLFONT 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) using the ShowWindow function. The application destroys the dialog box by using the DestroyWindow function. To support keyboard navigation and other dialog box functionality, the message loop for the dialog box must call the IsDialogMessage function.

Windows 95/98/Me: 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Dialog Boxes Overview, Dialog Box Functions, CreateDialog, CreateDialogIndirect, CreateDialogIndirectParam, CreateWindowEx, DestroyWindow, DialogProc, IsDialogMessage, MAKEINTRESOURCE, ShowWindow, WM_INITDIALOG, WM_SETFONT


DefDlgProc

The DefDlgProc function calls the default dialog box window procedure to provide default processing for any window messages that a dialog box with a private window class does not process.

LRESULT DefDlgProc(
  HWND hDlg,      // handle to dialog box
  UINT Msg,       // message
  WPARAM wParam,  // first message parameter
  LPARAM lParam   // second message parameter
);

Parameters

hDlg
[in] Handle to the dialog box.
Msg
[in] Specifies the message.
wParam
[in] Specifies additional message-specific information.
lParam
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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_PTR DialogBox(
  HINSTANCE hInstance,  // handle to module
  LPCTSTR lpTemplate,   // dialog box template
  HWND hWndParent,      // handle to owner window
  DLGPROC lpDialogFunc  // dialog box procedure
);

Parameters

hInstance
[in] Handle to the module whose executable file contains the dialog box template.
lpTemplate
[in] Specifies the dialog box template. This parameter is either the pointer to a null-terminated character string that specifies the name of the dialog box template or an integer value that specifies the resource identifier of the dialog box template. If the parameter specifies a resource identifier, its high-order word must be zero and its low-order word must contain the identifier. You can use the MAKEINTRESOURCE macro to create this value.
hWndParent
[in] Handle to the window that owns the dialog box.
lpDialogFunc
[in] 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 because the hWndParent parameter is invalid, the return value is zero. The function returns zero in this case for compatibility with previous versions of Windows. If the function fails for any other reason, 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 or DS_SHELLFONT style) to the dialog box procedure. The function displays the dialog box (regardless of whether the template specifies the WS_VISIBLE style), disables the owner window, and starts its own message loop to retrieve and dispatch messages for the dialog box.

When the dialog box procedure calls the EndDialog function, 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/98/Me: 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.

For an example, see Creating a Modal Dialog Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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_PTR DialogBoxIndirect(
  HINSTANCE hInstance,        // handle to module
  LPCDLGTEMPLATE lpTemplate,  // dialog box template
  HWND hWndParent,            // handle to owner window
  DLGPROC lpDialogFunc        // dialog box procedure
);

Parameters

hInstance
[in] Handle to the module that creates the dialog box.
lpTemplate
[in] Pointer to a global memory object that contains the 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
[in] Handle to the window that owns the dialog box.
lpDialogFunc
[in] 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 because the hWndParent parameter is invalid, the return value is zero. The function returns zero in this case for compatibility with previous versions of Windows. If the function fails for any other reason, 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 or DS_SHELLFONT 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 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 95/98 and Windows NT/Windows 2000, use the MultiByteToWideChar function to generate these Unicode strings.

Windows 95/98/Me: 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.

For an example, see Creating a Template in Memory.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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_PTR DialogBoxIndirectParam(
  HINSTANCE hInstance,             // handle to module
  LPCDLGTEMPLATE hDialogTemplate,  // dialog box template
  HWND hWndParent,                 // handle to owner window
  DLGPROC lpDialogFunc,            // dialog box procedure
  LPARAM dwInitParam               // initialization value
);

Parameters

hInstance
[in] Handle to the module that creates the dialog box.
hDialogTemplate
[in] Pointer to a global memory object that contains the 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
[in] Handle to the window that owns the dialog box.
lpDialogFunc
[in] Pointer to the dialog box procedure. For more information about the dialog box procedure, see DialogProc.
dwInitParam
[in] 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 because the hWndParent parameter is invalid, the return value is zero. The function returns zero in this case for compatibility with previous versions of Windows. If the function fails for any other reason, 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 or DS_SHELLFONT 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 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 95/98 and Windows NT/Windows 2000, use the MultiByteToWideChar function to generate these Unicode strings.

Windows 95/98/Me: 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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_PTR DialogBoxParam(
  HINSTANCE hInstance,     // handle to module
  LPCTSTR lpTemplateName,  // dialog box template
  HWND hWndParent,         // handle to owner window
  DLGPROC lpDialogFunc,    // dialog box procedure
  LPARAM dwInitParam       // initialization value
);

Parameters

hInstance
[in] Handle to the module whose executable file contains the dialog box template.
lpTemplateName
[in] Specifies the dialog box template. This parameter is either the pointer to a null-terminated character string that specifies the name of the dialog box template or an integer value that specifies the resource identifier of the dialog box template. If the parameter specifies a resource identifier, its high-order word must be zero and its low-order word must contain the identifier. You can use the MAKEINTRESOURCE macro to create this value.
hWndParent
[in] Handle to the window that owns the dialog box.
lpDialogFunc
[in] Pointer to the dialog box procedure. For more information about the dialog box procedure, see DialogProc.
dwInitParam
[in] 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 because the hWndParent parameter is invalid, the return value is zero. The function returns zero in this case for compatibility with previous versions of Windows. If the function fails for any other reason, 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 or DS_SHELLFONT style) to the dialog box procedure. The function displays the dialog box (regardless of whether the template specifies the WS_VISIBLE style), disables the owner window, and starts its own message loop to retrieve and dispatch messages for the dialog box.

When the dialog box procedure calls the EndDialog function, DialogBoxParam destroys the dialog box, ends the message loop, enables the owner window (if previously enabled), and returns the nResult parameter specified by the dialog box procedure when it called EndDialog.

Windows 95/98/Me: 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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 CreateDialog and DialogBox families of functions. It processes messages sent to a modal or modeless dialog box. The DLGPROC type defines a pointer to this callback function. DialogProc is a placeholder for the application-defined function name.

INT_PTR CALLBACK DialogProc(
  HWND hwndDlg,  // handle to dialog box
  UINT uMsg,     // message
  WPARAM wParam, // first message parameter
  LPARAM lParam  // second message parameter
);

Parameters

hwndDlg
[in] Handle to the dialog box.
uMsg
[in] Specifies the message.
wParam
[in] Specifies additional message-specific information.
lParam
[in] Specifies additional message-specific information.

Return Values

Typically, the dialog box procedure should return TRUE if it processed the message, and FALSE if it did not. If the dialog box procedure returns FALSE, the dialog manager performs the default dialog operation in response to the message.

If the dialog box procedure processes a message that requires a specific return value, the dialog box procedure should set the desired return value by calling SetWindowLong(hwndDlg, DWL_MSGRESULT, lResult) immediately before returning TRUE. Note that you must call SetWindowLong immediately before returning TRUE; doing so earlier may result in the DWL_MSGRESULT value being overwritten by a nested dialog box message.

The following messages are exceptions to the general rules stated above. Consult the documentation for the specific message for details on the semantics of the return value.

WM_CHARTOITEM
WM_COMPAREITEM
WM_CTLCOLORBTN
WM_CTLCOLORDLG
WM_CTLCOLOREDIT
WM_CTLCOLORLISTBOX
WM_CTLCOLORSCROLLBAR
WM_CTLCOLORSTATIC
WM_INITDIALOG
WM_QUERYDRAGICON
WM_VKEYTOITEM

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

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_PTR nResult   // value to return
);

Parameters

hDlg
[in] Handle to the dialog box to be destroyed.
nResult
[in] 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.

For an example, see Creating a Modal Dialog Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Dialog Boxes Overview, Dialog Box Functions, DialogBox, DialogBoxIndirect, DialogBoxIndirectParam, DialogBoxParam, WM_INITDIALOG


GetDialogBaseUnits

The GetDialogBaseUnits function retrieves 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 function returns 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 = MulDiv( templateunitX, baseunitX, 4 );
pixelY = MulDiv( templateunitY, baseunitY, 8 );

Similarly, to convert from pixels to dialog template units, use the following formulas:

templateunitX = MulDiv( pixelX, 4, baseunitX );
templateunitY = MulDiv( pixelY, 8, baseunitY );

For an example, see Creating a Combo-box Toolbar.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Dialog Boxes Overview, Dialog Box Functions, MapDialogRect


GetDlgCtrlID

The GetDlgCtrlID function retrieves the identifier of the specified control.

int GetDlgCtrlID(
  HWND hwndCtl   // handle to control
);

Parameters

hwndCtl
[in] Handle to 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 is a handle to a top-level window, top-level windows cannot have identifiers and such a return value is never valid.

For an example, see Initializing a Dialog Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Dialog Boxes Overview, Dialog Box Functions, CreateWindow, CreateWindowEx, GetDlgItem


GetDlgItem

The GetDlgItem function retrieves a handle to a control in the specified dialog box.

HWND GetDlgItem(
  HWND hDlg,       // handle to dialog box
  int nIDDlgItem   // control identifier
);

Parameters

hDlg
[in] Handle to the dialog box that contains the control.
nIDDlgItem
[in] Specifies the identifier of the control to be retrieved.

Return Values

If the function succeeds, the return value is the window handle of the specified control.

If the function fails, the return value is NULL, indicating an invalid dialog box handle or a nonexistent control. To get extended error information, call GetLastError.

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.

For an example, see Initializing a Dialog Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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,  // success state
  BOOL bSigned         // signed or unsigned value
);

Parameters

hDlg
[in] Handle to the dialog box that contains the control of interest.
nIDDlgItem
[in] Specifies the identifier of the control whose text is to be translated.
lpTranslated
[out] Pointer to a variable that receives a success or failure value (TRUE indicates success, FALSE indicates failure).

If this parameter is NULL, the function returns no information about success or failure.

bSigned
[in] 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 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 specified 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).

For an example, see Creating a Modeless Dialog Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 to dialog box
  int nIDDlgItem,  // control identifier
  LPTSTR lpString, // pointer to buffer for text
  int nMaxCount    // maximum size of string
);

Parameters

hDlg
[in] Handle to the dialog box that contains the control.
nIDDlgItem
[in] Specifies the identifier of the control whose title or text is to be retrieved.
lpString
[out] Pointer to the buffer to receive the title or text.
nMaxCount
[in] Specifies the maximum length, in TCHARs, of the string to be copied to the buffer pointed to by lpString. If the length of the string exceeds the limit, the string is truncated.

Return Values

If the function succeeds, the return value specifies the number of TCHARs copied to the buffer, not including the terminating null character.

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

Remarks

The GetDlgItemText function sends a WM_GETTEXT message to the control.

For the ANSI version of the function, the number of TCHARs is the number of bytes; for the Unicode version, it is the number of characters.

For an example, see Creating a Modal Dialog Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Dialog Boxes Overview, Dialog Box Functions, GetDlgItemInt, SetDlgItemInt, SetDlgItemText, WM_GETTEXT


GetNextDlgGroupItem

The GetNextDlgGroupItem function retrieves a handle to the first control in a group of controls that precedes (or follows) the specified control in a dialog box.

HWND GetNextDlgGroupItem(
  HWND hDlg,       // handle to dialog box
  HWND hCtl,       // handle to control
  BOOL bPrevious   // direction flag
);

Parameters

hDlg
[in] Handle to the dialog box being searched.
hCtl
[in] Handle to 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
[in] 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 a handle to 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 specified 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.

If the search for the next control in the group encounters a window with the WS_EX_CONTROLPARENT style, the system recursively searches the window's children.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Dialog Boxes Overview, Dialog Box Functions, GetNextDlgTabItem


GetNextDlgTabItem

The GetNextDlgTabItem function retrieves a handle to the first control that has the WS_TABSTOP style that precedes (or follows) the specified control.

HWND GetNextDlgTabItem(
  HWND hDlg,       // handle to dialog box
  HWND hCtl,       // handle to known control
  BOOL bPrevious   // direction flag
);

Parameters

hDlg
[in] Handle to the dialog box to be searched.
hCtl
[in] Handle to 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
[in] 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.

If the search for the next control with the WS_TABSTOP style encounters a window with the WS_EX_CONTROLPARENT style, the system recursively searches the window's children.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 to dialog box
  LPMSG lpMsg  // message to be checked
);

Parameters

hDlg
[in] Handle to the dialog box.
lpMsg
[in] 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 selections for the corresponding dialog box. For example, the TAB key, when pressed, selects the next control or group of controls, and the DOWN ARROW key, when pressed, selects the next control in a group.

Because the IsDialogMessage function performs all necessary translating and dispatching of messages, a message processed by IsDialogMessage must not be passed to the TranslateMessage or DispatchMessage function.

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.

For an example, see Creating a Modeless Dialog Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Dialog Boxes Overview, Dialog Box Functions, DispatchMessage, DM_GETDEFID, DM_SETDEFID, MSG, TranslateMessage, WM_GETDLGCODE, WM_USER


MapDialogRect

The MapDialogRect function converts 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 to dialog box
  LPRECT lpRect   // dialog box coordinates
);

Parameters

hDlg
[in] Handle to a dialog box. This function accepts only handles returned by one of the dialog box creation functions; handles for other windows are not valid.
lpRect
[in/out] 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   = MulDiv( left,   baseunitX, 4 );
right  = MulDiv( right,  baseunitX, 4 );
top    = MulDiv( top,    baseunitY, 8 );
bottom = MulDiv( bottom, baseunitY, 8 );

If the dialog box template has the DS_SETFONT or DS_SHELLFONT style, the base units are the average width and height, in pixels, of the characters in the font specified by the template.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Dialog Boxes Overview, Dialog Box Functions, 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 to owner window
  LPCTSTR lpText,     // text in message box
  LPCTSTR lpCaption,  // message box title
  UINT uType          // message box style
);

Parameters

hWnd
[in] Handle to the owner window of the message box to be created. If this parameter is NULL, the message box has no owner window.
lpText
[in] Pointer to a null-terminated string that contains the message to be displayed.
lpCaption
[in] Pointer to a null-terminated string that contains the dialog box title. If this parameter is NULL, the default title Error is used.
uType
[in] Specifies the contents and behavior of the dialog box. This parameter can be a combination of flags from the following groups of flags.

To indicate the buttons displayed in the message box, specify one of the following values.
Value | Meaning
MB_ABORTRETRYIGNORE | The message box contains three push buttons: Abort, Retry, and Ignore.
MB_CANCELTRYCONTINUE | Windows 2000 or later: The message box contains three push buttons: Cancel, Try Again, Continue. Use this message box type instead of MB_ABORTRETRYIGNORE.
MB_HELP | Windows 95/98, Windows NT 4.0 and later: Adds a Help button to the message box. When the user clicks the Help button or presses F1, the system sends a WM_HELP message to the owner.
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.

To display an icon in the message box, specify one of the following values.
Value | 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.

To indicate the default button, specify one of the following values.
Value | 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.

To indicate the modality of the dialog box, specify one of the following values.
Value | 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.

To specify other options, use one or more of the following values.
Value | Meaning
MB_DEFAULT_DESKTOP_ONLY Windows NT/2000 or later: Same as MB_SERVICE_NOTIFICATION except that the system will display the message box only on the default desktop of the interactive window station. For more information, see Window Stations and Desktops.

Windows NT 4.0 and earlier: If the current input desktop is not the default desktop, MessageBox fails.

Windows 2000 or later: If the current input desktop is not the default desktop, MessageBox does not return until the user switches to the default desktop.

Windows 95/98/Me: This flag has no effect.
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/2000 or later: 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.

Terminal Services: If the calling thread has an impersonation token, the function directs the message box to the session specified in the impersonation token.

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 more information on the changes between Windows NT 3.51 and Windows NT 4.0, see Remarks.
MB_SERVICE_NOTIFICATION_NT3X Windows NT/2000 or later: This value corresponds to the value defined for MB_SERVICE_NOTIFICATION for Windows NT version 3.51.

For more information on the changes between Windows NT 3.51 and Windows NT 4.0, see Remarks.

Return Values

If the function succeeds, the return value is one of the following menu-item values.

Value | Meaning
IDABORT | Abort button was selected.
IDCANCEL | Cancel button was selected.
IDCONTINUE | Continue button was selected.
IDIGNORE | Ignore button was selected.
IDNO | No button was selected.
IDOK | OK button was selected.
IDRETRY | Retry button was selected.
IDTRYAGAIN | Try Again 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.

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

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.

If you create a message box while a dialog box is present, use a handle to 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 NT/2000 or later: The value of MB_SERVICE_NOTIFICATION changed starting with Windows NT 4.0. 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. This mapping is only done for executables that have a version number less than 4.0, as set by the linker.

To build a service that uses MB_SERVICE_NOTIFICATION, and can run on both Windows NT 3.x and Windows NT 4.0, you can do one of the following.

  • At link-time, specify a version number less than 4.0
  • 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.

For an example, see Displaying a Message Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on all platforms.

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 buttons are in the language of the system user interface.

Currently MessageBoxEx and MessageBox work the same way.

int MessageBoxEx(
  HWND hWnd,         // handle to owner window
  LPCTSTR lpText,    // text in message box
  LPCTSTR lpCaption, // message box title
  UINT uType,        // message box style
  WORD wLanguageId   // language identifier
);

Parameters

hWnd
[in] Handle to the owner window of the message box to be created. If this parameter is NULL, the message box has no owner window.
lpText
[in] Pointer to a null-terminated string that contains the message to be displayed.
lpCaption
[in] Pointer to a null-terminated string that contains the dialog box title. If this parameter is NULL, the default title Error is used.
uType
[in] Specifies the contents and behavior of the dialog box. This parameter can be a combination of flags from the following groups of flags.

To indicate the buttons displayed in the message box, specify one of the following values.
Value | Meaning
MB_ABORTRETRYIGNORE | The message box contains three push buttons: Abort, Retry, and Ignore.
MB_CANCELTRYCONTINUE | Windows 2000 or later: The message box contains three push buttons: Cancel, Try Again, Continue. Use this message box type instead of MB_ABORTRETRYIGNORE.
MB_HELP | Windows 95/98, Windows NT 4.0 and later: Adds a Help button to the message box. When the user clicks the Help button or presses F1, the system sends a WM_HELP message to the owner.
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.

To display an icon in the message box, specify one of the following values.
Value | 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.

To indicate the default button, specify one of the following values.
Value | 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.

To indicate the modality of the dialog box, specify one of the following values.
Value | 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.

To specify other options, use one or more of the following values.
Values | Meaning
MB_DEFAULT_DESKTOP_ONLY Windows NT/2000 or later: Same as MB_SERVICE_NOTIFICATION except that the system will display the message box only on the default desktop of the interactive window station. For more information, see Window Stations and Desktops.

Windows NT 4.0 and earlier: If the current input desktop is not the default desktop, MessageBoxEx fails.

Windows 2000 or later: If the current input desktop is not the default desktop, MessageBoxEx does not return until the user switches to the default desktop.

Windows 95/98/Me: This flag has no effect.
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/2000 or later: 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.

Terminal Services: If the calling thread has an impersonation token, the function directs the message box to the session specified in the impersonation token.

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 more information on the changes between Windows NT 3.51 and Windows NT 4.0, see Remarks.
MB_SERVICE_NOTIFICATION_NT3X Windows NT/2000 or later: This value corresponds to the value defined for MB_SERVICE_NOTIFICATION for Windows NT version 3.51.

For more information on the changes between Windows NT 3.51 and Windows NT 4.0, see Remarks.

wLanguageId
[in] Reserved.

Return Values

If the function succeeds, the return value is one of the following menu-item values.

Value | Meaning
IDABORT | Abort button was selected.
IDCANCEL | Cancel button was selected.
IDCONTINUE | Continue button was selected.
IDIGNORE | Ignore button was selected.
IDNO | No button was selected.
IDOK | OK button was selected.
IDRETRY | Retry button was selected.
IDTRYAGAIN | Try Again 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.

If you create a message box while a dialog box is present, use a handle to 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.

Windows NT/2000 or later: The value of MB_SERVICE_NOTIFICATION changed starting with Windows NT 4.0. Windows NT 4.0 provides backward compatibility for pre-existing services by mapping the old value to the new value in the implementation of MessageBoxEx. This mapping is only done for executables that have a version number less than 4.0, as set by the linker.

To build a service that uses MB_SERVICE_NOTIFICATION, and can run on both Windows NT 3.x and Windows NT 4.0, you can do one of the following.

  • At link-time, specify a version number less than 4.0
  • 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on all platforms.

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(
  CONST LPMSGBOXPARAMS lpMsgBoxParams  // message box parameters
);

Parameters

lpMsgBoxParams
[in] Pointer to a MSGBOXPARAMS structure that contains information used to display the message box.

Return Values

If the function succeeds, the return value is one of the following menu-item values.

Value | Meaning
IDABORT | Abort button was selected.
IDCANCEL | Cancel button was selected.
IDCONTINUE | Continue button was selected.
IDIGNORE | Ignore button was selected.
IDNO | No button was selected.
IDOK | OK button was selected.
IDRETRY | Retry button was selected.
IDTRYAGAIN | Try Again 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.

If there is not enough memory to create the message box, the return value is zero.

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.

If you create a message box while a dialog box is present, use a handle to 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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.

LRESULT SendDlgItemMessage(
  HWND hDlg,      // handle to dialog box
  int nIDDlgItem, // control identifier
  UINT Msg,       // message to send
  WPARAM wParam,  // first message parameter
  LPARAM lParam   // second message parameter
);

Parameters

hDlg
[in] Handle to the dialog box that contains the control.
nIDDlgItem
[in] Specifies the identifier of the control that receives the message.
Msg
[in] Specifies the message to be sent.
wParam
[in] Specifies additional message-specific information.
lParam
[in] 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 to the specified control and calling the SendMessage function.

For an example, see Creating a Modeless Dialog Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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 to dialog box
  int nIDDlgItem,  // control identifier
  UINT uValue,     // value to set
  BOOL bSigned     // signed or unsigned indicator
);

Parameters

hDlg
[in] Handle to the dialog box that contains the control.
nIDDlgItem
[in] Specifies the control to be changed.
uValue
[in] Specifies the integer value used to generate the item text.
bSigned
[in] 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.

For an example, see Using the Registry.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 to dialog box
  int nIDDlgItem,    // control identifier
  LPCTSTR lpString   // text to set
);

Parameters

hDlg
[in] Handle to the dialog box that contains the control.
nIDDlgItem
[in] Specifies the control with a title or text to be set.
lpString
[in] 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.

For an example, see Creating a Simple List Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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 {
  DWORD style;
  DWORD dwExtendedStyle;
  short x;
  short y;
  short cx;
  short cy;
  WORD  id;             // on Windows 95/98, this is a byte.
} DLGITEMTEMPLATE, *PDLGITEMTEMPLATE;

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.

Windows 95/98/Me: Only the first byte is used (that is, 255 is the maximum).

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 Specifies 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 95/98 and Windows NT/Windows 2000, 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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;
  sz_Or_Ord title;
  WORD   extraCount;
} 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.
exStyle
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 Specifies 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 the 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.

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 95/98 and Windows NT/Windows 2000, 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.

See Also

Dialog Boxes Overview, Dialog Box Structures, CreateDialogIndirect, CreateDialogIndirectParam, CreateWindowEx, DialogBoxIndirect, DialogBoxIndirectParam, DLGTEMPLATEEX, MapDialogRect, MultiByteToWideChar, WM_CREATE, WM_HELP


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 {
  DWORD style;
  DWORD dwExtendedStyle;
  WORD  cdit;
  short x;
  short y;
  short cx;
  short cy;
} DLGTEMPLATE, *LPDLGTEMPLATE;

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 dialog box style values (such as DS_CENTER).

For a list of window styles, see CreateWindow. For a list of dialog box styles, see Dialog Box Template Styles.

If the style member includes the DS_SETFONT style, 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. The font data 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 sends a WM_SETFONT message to the dialog box and to each control to provide a handle to the font. If DS_SETFONT is not specified, the dialog box template does not include the font data.

Windows 2000 or later: The DS_SHELLFONT style is not supported in the DLGTEMPLATE header.

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 specified, 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 valuespecifies 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 specified, the system creates a font having the specified 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 95/98 and Windows NT/Windows 2000, 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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;
  sz_Or_Ord windowClass;
  WCHAR     title[titleLen];
// The following members exist only if the style member is
// set to DS_SETFONT or DS_SHELLFONT.
  WORD     pointsize;
  WORD     weight;
  BYTE     italic;
  BYTE     charset;
  WCHAR    typeface[stringLen];
} DLGTEMPLATEEX;

Members

dlgVer
Specifies the version number of the extended dialog box template. This member must be 1.
signature
Indicates whether a template is an extended dialog box template. If signature is 0xFFFF, this is 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 dialog box 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 windows styles. This member is not used when creating dialog boxes, but applications that use dialog box templates can use it to create other types of windows.

For a list of extended window styles, see CreateWindowEx.

style
Specifies the style of the dialog box. This member can be a combination of window style values and dialog box style values. For a list of window styles, see CreateWindow. For a list of dialog box styles, see Dialog Box Template Styles.

If style includes the DS_SETFONT or DS_SHELLFONT dialog box style, the DLGTEMPLATEEX header of the extended dialog box template contains four additional members (pointsize, weight, italic, and typeface) 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 sends a WM_SETFONT message to the dialog box and to each control to provide a handle to the font.

For more information, see Dialog Box Fonts.

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.

This member is present only if the style member specifies DS_SETFONT or DS_SHELLFONT.

weight
Specifies the weight of the font. Note that, although this can be any of the values listed for the lfWeight member of the LOGFONT structure, any value that is used will be automatically changed to FW_NORMAL.

This member is present only if the style member specifies DS_SETFONT or DS_SHELLFONT.

italic
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 or DS_SHELLFONT.

charset
Indicates the character set to use. For more information, see the lfcharset member of LOGFONT.

This member is present only if the style member specifies DS_SETFONT or DS_SHELLFONT.

typeface
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 or DS_SHELLFONT.

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.

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 of the DLGITEMTEMPLATEEX structure specifies the number of DLGITEMTEMPLATEEX structures that follow in the template.

Each DLGITEMTEMPLATEEX structure in the template must be aligned on a DWORD boundary. If the style member specifies the DS_SETFONT or DS_SHELLFONT style, the first DLGITEMTEMPLATEEX structure begins on the first DWORD boundary after the typeface string. If these styles are not specified, the first structure begins on the first DWORD boundary after the title string.

The menu, windowClass, title, and typeface arrays must be aligned on WORD boundaries.

If you specify character strings in the menu, windowClass, title, and typeface arrays, you must use Unicode strings. To create code that works on both Windows 95/98 and Windows NT/Windows 2000, 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.

See Also

Dialog Boxes Overview, Dialog Box Structures, CreateDialogIndirect, CreateDialogIndirectParam, DialogBoxIndirect, DialogBoxIndirectParam, DLGITEMTEMPLATEEX, LOGFONT, 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_PTR dwContextHelpId;
  MSGBOXCALLBACK lpfnMsgBoxCallback;
  DWORD     dwLanguageId;
} MSGBOXPARAMS, *PMSGBOXPARAMS;

Members

cbSize
Specifies the structure size, in bytes.
hwndOwner
Handle to the owner window. This member can be NULL.
hInstance
Handle to the module that contains 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 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 supported language identifiers, see Language Identifiers. Note that each localized release of Windows 95/98 and Windows NT/Windows 2000 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Unicode: Declared 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_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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  DM_GETDEFID,              // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  DM_REPOSITION,            // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  DM_SETDEFID,              // message to send
  (WPARAM) wParam,          // button identifier
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the identifier of a push button control that will become the default.
lParam
This parameter is not used.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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 using the specified display device context handle.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_CTLCOLORDLG
  WPARAM wParam,   // handle to DC (HDC)
  LPARAM lParam    // handle to dialog box (HWND)
);

Parameters

wParam
Handle to the device context for the dialog box.
lParam
Handle to the dialog 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 dialog box.

Remarks

By default, the DefWindowProc function selects the default system colors for the dialog box.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Dialog Boxes Overview, Dialog Box Messages, DefWindowProc, RealizePalette, SelectPalette, SetWindowLong


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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_ENTERIDLE
  WPARAM wParam,   // idle reason
  LPARAM lParam    // handle to dialog box or owner (HWND)
);

Parameters

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.

lParam
Handle to the dialog box (if wParam is MSGF_DIALOGBOX) or window containing the displayed menu (if wParam 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_GETDLGCODE
  WPARAM wParam,   // not used
  LPARAM lParam    // message information
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to an MSG structure (or NULL if the system is performing a query).

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.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_INITDIALOG
  WPARAM wParam,   // handle to control (HWND)
  LPARAM lParam    // initialization parameter
);

Parameters

wParam
Handle to the control to receive the default keyboard focus. The system assigns the default keyboard focus only if the dialog box procedure returns TRUE.
lParam
Specifies additional initialization data. This data is passed to the system as the lParam parameter in a call to the CreateDialogIndirectParam, CreateDialogParam, DialogBoxIndirectParam, or DialogBoxParam function used to create the dialog box. For property sheets, this parameter is a pointer to the PROPSHEETPAGE structure used to create the page. This parameter is zero if any other dialog box creation function is used.

Return Values

The dialog box procedure should return TRUE to direct the system to set the keyboard focus to the control specified by wParam. Otherwise, it should return FALSE to prevent the system from setting the default keyboard focus.

The dialog box procedure should return the value directly. The DWL_MSGRESULT value set by the SetWindowLong function is ignored.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NEXTDLGCTL
  WPARAM wParam,   // control identifier
  LPARAM lParam    // wParam usage
);

Parameters

wParam
If lParam is TRUE, this parameter identifies the control that receives the focus. If lParam is FALSE, this parameter indicates whether the next or previous control with the WS_TABSTOP style receives the focus. If wParam is zero, the next control receives the focus; otherwise, the previous control with the WS_TABSTOP style receives the focus.
lParam
The low-order word indicates how the system uses wParam. If the low-order word is TRUE, wParam is a handle associated with the control that receives the focus; otherwise, wParam 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

This message performs additional dialog box management operations beyond those performed by the SetFocus function WM_NEXTDLGCTL updates the default pushbutton border, sets the default control identifier, and automatically selects the text of an edit control (if the target window is an edit 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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 applications.

  • About Messages and Message Queues
  • Using Messages and Message Queues
  • Message and Message Queue Reference


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.

This overview provides information on the following topics:

• Windows Messages

• Message Types

• Message Routing

• Message Handling

• Message Filtering

• Posting and Sending Messages

• Message Deadlocks

• Broadcasting Messages

• Query Messages


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 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 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-defined 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
CBEM | Extended combo box control
CDM | Common dialog box
DBT | Device
DL | Drag list box
DM | Default push button control
DTM | Date and time picker control
EM | Edit control
HDM | Header control
HKM | Hot key control
IPM | IP address control
LB | List box control
LVM | List view control
MCM | Month calendar control
PBM | Progress bar
PGM | Pager control
PSM | Property sheet
RB | Rebar control
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 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
  • 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 one thread-specific message queue 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-specific 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 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. Note that if there is an error, GetMessage returns -1 -- thus the need for the special testing.

MSG msg;
BOOL bRet;

while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
{
    if (bRet == -1)
    {
        // handle the error and possibly exit
    }
    else
    {
        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.


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. It is also useful if an application must process input (hardware) messages before processing posted messages.

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.

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.


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.

Posting Messages

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

Occasionally, you may want to post a message to all top-level windows in the system. An application can post a message to all top-level windows by calling PostMessage and specifying HWND_TOPMOST in the hwnd parameter.

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.

Sending Messages

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 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 a message to all top-level windows by calling SendMessage 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.

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.


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 is attached to the same queue as the sender, it can cause an application deadlock to occur. (Note that journal hooks attach threads to the same queue.)

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
SendMessage

To avoid potential deadlocks in your application, 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 or InSendMessageEx function. Before calling any of the functions in the preceding list while processing a message, the window procedure should first call InSendMessage or InSendMessageEx. If this function returns TRUE, the window procedure must call the ReplyMessage function before any function that causes the thread to yield control.


Broadcasting Messages

Each message consists of a message identifier and two parameters, wParam and lParam. The message identifier is a unique value that specifies the message purpose. The parameters provide additional information that is message-specific, but the wParam parameter is generally a type value that provides more information about the message.

A message broadcast is simply the sending of a message to multiple recipients in the system. To broadcast a message from an application, use the BroadcastSystemMessage function, specifying the recipients of the message. Rather than specify individual recipients, you must specify one or more types of recipients. These types are applications, installable drivers, network drivers, and system-level device drivers. The system sends broadcast messages to all members of each specified type.

The system typically broadcasts messages in response to changes that take place within system-level device drivers or related components. The driver or related component broadcasts the message to applications and other components to notify them of the change. For example, the component responsible for disk drives broadcasts a message whenever the device driver for the floppy disk drive detects a change of media such as when the user inserts a disk in the drive.

The system broadcasts messages to recipients in this order: system-level device drivers, network drivers, installable drivers, and applications. This means that system-level device drivers, if chosen as recipients, always get the first opportunity to respond to a message. Within a given recipient type, no driver is guaranteed to receive a given message before any other driver. This means that a message intended for a specific driver must have a globally-unique message identifier so that no other driver unintentionally processes it.

You can also broadcast messages to all top-level windows by specifying HWND_BROADCAST in the SendMessage, SendMessageCallback, SendMessageTimeout, or SendNotifyMessage function.

Applications receive messages through the window procedure of their top-level windows. Messages are not sent to child windows. Services can receive messages through a window procedure or their service control handlers.

Note System-level device drivers use a related, system-level function to broadcast system messages.


Query Messages

You can create your own custom messages and use them to coordinate activities between your applications and other components in the system. This is especially useful if you have created your own installable drivers or system-level device drivers. Your custom messages can carry information to and from your driver and the applications that use the driver.

To poll recipients for permission to carry out a given action, use a query message. You can generate your own query messages by setting the BSF_QUERY value in the dwFlags parameter when calling BroadcastSystemMessage. Each recipient of the query message must return TRUE for the function to send the message to the next recipient. If any recipient returns BROADCAST_QUERY_DENY, the broadcast ends immediately and the function returns a zero.

Windows 95/98/Me: You can create installable drivers that broadcast and process messages. An installable driver is a dynamic-link library (DLL) that exports a DriverProc function. The driver receives messages through its DriverProc function and can broadcast messages using BroadcastSystemMessage. Installable drivers are typically used to support multimedia devices, such as sound boards, but can be used for other devices and purposes too.

Windows 95/98/Me: Network drivers are dynamic-link libraries that provide the underlying support for applications that use the network functions to connect to and browse network resources. System-level device drivers are system-specific executable components that provide direct access to and management of the hardware devices of the computer. The details regarding how these components process system messages is beyond the scope of this overview.


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;
    BOOL bRet;
    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( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
    {
        if (bRet == -1)
        {
            // handle the error and possibly exit
        }
        else
        {
            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;
BOOL bRet;
HACCEL haccel;
//
// Perform initialization and create a main window.
//

while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
{
    if (bRet == -1)
    {
        // handle the error and possibly exit
    }
    else
    {
        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

Platform SDK: Windows User Interface

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

Platform SDK: Windows User Interface

Message and Message Queue Functions

The following functions are used with messages and message queues.

Function | Description
BroadcastSystemMessage | Sends a message to the specified recipients.
BroadcastSystemMessageEx | Sends a message to the specified recipients and returns additional information.
DispatchMessage | Dispatches a message to a window procedure.
GetInputState | Determines whether there are mouse-button or keyboard messages in the calling thread's message queue.
GetMessage | Retrieves a message from the calling thread's message queue.
GetMessageExtraInfo | Retrieves the extra message information for the current thread.
GetMessagePos | Retrieves the position of the cursor for the last message retrieved by GetMessage.
GetMessageTime | Retrieves the message time for the last message retrieved by GetMessage.
GetQueueStatus | Indicates the type of messages found in the calling thread's message queue.
InSendMessage | Determines whether the current window procedure is processing a message that was sent from another thread.
InSendMessageEx | Determines whether the current window procedure is processing a message that was sent from another thread.
PeekMessage | Dispatches incoming sent messages, checks the thread message queue for a posted message, and retrieves the message (if any exist).
PostMessage | Posts a message in the message queue associated with the thread that created the specified window and returns without waiting for the thread to process the message.
PostQuitMessage | Indicates to the system that a thread has made a request to terminate (quit).
PostThreadMessage | Posts a message to the message queue of the specified thread.
RegisterWindowMessage | Defines a new window message that is guaranteed to be unique throughout the system.
ReplyMessage | Replies to a message sent through the SendMessage function without returning control to the function that called SendMessage.
SendAsyncProc | An application-defined callback function used with the SendMessageCallback function.
SendMessage | Sends the specified message to a window or windows.
SendMessageCallback | Sends the specified message to a window or windows. It calls the window procedure for the specified window and returns immediately.
SendMessageTimeout | 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.
SendNotifyMessage | Sends the specified message to a window or windows. 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.
SetMessageExtraInfo | Sets the extra message information for the current thread.
TranslateMessage | Translates virtual-key messages into character messages.
WaitMessage | Yields control to other threads when a thread has no other messages in its message queue.


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.

To receive additional information if the request is defined, use the BroadcastSystemMessageEx function.

long BroadcastSystemMessage(
  DWORD dwFlags,           // broadcast option
  LPDWORD lpdwRecipients,  // recipients
  UINT uiMessage,          // message
  WPARAM wParam,           // first message parameter
  LPARAM lParam            // second message parameter
);

Parameters

dwFlags
[in] Specifies the broadcast option. This parameter can be one or more of the following values.
Value | Meaning
BSF_ALLOWSFW | Windows 2000 or later: Enables the recipient to set the foreground window while processing the message.
BSF_FLUSHDISK | Flushes the disk after each recipient processes the message.
BSF_FORCEIFHUNG | Continues to broadcast the message, even if the time-out period elapses or one of the recipients is hung.
BSF_IGNORECURRENTTASK | Does not send the message to windows that belong to the current task. This prevents an application from receiving its own message.
BSF_NOHANG | Forces a hung application to time out. If one of the recipients times out, do not continue broadcasting the message.
BSF_NOTIMEOUTIFNOTHUNG | Waits for a response to the message, as long as the recipient is not hung. Does not time out.
BSF_POSTMESSAGE | Posts the message. Do not use in combination with BSF_QUERY.
BSF_QUERY | Sends the message to one recipient at a time, sending to a subsequent recipient only if the current recipient returns TRUE.
BSF_SENDNOTIFYMESSAGE | Windows 2000 or later: Sends the message using SendNotifyMessage function. Do not use in combination with BSF_QUERY.

lpdwRecipients
[in] Pointer to a variable that contains and receives information about the recipients of the message. This parameter can be one or more of the following values.
Value | Meaning
BSM_ALLCOMPONENTS | Broadcast to all system components.
BSM_ALLDESKTOPS | Windows NT/2000 or later: Broadcast to all desktops. Requires the SE_TCB_NAME privilege.
BSM_APPLICATIONS | Broadcast to applications.
BSM_INSTALLABLEDRIVERS | Windows 95/98/Me: Broadcast to installable drivers.
BSM_NETDRIVER | Windows 95/98/Me: Broadcast to network drivers.
BSM_VXDS | Windows 95/98/Me: 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
[in] Specifies the message to be sent.
wParam
[in] Specifies additional message-specific information.
lParam
[in] Specifies additional message-specific information.

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.

For an example, see Terminating a Process.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, BroadcastSystemMessageEx, SendNotifyMessage


BroadcastSystemMessageEx

[This is preliminary documentation and subject to change.]

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

This function is similar to BroadcastSystemMessage except that this function can return more information from the recipients.

long BroadcastSystemMessageEx(
  DWORD dwFlags,           // broadcast option
  LPDWORD lpdwRecipients,  // recipients
  UINT uiMessage,          // message
  WPARAM wParam,           // first message parameter
  LPARAM lParam,           // second message parameter
  PBSMINFO pBSMInfo        // additional information
);

Parameters

dwFlags
[in] Specifies the broadcast option. This parameter can be one or more of the following values.
Value | Meaning
BSF_ALLOWSFW | Enables the recipient to set the foreground window while processing the message.
BSF_FLUSHDISK | Flushes the disk after each recipient processes the message.
BSF_FORCEIFHUNG | Continues to broadcast the message, even if the time-out period elapses or one of the recipients is hung.
BSF_IGNORECURRENTTASK | Does not send the message to windows that belong to the current task. This prevents an application from receiving its own message.
BSF_LUID | Whistler: If BSF_LUID is set, the message is sent to the window that has the same LUID as specified in BSMINFO .luid.
BSF_NOHANG | Forces a hung application to time out. If one of the recipients times out, do not continue broadcasting the message.
BSF_NOTIMEOUTIFNOTHUNG | Waits for a response to the message, as long as the recipient is not hung. Does not time out.
BSF_POSTMESSAGE | Posts the message. Do not use in combination with BSF_QUERY.
BSF_RETURNHDESK | Whistler: If access is denied and both this and BSF_QUERY are set, BSMINFO returns both the desktop handle and the window handle. If access is denied and only BSF_QUERY is set, only the window handle is returned by BSMINFO.
BSF_QUERY | Sends the message to one recipient at a time, sending to a subsequent recipient only if the current recipient returns TRUE.
BSF_SENDNOTIFYMESSAGE | Sends the message using SendNotifyMessage function. Do not use in combination with BSF_QUERY..

lpdwRecipients
[in] Pointer to a variable that contains and receives information about the recipients of the message. This parameter can be one or more of the following values.
Value | Meaning
BSM_ALLCOMPONENTS | Broadcast to all system components.
BSM_ALLDESKTOPS | Broadcast to all desktops. Requires the SE_TCB_NAME privilege.
BSM_APPLICATIONS | Broadcast to applications.

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
[in] Specifies the message to be sent.
wParam
[in] Specifies additional message-specific information.
lParam
[in] Specifies additional message-specific information.
pBSMInfo
[out] Pointer to a BSMINFO structure that contains additional information if the request is denied and dwFlags is set to BSF_QUERY.

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.

If the caller's thread is on a desktop other than that of the window that denied the request, the caller must call SetThreadDesktop(hdesk) to query anything on that window. Also, the caller must call CloseDesktop on the returned hdesk handle.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Whistler.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, BroadcastSystemMessage, BSMINFO, SendNotifyMessage


DispatchMessage

The DispatchMessage function dispatches a message to a window procedure. It is typically used to dispatch a message retrieved by the GetMessage function.

LRESULT DispatchMessage(
  CONST MSG *lpmsg   // message information
);

Parameters

lpmsg
[in] 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.

For an example, see Creating a Message Loop.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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. The function dispatches incoming sent messages until a posted message is available for retrieval.

Unlike GetMessage, the PeekMessage function does not wait for a message to be posted before returning.

BOOL GetMessage(
  LPMSG lpMsg,         // message information
  HWND hWnd,           // handle to window
  UINT wMsgFilterMin,  // first message
  UINT wMsgFilterMax   // last message
);

Parameters

lpMsg
[out] Pointer to an MSG structure that receives message information from the thread's message queue.
hWnd
[in] Handle to the window whose messages are to be retrieved. The window must belong to the calling thread. The following 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 using the PostThreadMessage function.

wMsgFilterMin
[in] Specifies the integer value of the lowest message value to be retrieved. Use WM_KEYFIRST to specify the first keyboard message or WM_MOUSEFIRST to specify the first mouse message.

Whistler: Use WM_INPUT here and in wMsgFilterMax to specify only the WM_INPUT messages.

If wMsgFilterMin and wMsgFilterMax are both zero, GetMessage returns all available messages (that is, no range filtering is performed).

wMsgFilterMax
[in] Specifies the integer value of the highest message value to be retrieved. Use WM_KEYLAST to specify the first keyboard message or WM_MOUSELAST to specify the last mouse message.

Whistler: Use WM_INPUT here and in wMsgFilterMin to specify only the WM_INPUT messages.

If wMsgFilterMin and wMsgFilterMax are both zero, GetMessage returns all available messages (that is, no range filtering is performed).

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.

Warning Because the return value can be nonzero, zero, or -1, 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. Instead, use code like this:

BOOL bRet;

while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
{
    if (bRet == -1)
    {
        // handle the error and possibly exit
    }
    else
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}

Remarks

An application typically uses the return value to determine whether to end the main message loop and exit the program.

The GetMessage function 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. Note that an application can only use the low word in the wMsgFilterMin and wMsgFilterMax parameters; the high word is reserved for the system.

Note that GetMessage always retrieves WM_QUIT messages, no matter which values you specify for wMsgFilterMin and wMsgFilterMax.

During this call, the system delivers pending messages that were sent to windows owned by the calling thread using the SendMessage, SendMessageCallback, SendMessageTimeout, or SendNotifyMessage function. The system may also process internal events. Messages are processed in the following order:

  • Sent messages
  • Posted messages
  • Input (hardware) messages and system internal events
  • Sent messages (again)
  • WM_PAINT messages
  • WM_TIMER messages

To retrieve input messages before posted messages, use the wMsgFilterMin and wMsgFilterMax parameters.

GetMessage does not remove WM_PAINT messages from the queue. The messages remain in the queue until processed.

For an example, see Creating a Message Loop.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, IsChild, MSG, PeekMessage, PostMessage, PostThreadMessage, WaitMessage


GetMessageExtraInfo

The GetMessageExtraInfo function retrieves the extra message information for the current thread. Extra message information is an application- or driver-defined value associated with the current thread's message queue.

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

Remarks

To set a thread's extra message information, use the SetMessageExtraInfo function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, GetMessage, PeekMessage, SetMessageExtraInfo


GetMessagePos

The GetMessagePos function retrieves the cursor position for the last message retrieved by the GetMessage function.

To determine the current position of the cursor, use the GetCursorPos function.

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.

Important Do not use the LOWORD or HIWORD macros to extract the x- and y- coordinates of the cursor position because these macros 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 retrieves the message time for the last message retrieved by the GetMessage function. 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, GetMessage, GetMessagePos


GetQueueStatus

The GetQueueStatus function indicates the type of messages found in the calling thread's message queue.

DWORD GetQueueStatus(
  UINT flags   // message types
);

Parameters

flags
[in] Specifies the types of messages for which to check. This parameter can be one or more 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. This is composed of QS_KEY and QS_MOUSE.

Whistler: This also includes QS_RAWINPUT.
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_RAWINPUT | Whistler: A raw input message is in the queue. For more information, see Raw Input.
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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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.

To obtain additional information about how the message was sent, use the InSendMessageEx 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.

For an example, see Sending a Message.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, InSendMessageEx, SendMessage


InSendMessageEx

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

DWORD InSendMessageEx(
  LPVOID lpReserved      // not used; 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.

Remarks

To determine if the sender is blocked, use the following test:

fBlocked = ( InSendMessageEx(NULL) & (ISMEX_REPLIED|ISMEX_SEND) ) == ISMEX_SEND;

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, SendMessage, SendMessageCallback, SendMessageTimeout, SendNotifyMessage


PeekMessage

The PeekMessage function dispatches incoming sent messages, checks the thread message queue for a posted message, and retrieves the message (if any exist).

BOOL PeekMessage(
  LPMSG lpMsg,         // message information
  HWND hWnd,           // handle to window
  UINT wMsgFilterMin,  // first message
  UINT wMsgFilterMax,  // last message
  UINT wRemoveMsg      // removal options
);

Parameters

lpMsg
[out] Pointer to an MSG structure that receives message information.
hWnd
[in] Handle to the window whose messages are to be examined. The window must belong to the current thread.

If hWnd is NULL, PeekMessage retrieves messages for any window that belongs to the current thread. If hWnd is INVALID_HANDLE_VALUE, PeekMessage retrieves messages whose hWnd value is NULL, as posted by the PostThreadMessage function.

wMsgFilterMin
[in] Specifies the value of the first message in the range of messages to be examined. Use WM_KEYFIRST to specify the first keyboard message or WM_MOUSEFIRST to specify the first mouse message.

If wMsgFilterMin and wMsgFilterMax are both zero, PeekMessage returns all available messages (that is, no range filtering is performed).

wMsgFilterMax
[in] Specifies the value of the last message in the range of messages to be examined. Use WM_KEYLAST to specify the first keyboard message or WM_MOUSELAST to specify the last mouse message.

If wMsgFilterMin and wMsgFilterMax are both zero, PeekMessage returns all available messages (that is, no range filtering is performed).

wRemoveMsg
[in] 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 98/Me, Windows 2000 or later: Process mouse and keyboard messages.
PM_QS_PAINT | Windows 98/Me, Windows 2000 or later: Process paint messages.
PM_QS_POSTMESSAGE | Windows 98/Me, Windows 2000 or later: Process all posted messages, including timers and hotkeys.
PM_QS_SENDMESSAGE | Windows 98/Me, Windows 2000 or later: 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

PeekMessage 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. Note that an application can only use the low word in the wMsgFilterMin and wMsgFilterMax parameters; the high word is reserved for the system.

Note that PeekMessage always retrieves WM_QUIT messages, no matter which values you specify for wMsgFilterMin and wMsgFilterMax.

During this call, the system delivers pending messages that were sent to windows owned by the calling thread using the SendMessage, SendMessageCallback, SendMessageTimeout, or SendNotifyMessage function. The system may also process internal events. Messages are processed in the following order:

  • Sent messages
  • Posted messages
  • Input (hardware) messages and system internal events
  • Sent messages (again)
  • WM_PAINT messages
  • WM_TIMER messages

To retrieve input messages before posted messages, use the wMsgFilterMin and wMsgFilterMax parameters.

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.

For an example, see Examining a Message Queue.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, GetMessage, IsChild, MSG, WaitForInputIdle, WaitMessage


PostMessage

The PostMessage function places (posts) a message in the message queue associated with the thread that created the specified window and returns without waiting for the thread to process the message.

To post a message in the message queue associate with a thread, use the PostThreadMessage function.

BOOL PostMessage(
  HWND hWnd,      // handle to destination window
  UINT Msg,       // message
  WPARAM wParam,  // first message parameter
  LPARAM lParam   // second message parameter
);

Parameters

hWnd
[in] Handle to the window whose window procedure is to receive the message. The following 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
[in] Specifies the message to be posted.
wParam
[in] Specifies additional message-specific information.
lParam
[in] 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

Messages in a message queue are retrieved by calls to the GetMessage or PeekMessage function.

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.

Do not post the WM_QUIT message using PostMessage; use the PostQuitMessage function.

Windows 2000 or later: There is a limit of 10,000 posted messages per message queue. This limit should be sufficiently large. If your application exceeds the limit, it should be redesigned to avoid consuming so many system resources. To adjust this limit, modify the following registry key:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows\USERPostMessageLimit.

The minimum acceptable value is 4000.

For an example, see Initiating a Data Link.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, GetMessage, PeekMessage, PostQuitMessage, PostThreadMessage, RegisterWindowMessage, 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
[in] 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.

For an example, see Posting a Message.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 posts a message to the message queue of the specified thread. It returns without waiting for the thread to process the message.

BOOL PostThreadMessage(
  DWORD idThread, // thread identifier
  UINT Msg,       // message
  WPARAM wParam,  // first message parameter
  LPARAM lParam   // second message parameter
);

Parameters

idThread
[in] Identifier of the thread to which the message is to 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.

Windows 2000 or later: This thread must either belong to the same desktop as the calling thread or to a process with the same LUID. Otherwise, the function fails and returns ERROR_INVALID_THREAD_ID.

Msg
[in] Specifies the type of message to be posted.
wParam
[in] Specifies additional message-specific information.
lParam
[in] 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.

Messages sent by PostThreadMessage are not associated with a window. Messages that are not associated with a window cannot be dispatched by the DispatchMessage function. Therefore, if the recipient thread is in a modal loop (as used by MessageBox or DialogBox), the messages will be lost. To intercept thread messages while in a modal loop, use a thread-specific hook.

Windows 2000 or later: There is a limit of 10,000 posted messages per message queue. This limit should be sufficiently large. If your application exceeds the limit, it should be redesigned to avoid consuming so many system resources. To adjust this limit, modify the following registry key:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows\USERPostMessageLimit.

The minimum acceptable value is 4000.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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 message value can be used when sending or posting messages.

UINT RegisterWindowMessage(
  LPCTSTR lpString   // message string
);

Parameters

lpString
[in] 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.)

For an example, see Finding Text.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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
[in] 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.

For an example, see Sending a Message.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 to destination window
  UINT uMsg,        // message
  ULONG_PTR dwData, // application-defined value
  LRESULT lResult   // result of message processing
);

Parameters

hwnd
[in] 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
[in] Specifies the message.
dwData
[in] Specifies an application-defined value sent from the SendMessageCallback function.
lResult
[in] Specifies the result of the message processing. This value 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

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. It calls the window procedure for the specified window and does not return until the window procedure has processed the message.

To send a message and return immediately, use the SendMessageCallback or SendNotifyMessage function. To post a message to a thread's message queue and return immediately, use the PostMessage or PostThreadMessage function.

LRESULT SendMessage(
  HWND hWnd,      // handle to destination window
  UINT Msg,       // message
  WPARAM wParam,  // first message parameter
  LPARAM lParam   // second message parameter
);

Parameters

hWnd
[in] 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
[in] Specifies the message to be sent.
wParam
[in] Specifies additional message-specific information.
lParam
[in] Specifies additional message-specific information.

Return Values

The return value specifies the result of the message processing; it 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. However, the sending thread will process messages from its queue while waiting for its message to be processed. To prevent this, use SendMessageTimeout with SMTO_BLOCK set.

For an example, see Processing Keyboard Input.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, InSendMessage, PostMessage, PostThreadMessage, RegisterWindowMessage SendDlgItemMessage, SendMessageCallback, SendMessageTimeout, SendNotifyMessage


SendMessageCallback

The SendMessageCallback function sends the specified message to a window or windows. It 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 to window
  UINT Msg,                 // message
  WPARAM wParam,            // first message parameter
  LPARAM lParam,            // second message parameter
  SENDASYNCPROC lpCallBack, // callback function
  ULONG_PTR dwData          // application-defined value
);

Parameters

hWnd
[in] 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
[in] Specifies the message to be sent.
wParam
[in] Specifies additional message-specific information.
lParam
[in] Specifies additional message-specific information.
lpCallBack
[in] Pointer to a callback function that the system calls after the window procedure processes the message. For more information, see SendAsyncProc.

If hWnd is HWND_BROADCAST, the system calls the SendAsyncProc callback function once for each top-level window.

dwData
[in] Specifies an application-defined value to be sent to the callback function pointed to by the lpCallBack 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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 to window
  UINT Msg,             // message
  WPARAM wParam,        // first message parameter
  LPARAM lParam,        // second message parameter
  UINT fuFlags,         // send options
  UINT uTimeout,        // time-out duration
  PDWORD_PTR lpdwResult // return value for synchronous call
);

Parameters

hWnd
[in] 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. The function does not return until each window has timed out. Therefore, the total wait time can be up to uTimeout times the number of top-level windows.

Msg
[in] Specifies the message to be sent.
wParam
[in] Specifies additional message-specific information.
lParam
[in] Specifies additional message-specific information.
fuFlags
[in] Specifies how to send the message. This parameter can be one or more 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 2000 or later: Does not return when the time-out period elapses if the receiving thread is not hung.

uTimeout
[in] 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
[in] Receives the result of the message processing. This value 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.

Remarks

This function considers a thread to be hung if it has not called GetMessage or a similar function within 5 seconds.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, GetMessage, InSendMessage, PostMessage, SendDlgItemMessage, SendMessage, SendMessageCallback, SendNotifyMessage


SendNotifyMessage

The SendNotifyMessage function sends the specified message to a window or windows. 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 to window
  UINT Msg,       // message
  WPARAM wParam,  // first message parameter
  LPARAM lParam   // second message parameter
);

Parameters

hWnd
[in] 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
[in] Specifies the message to be sent.
wParam
[in] Specifies additional message-specific information.
lParam
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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 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 value
);

Parameters

lParam
[in] Specifies the value to associate with the current thread.

Return Values

The return value is the previous value associated with the current thread.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Messages and Message Queues Overview, Message and Message Queue Functions, GetMessageExtraInfo


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   // message information
);

Parameters

lpMsg
[in] 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.

For an example, see Creating a Message Loop.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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.

BSMINFO
MSG


BSMINFO

[This is preliminary documentation and subject to change.]

The BSMINFO structure contains information about a window that denied a request from BroadcastSystemMessageEx.

typedef struct {
  UINT cbSize;
  HDESK hdesk;
  HWND   hwnd;
  LUID   luid;
} BSMINFO, *PBSMINFO

Members

cbSize
[in] Size, in bytes, of this structure.
hdesk
[out] Desktop handle to the window specified by hwnd. This is returned only if BroadcastSystemMessageEx specifies BSF_RETURNHDESK and BSF_QUERY.
hwnd
[out] Handle to the window that denied the request. This is returned if BroadcastSystemMessageEx specifies BSF_QUERY.
luid
[in] Locally unique identifier (LUID) for the window.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Messages and Message Queues Overview, Message and Message Queue Structures, BroadcastSystemMessageEx


MSG

The MSG structure contains message information from a thread's message queue.

typedef struct tagMSG {
  HWND   hwnd;
  UINT   message;
  WPARAM wParam;
  LPARAM lParam;
  DWORD  time;
  POINT  pt;
} MSG, *PMSG;

Members

hwnd
Handle to the window whose window procedure receives the message.
message
Specifies the message identifier. Applications can only use the low word; the high word is reserved by the system.
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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Messages and Message Queues Overview, Message and Message Queue Structures, GetMessage, PeekMessage


Messages and Message Queues Messages

Platform SDK: Windows User Interface

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. The following are the ranges of message numbers available.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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 for use by private window classes, usually of the form WM_USER+X, where X is an integer value.

#define WM_USER       0x0400

Remarks

The following are the 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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
  • Using the Multiple Document Interface
  • Multiple Document Interface Reference


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. For more information, see the following topics.

  • Frame, Client, and Child Windows
  • Child Window Creation
  • Child Window Activation
  • Multiple Document Menus
  • Multiple Document Accelerators
  • Child Window Size and Arrangement
  • Icon Title Windows
  • Child Window Data


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, 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 the 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 clicking Next 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.


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

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

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. Note that GetMessage can return -1 if there is an error.

MSG msg;
BOOL bRet;

while ((bRet = GetMessage(&msg, (HWND) NULL, 0, 0)) != 0)
{
    if (bRet == -1)
    {
        // handle the error and possibly exit
    }
    else
    {
        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


Multiple Document Interface Functions

The following functions are used with MDI.

Function | Description
CreateMDIWindow | Creates an MDI child window.
DefFrameProc | Provides default processing for any window messages that the window procedure of an MDI frame window does not process.
DefMDIChildProc | Provides default processing for any window message that the window procedure of an MDI child window does not process.
TranslateMDISysAccel | Processes accelerator keystrokes for window menu commands of the MDI child windows associated with the specified MDI client window.


CreateMDIWindow

The CreateMDIWindow function creates a multiple document interface (MDI) child window.

HWND CreateMDIWindow(
  LPCTSTR lpClassName,  // registered child class name
  LPCTSTR lpWindowName, // 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 window
  HINSTANCE hInstance,  // handle to application instance
  LPARAM lParam         // application-defined value
);

Parameters

lpClassName
[in] 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
[in] 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
[in] 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
[in] 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
[in] 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
[in] 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
[in] 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
[in] Handle to the MDI client window that will be the parent of the new MDI child window.
hInstance
[in] Handle to the instance of the application creating the MDI child window.
lParam
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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
[in] Handle to the MDI frame window.
hWndMDIClient
[in] Handle to the MDI client window.
uMsg
[in] Specifies the message to be processed.
wParam
[in] Specifies additional message-specific information.
lParam
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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
[in] Handle to the MDI child window.
uMsg
[in] Specifies the message to be processed.
wParam
[in] Specifies additional message-specific information.
lParam
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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       // message data
);

Parameters

hWndClient
[in] Handle to the MDI client window.
lpMsg
[in] 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.

For an example, see Writing the Main Message Loop.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 structure is 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 {
    LPCTSTR szClass;
    LPCTSTR szTitle;
    HANDLE  hOwner;
    int     x;
    int     y;
    int     cx;
    int     cy;
    DWORD   style;
    LPARAM  lParam;
} MDICREATESTRUCT, *LPMDICREATESTRUCT;

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Multiple Document Interface Overview, Multiple Document Interface Structures, CLIENTCREATESTRUCT, CREATESTRUCT, WM_CREATE


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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_MDIACTIVE,             // message to send
  (WPARAM) wParam,          // handle to child window (HWND)
  (LPARAM) lParam           // not used; must be zero
);

Parameters

wParam
Handle to the MDI child window to be activated.
lParam
This parameter is not used.

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

As the client window processes this message, it sends WM_MDIACTIVATE to the child window being deactivated and to the child window being activated. The message parameters received by an MDI child window are as follows:

wParam
Handle to the MDI child window being deactivated.
lParam
Handle to the MDI child window being activated.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_MDICASCADE,            // message to send
  (WPARAM) wParam,          // cascade option
  (LPARAM) lParam           // not used; must be zero
);

Parameters

wParam
Specifies the cascade behavior. This parameter can be one or more of the following values.
Value | Meaning
MDITILE_SKIPDISABLED | Prevents disabled MDI child windows from being cascaded.
MDITILE_ZORDER | Windows 2000 or later: Arranges the windows in Z order.

lParam
This parameter is not used.

Return Values

If the message succeeds, the return value is TRUE.

If the message fails, the return value is FALSE.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,          // handle to destination window
  WM_MDICREATE,         // message to send
  (WPARAM) wParam,      // not used; must be zero
  (LPARAM) lParam       // creation data (LPMDICREATESTRUCT)
);

Parameters

wParam
This parameter is not used.
lParam
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. 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_MDIDESTROY,            // message to send
  (WPARAM) wParam,          // handle to child window (HWND)
  (LPARAM) lParam           // not used; must be zero
);

Parameters

wParam
Handle to the MDI child window to be closed.
lParam
This parameter is not used.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_MDIGETACTIVE,          // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam           // maximized state (LPBOOL)
);

Parameters

wParam
This parameter is not used.
lParam
Specifies the maximized state. If this parameter is not NULL, it is a pointer to a value that indicates the maximized state of the MDI child window. If the value is TRUE, the window is maximized; a value of FALSE indicates that it is not. If this parameter is NULL, the parameter is ignored.

Return Values

The return value is the handle to the active MDI child window.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_MDIICONARRANGE,        // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam           // not used; must be zero
);

Parameters

This message has no parameters.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_MDIMAXIMIZE,           // message to send
  (WPARAM) wParam,          // handle to child window (HWND)
  (LPARAM) lParam           // not used; must be zero
);

Parameters

wParam
Handle to the MDI child window to be maximized.
lParam
This parameter is not used.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_MDINEXT,               // message to send
  (WPARAM) wParam,          // handle to child window (HWND)
  (LPARAM) lParam           // next or previous indicator
);

Parameters

wParam
Handle to the MDI child window. The system activates the child window that is immediately before or after the specified 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.
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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_MDIREFRESHMENU,        // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam           // 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_MDIRESTORE,            // message to send
  (WPARAM) wParam,          // handle to child window (HWND)
  (LPARAM) lParam           // not used; must be zero
);

Parameters

wParam
Handle to the MDI child window to be restored.
lParam
This parameter is not used.

Return Values

The return value is always zero.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_MDISETMENU,            // message to send
  (WPARAM) wParam,          // handle to menu (HMENU)
  (LPARAM) lParam           // handle to window menu (HMENU)
);

Parameters

wParam
Handle to the new frame window menu. If this parameter is NULL, the frame window menu is not changed.
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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_MDITILE,               // message to send
  (WPARAM) wParam,          // tiling option
  (LPARAM) lParam           // not used; must be zero
);

Parameters

wParam
Specifies the tiling option. 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.

lParam
This parameter is not used.

Return Values

If the message succeeds, the return value is TRUE.

If the message fails, the return value is FALSE.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Multiple Document Interface Overview, Multiple Document Interface Messages, WM_MDICASCADE, WM_MDIICONARRANGE


Timers

A timer is an internal routine that repeatedly measures a specified interval, in milliseconds.

  • About Timers
  • Using Timers
  • Timer Reference


About Timers

Each time the specified interval (or time-out value) for a timer elapses, the system notifies the window associated with the timer. Because the accuracy of a timer depends on the system clock rate and how often the application retrieves messages from the message queue, the time-out value is only approximate.

If you need a timer with higher precision, use the high-resolution timer. For more information, see High-Resolution Timer. If you need to be notified when a timer elapses, use the waitable timers. For more information on these, see Waitable Timer Objects.

  • Timer Operations


Timer Operations

A Win32®-based application creates a timer by using the SetTimer function. A new timer starts timing the interval as soon as it is created. An application can change a timer's time-out value by using SetTimer and can destroy a timer by using the KillTimer function. To use system resources efficiently, applications should destroy timers that are no longer necessary.

Each timer has a unique identifier. When creating a timer, an application can either specify an identifier or have the system create a unique value. The first parameter of a WM_TIMER message contains the identifier of the timer that posted the message.

If you specify a window handle in the call to SetTimer, the application associates the timer with that window. Whenever the time-out value for the timer elapses, the system posts a WM_TIMER message to the window associated with the timer. If no window handle is specified in the call to SetTimer, the application that created the timer must monitor its message queue for WM_TIMER messages and dispatch them to the appropriate window. If you specify a TimerProc callback function, the default window procedure calls the callback function when it processes WM_TIMER. Therefore, you need to dispatch messages in the calling thread, even when you use TimerProc instead of processing WM_TIMER.


High-Resolution Timer

A counter is a general term used in programming to refer to an incrementing variable. Some systems include a high-resolution performance counter that provides high-resolution elapsed times.

If a high-resolution performance counter exists on the system, the QueryPerformanceFrequency function can be used to express the frequency, in counts per second. The value of the count is processor dependent. On some processors, for example, the count might be the cycle rate of the processor clock.

The QueryPerformanceCounter function retrieves the current value of the high-resolution performance counter. By calling this function at the beginning and end of a section of code, an application essentially uses the counter as a high-resolution timer. For example, suppose that QueryPerformanceFrequency indicates that the frequency of the high-resolution performance counter is 50,000 counts per second. If the application calls QueryPerformanceCounter immediately before and immediately after the section of code to be timed, the counter values might be 1500 counts and 3500 counts, respectively. These values would indicate that .04 seconds (2000 counts) elapsed while the code executed.


Using Timers

  • Creating a timer
  • Destroying a timer
  • Using timer functions to create a mousetrap


Creating a Timer

The following example uses the SetTimer function to create two timers. The first timer is set for every 10 seconds, the second for every 5 minutes.

// Set two timers.

SetTimer(hwnd,             // handle to main window
    IDT_TIMER1,            // timer identifier
    10000,                 // 10-second interval
    (TIMERPROC) NULL);     // no timer callback

SetTimer(hwnd,             // handle to main window
    IDT_TIMER2,            // timer identifier
    300000,                // 5-minute interval
    (TIMERPROC) NULL);     // no timer callback

To process the WM_TIMER messages generated by these timers, add a WM_TIMER case statement to the window procedure for the hwnd parameter.

case WM_TIMER:

    switch (wParam)
    {
        case IDT_TIMER1:
            // Process the 10-second timer.

             return 0;

        case IDT_TIMER2:
            // Process the 5-minute timer.

            return 0;
    }

An application can also create a timer whose WM_TIMER messages are processed not by the main window procedure but by an application-defined callback function, as in the following code sample, which creates a timer and uses the callback function MyTimerProc to process the timer's WM_TIMER messages.

// Set the timer.

SetTimer(hwnd,                // handle to main window
    IDT_TIMER3,               // timer identifier
    5000,                     // 5-second interval
    (TIMERPROC) MyTimerProc); // timer callback

The calling convention for MyTimerProc must be based on the TimerProc callback function.

If your application creates a timer without specifying a window handle, your application must monitor the message queue for WM_TIMER messages and dispatch them to the appropriate window. Note that GetMessage can return -1 if there is an error.

HWND hwndTimer;   // handle to window for timer messages
MSG msg;          // message structure

    while (GetMessage(&msg, // message structure
            NULL,           // handle to window to receive the message
            NULL,           // lowest message to examine
            NULL)          // highest message to examine
           != 0 && GetMessage(&msg, NULL, NULL, NULL) != -1)
    {

        // Post WM_TIMER messages to the hwndTimer procedure.

        if (msg.message == WM_TIMER)
        {
            msg.hwnd = hwndTimer;
        }

        TranslateMessage(&msg); // translates virtual-key codes
        DispatchMessage(&msg);  // dispatches message to window
    }


Destroying a Timer

Applications should use the KillTimer function to destroy timers that are no longer necessary. The following example destroys the timers identified by the constants IDT_TIMER1, IDT_TIMER2, and IDT_TIMER3.

// Destroy the timers.

KillTimer(hwnd, IDT_TIMER1);
KillTimer(hwnd, IDT_TIMER2);
KillTimer(hwnd, IDT_TIMER3);


Using Timer Functions to Create a Mousetrap

Sometimes it is necessary to prevent more input while you have a cursor on the screen. One way to accomplish this is to create a special routine that traps mouse input until a specific event occurs. Many developers refer to this routine as "building a mousetrap."

The following example uses the SetTimer and KillTimer functions to create a simple mousetrap. SetTimer creates a timer that sends a WM_TIMER message every 10 seconds. Each time the application receives a WM_TIMER message, it records the cursor location. If the current location is the same as the previous location and the application's main window is minimized, the application moves the cursor to the icon. When the application closes, KillTimer stops the timer.

HICON hIcon1;               // icon handle
POINT ptOld;                // previous cursor location
UINT uResult;               // SetTimer's return value
HINSTANCE hinstance;        // handle to current instance

//
// Perform application initialization here.
//

wc.hIcon = LoadIcon(hinstance, MAKEINTRESOURCE(400));
wc.hCursor = LoadCursor(hinstance, MAKEINTRESOURCE(200));

// Record the initial cursor position.

GetCursorPos(&ptOld);

// Set the timer for the mousetrap.

uResult = SetTimer(hwnd,             // handle to main window
    IDT_MOUSETRAP,                   // timer identifier
    10000,                           // 10-second interval
    (TIMERPROC) NULL);               // no timer callback

if (uResult == 0)
{
    ErrorHandler("No timer is available.");
}

LONG APIENTRY MainWndProc(
    HWND hwnd,          // handle to main window
    UINT message,       // type of message
    WPARAM  wParam,     // additional information
    LPARAM  lParam)     // additional information
{

    HDC hdc;        // handle to device context
    POINT pt;       // current cursor location
    RECT rc;        // location of minimized window

    switch (message)
    {
        //
        // Process other messages.
        //

        case WM_TIMER:
        // If the window is minimized, compare the current
        // cursor position with the one from 10 seconds
        // earlier. 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, rc.top);
                }
                else
                {
                    ptOld.x = pt.x;
                    ptOld.y = pt.y;
                }
            }

            return 0;

        case WM_DESTROY:

        // Destroy the timer.

            KillTimer(hwnd, IDT_MOUSETRAP);
            PostQuitMessage(0);
            break;

        //
        // Process other messages.
        //

}

Although the following example also creates a mousetrap, it processes the WM_TIMER message through the application-defined callback function MyTimerProc, rather than through the application's message queue.

UINT uResult;               // SetTimer's return value
HICON hIcon1;               // icon handle
POINT ptOld;                // previous cursor location
HINSTANCE hinstance;        // handle to current instance

//
// Perform application initialization here.
//

wc.hIcon = LoadIcon(hinstance, MAKEINTRESOURCE(400));
wc.hCursor = LoadCursor(hinstance, MAKEINTRESOURCE(200));

// Record the current cursor position.

GetCursorPos(&ptOld);

// Set the timer for the mousetrap.

uResult = SetTimer(hwnd,      // handle to main window
    IDT_MOUSETRAP,            // timer identifier
    10000,                    // 10-second interval
    (TIMERPROC) MyTimerProc); // timer callback

if (uResult == 0)
{
    ErrorHandler("No timer is available.");
}

LONG APIENTRY MainWndProc(
    HWND hwnd,          // handle to main window
    UINT message,       // type of message
    WPARAM  wParam,     // additional information
    LPARAM   lParam)    // additional information
{

    HDC hdc;            // handle to device context

    switch (message)
    {
    //
    // Process other messages.
    //

        case WM_DESTROY:
        // Destroy the timer.

            KillTimer(hwnd, IDT_MOUSETRAP);
            PostQuitMessage(0);
            break;

        //
        // Process other messages.
        //

}

// MyTimerProc is an application-defined callback function that
// processes WM_TIMER messages.

VOID CALLBACK MyTimerProc(
    HWND hwnd,        // handle to window for timer messages
    UINT message,     // WM_TIMER message
    UINT idTimer,     // timer identifier
    DWORD dwTime)     // current system time
{

    RECT rc;
    POINT pt;

    // If the window is minimized, compare the current
    // cursor position with the one from 10 seconds earlier.
    // 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, rc.top);
        }
        else
        {
            ptOld.x = pt.x;
            ptOld.y = pt.y;
        }
    }
}


Timer Reference

The following elements are used with timers.

  • Timer Functions
  • Timer Messages


Timer Functions

The following functions are used with timers.

Function | Description
KillTimer | Destroys the specified timer.
QueryPerformanceCounter | Retrieves the current value of the high-resolution performance counter.
QueryPerformanceFrequency | Retrieves the frequency of the high-resolution performance counter.
SetTimer | Creates a timer with the specified time-out value.
TimerProc | An application-defined callback function that processes WM_TIMER messages.


KillTimer

The KillTimer function destroys the specified timer.

BOOL KillTimer(
  HWND hWnd,          // handle to window
  UINT_PTR uIDEvent   // timer identifier
);

Parameters

hWnd
[in] Handle to the window associated with the specified timer. This value must be the same as the hWnd value passed to the SetTimer function that created the timer.
uIDEvent
[in] Specifies the timer to be destroyed. If the window handle passed to SetTimer is valid, this parameter must be the same as the uIDEvent value passed to SetTimer. If the application calls SetTimer with hWnd set to NULL, this parameter must be the timer identifier returned by SetTimer.

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 KillTimer function does not remove WM_TIMER messages already posted to the message queue.

For an example, see Destroying a Timer.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Timers Overview, Timer Functions, SetTimer, WM_TIMER


QueryPerformanceCounter

The QueryPerformanceCounter function retrieves the current value of the high-resolution performance counter.

BOOL QueryPerformanceCounter(
  LARGE_INTEGER *lpPerformanceCount   // counter value
);

Parameters

lpPerformanceCount
[out] Pointer to a variable that receives the current performance-counter value, in counts.

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

On a multiprocessor machine, it should not matter which processor is called. However, you can get different results on different processors due to bugs in the BIOS or the HAL. To specify processor affinity for a thread, use the SetThreadAffinityMask function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Timers Overview, Timer Functions, QueryPerformanceFrequency


QueryPerformanceFrequency

The QueryPerformanceFrequency function retrieves the frequency of the high-resolution performance counter, if one exists. The frequency cannot change while the system is running.

BOOL QueryPerformanceFrequency(
  LARGE_INTEGER *lpFrequency   // current frequency
);

Parameters

lpFrequency
[out] Pointer to a variable that receives the current performance-counter frequency, in counts per second. If the installed hardware does not support a high-resolution performance counter, this parameter can be zero.

Return Values

If the installed hardware supports a high-resolution performance counter, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError. For example, if the installed hardware does not support a high-resolution performance counter, the function fails.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Timers Overview, Timer Functions, QueryPerformanceCounter


SetTimer

The SetTimer function creates a timer with the specified time-out value.

UINT_PTR SetTimer(
  HWND hWnd,              // handle to window
  UINT_PTR nIDEvent,      // timer identifier
  UINT uElapse,           // time-out value
  TIMERPROC lpTimerFunc   // timer procedure
);

Parameters

hWnd
[in] Handle to the window to be associated with the timer. This window must be owned by the calling thread. If this parameter is NULL, no window is associated with the timer and the nIDEvent parameter is ignored.
nIDEvent
[in] Specifies a nonzero timer identifier. If the hWnd parameter is NULL, this parameter is ignored.

If the hWnd parameter is not NULL and the window specified by hWnd already has a timer with the value nIDEvent, then the existing timer is replaced by the new timer. When SetTimer replaces a timer, the timer is reset. Therefore, a message will be sent after the current time-out value elapses, but the previously set time-out value is ignored.

uElapse
[in] Specifies the time-out value, in milliseconds.
lpTimerFunc
[in] Pointer to the function to be notified when the time-out value elapses. For more information about the function, see TimerProc.

If lpTimerFunc is NULL, the system posts a WM_TIMER message to the application queue. The hwnd member of the message's MSG structure contains the value of the hWnd parameter.

Return Values

If the function succeeds and the hWnd parameter is NULL, the return value is an integer identifying the new timer. An application can pass this value to the KillTimer function to destroy the timer.

If the function succeeds and the hWnd parameter is not NULL, then the return value is a nonzero integer. An application can pass the value of the nIDTimer parameter to the KillTimer function to destroy the timer.

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

Remarks

An application can process WM_TIMER messages by including a WM_TIMER case statement in the window procedure or by specifying a TimerProc callback function when creating the timer. When you specify a TimerProc callback function, the default window procedure calls the callback function when it processes WM_TIMER. Therefore, you need to dispatch messages in the calling thread, even when you use TimerProc instead of processing WM_TIMER.

The wParam parameter of the WM_TIMER message contains the value of the nIDEvent parameter.

The timer identifier, nIDEvent, is specific to the associated window. Another window can have its own timer which has the same identifier as a timer owned by another window. The timers are distinct.

For an example, see Creating a Timer.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Timers Overview, Timer Functions, KillTimer, MSG, TimerProc, WM_TIMER


TimerProc

The TimerProc function is an application-defined callback function that processes WM_TIMER messages. The TIMERPROC type defines a pointer to this callback function. TimerProc is a placeholder for the application-defined function name.

VOID CALLBACK TimerProc(
  HWND hwnd,         // handle to window
  UINT uMsg,         // WM_TIMER message
  UINT_PTR idEvent,  // timer identifier
  DWORD dwTime       // current system time
);

Parameters

hwnd
[in] Handle to the window associated with the timer.
uMsg
[in] Specifies the WM_TIMER message.
idEvent
[in] Specifies the timer's identifier.
dwTime
[in] Specifies the number of milliseconds that have elapsed since the system was started. This is the value returned by the GetTickCount function.

Return Values

This function does not return a value.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Timers Overview, Timer Functions, GetTickCount, KillTimer, SetTimer, WM_TIMER


Timer Messages

The following message is used with timers.

WM_TIMER


WM_TIMER

The WM_TIMER message is posted to the installing thread's message queue when a timer expires. The message is posted by the GetMessage or PeekMessage function.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_TIMER
  WPARAM wParam,   // timer identifier
  LPARAM lParam    // timer callback (TIMERPROC)
);

Parameters

wParam
Specifies the timer identifier.
lParam
Pointer to an application-defined callback function that was passed to the SetTimer function when the timer was installed.

Return Values

An application should return zero if it processes this message.

Remarks

You can process the message by providing a WM_TIMER case in the window procedure. Otherwise, the default window procedure will call the TimerProc callback function specified in the call to the SetTimer function used to install the timer.

The WM_TIMER message is a low-priority message. The GetMessage and PeekMessage functions post this message only when no other higher-priority messages are in the thread's message queue.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Timers Overview, Timer Messages, GetMessage, PeekMessage, SetTimer, TimerProc


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
  • Using Window Classes
  • Window Class Reference


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 Classes

A system class is a window class registered by the system. Many system classes are available for all processes to use, while others are used only internally by the system. Because the system registers these classes, a process cannot destroy them.

Windows 95/98/Me: The system registers the system classes when it starts.

Windows NT/2000 or later: The system registers the system classes for a process the first time one of its threads calls a User or a GDI function.

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 that are available for use by all processes.

Class | Description
Button | The class for a button.
ComboBox | The class for a combo box.
Edit | The class for an edit control.
ListBox | The class for a list box.
MDIClient | The class for an MDI client window.
ScrollBar | The class for a scroll bar.
Static | The class for a static control.

The following table describes the system classes that are available only for use by the system. They are listed here for completeness sake.

Class | Description
ComboLBox | The class for the list box contained in a combo box.
DDEMLEvent | Windows NT/2000 or later: The class for DDEML events.
Message | Windows 2000 or later: The class for a message-only window.
#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/2000 or later: The class for icon titles.


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/2000 or later: 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 handle to the .dll instance.

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/2000 or later: 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 shown in the following table..

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/98/Me: 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 a handle to 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.
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.
CS_DROPSHADOW | Whistler: Enables the drop shadow effect on a window. The effect is turned on and off through SPI_SETDROPSHADOW. Typically, this is enabled for small, short-lived windows such as menus to emphasize their Z order relationship to other windows.
CS_GLOBALCLASS | Specifies that the window class is an application global class. For more information, see Application Global Classes.
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 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.
CS_SAVEBITS | Saves, as a bitmap, the portion of the screen image obscured by a window of this class. When the window is removed, the system uses the saved bitmap to restore the screen image, including other windows that were obscured. Therefore, the system does not send WM_PAINT messages to windows that were obscured 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.

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/98/Me: 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 SetWindowLong function copies a value to the extra memory. The GetWindowLong function retrieves 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) != 0 && GetMessage(&msg, (HWND) NULL, 0, 0) != -1)
    {
        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 to 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),
        IMAGE_ICON,
        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 to 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.

Function | Description
GetClassInfo | Retrieves information about a window class.
GetClassInfoEx | Retrieves information about a window class, including a handle to its small icon.
GetClassLong | Retrieves the specified 32-bit value from the WNDCLASSEX structure associated with the specified window.
GetClassLongPtr | Retrieves the specified value from the WNDCLASSEX structure associated with the specified window.
GetClassName | Retrieves the name of the class to which the specified window belongs.
GetWindowLong | Retrieves information about the specified window.
GetWindowLongPtr | Retrieves information about the specified window.
RegisterClass | Registers a window class.
RegisterClassEx | Registers a window class.
SetClassLong | Replaces the specified 32-bit value at the specified offset into the extra class memory or the WNDCLASSEX structure.
SetClassLongPtr | Replaces the specified value at the specified offset into the extra class memory or the WNDCLASSEX structure.
SetWindowLong | Changes an attribute of the specified window.
SetWindowLongPtr | Changes an attribute of the specified window.
UnregisterClass | Unregisters a window class.

Obsolete Functions

These functions are provided only for compatibility with 16-bit versions of Windows.

GetClassWord
SetClassWord


GetClassInfo

The GetClassInfo function retrieves information about a window class.

Note 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 to application instance
  LPCTSTR lpClassName,    // class name
  LPWNDCLASS lpWndClass   // class data
);

Parameters

hInstance
[in] 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
[in] 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 or RegisterClassEx function.

Alternatively, this parameter can be an atom. If so, it must be a class atom created by a previous call to RegisterClass or RegisterClassEx. The atom must be in the low-order word of lpClassName; the high-order word must be zero.

lpWndClass
[out] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Window Classes Overview, Window Class Functions, GetClassInfoEx, GetClassLong, GetClassName, RegisterClass, RegisterClassEx, WNDCLASS


GetClassInfoEx

The GetClassInfoEx function retrieves information about a window class, including a handle to the small icon associated with the window class. The GetClassInfo function does not retrieve a handle to the small icon.

BOOL GetClassInfoEx(
  HINSTANCE hinst,    // handle to application instance
  LPCTSTR lpszClass,  // class name
  LPWNDCLASSEX lpwcx  // class data
);

Parameters

hinst
[in] 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
[in] 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 or RegisterClassEx function.

Alternatively, this parameter can be a class atom created by a previous call to RegisterClass or RegisterClassEx. The atom must be in the low-order word of lpszClass; the high-order word must be zero.

lpwcx
[out] 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.

Remarks

Class atoms are created using the RegisterClass or RegisterClassEx function, not the GlobalAddAtom function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Window Classes Overview, Window Class Functions, GetClassLong, GetClassName, RegisterClass, RegisterClassEx


GetClassLong

The GetClassLong function retrieves the specified 32-bit (long) value from the WNDCLASSEX structure associated with the specified window.

If you are retrieving a pointer or a handle, this function has been superseded by the GetClassLongPtr function. (Pointers and handles are 32 bits on 32-bit Windows and 64 bits on 64-bit Windows.) To write code that is compatible with both 32-bit and 64-bit versions of Windows, use GetClassLongPtr.

DWORD GetClassLong(
  HWND hWnd,  // handle to window
  int nIndex  // offset of value to retrieve
);

Parameters

hWnd
[in] Handle to the window and, indirectly, the class to which the window belongs.
nIndex
[in] 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 a handle to the background brush associated with the class.
GCL_HCURSOR | Retrieves a handle to the cursor associated with the class.
GCL_HICON | Retrieves a handle to the icon associated with the class.
GCL_HICONSM | Retrieves a handle to the small icon associated with the class.
GCL_HMODULE | Retrieves a handle to 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, or a handle representing the address of the window procedure. You must use the CallWindowProc function to call the window procedure.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Window Classes Overview, Window Class Functions, GetClassLongPtr, GetWindowLong, RegisterClassEx, SetClassLong, WNDCLASSEX


GetClassLongPtr

The GetClassLongPtr function retrieves the specified value from the WNDCLASSEX structure associated with the specified window.

If you are retrieving a pointer or a handle, this function supersedes the GetClassLong function. (Pointers and handles are 32 bits on 32-bit Windows and 64 bits on 64-bit Windows.) To write code that is compatible with both 32-bit and 64-bit versions of Windows, use GetClassLongPtr.

ULONG_PTR GetClassLongPtr(
  HWND hWnd,  // handle to window
  int nIndex  // offset of value to retrieve
);
hWnd
[in] Handle to the window and, indirectly, the class to which the window belongs.
nIndex
[in] Specifies the value to retrieve. To retrieve a 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 eight; for example, if you specified 24 or more bytes of extra class memory, a value of 16 would be an index to the third 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 GetWindowLongPtr.
GCLP_HBRBACKGROUND | Retrieves a handle to the background brush associated with the class.
GCLP_HCURSOR | Retrieves a handle to the cursor associated with the class.
GCLP_HICON | Retrieves a handle to the icon associated with the class.
GCLP_HICONSM | Retrieves a handle to the small icon associated with the class.
GCLP_HMODULE | Retrieves a handle to the module that registered the class.
GCLP_MENUNAME | Retrieves the pointer to the menu name string. The string identifies the menu resource associated with the class.
GCL_STYLE | Retrieves the window-class style bits.
GCLP_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.

Return Values

If the function succeeds, the return value is the requested 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Window Classes Overview, Window Class Functions, GetWindowLongPtr, RegisterClassEx, SetClassLongPtr, WNDCLASSEX


GetClassName

The GetClassName function retrieves the name of the class to which the specified window belongs.

int GetClassName(
  HWND hWnd,           // handle to window
  LPTSTR lpClassName,  // class name
  int nMaxCount        // size of class name buffer
);

Parameters

hWnd
[in] Handle to the window and, indirectly, the class to which the window belongs.
lpClassName
[out] Pointer to the buffer that is to receive the class name string.
nMaxCount
[in] Specifies the length, in TCHARs, 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 TCHARs copied to the specified buffer.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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.

Note This function is provided only for compatibility with 16-bit versions of Windows. The only offsets supported on 32-bit Windows are GCW_ATOM and GCW_HICONSM. Win32-based applications should use the GetClassLong function.

WORD GetClassWord(
  HWND hWnd,  // handle to window
  int nIndex  // offset of value to retrieve
);

Parameters

hWnd
[in] Handle to the window and, indirectly, the class to which the window belongs.
nIndex
[in] 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 as shown in the following table.
Value | Action
GCW_ATOM | Retrieves an ATOM value that uniquely identifies the window class. This is the same atom that the RegisterClass or RegisterClassEx function returns.
GCW_HICONSM | Retrieves a handle to 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Window Classes Overview, Window Class Functions, GetClassLong, RegisterClass, RegisterClassEx, 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.

If you are retrieving a pointer or a handle, this function has been superseded by the GetWindowLongPtr function. (Pointers and handles are 32 bits on 32-bit Windows and 64 bits on 64-bit Windows.) To write code that is compatible with both 32-bit and 64-bit versions of Windows, use GetWindowLongPtr.

LONG GetWindowLong(
  HWND hWnd,  // handle to window
  int nIndex  // offset of value to retrieve
);

Parameters

hWnd
[in] Handle to the window and, indirectly, the class to which the window belongs.
nIndex
[in] 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. For more information, see CreateWindowEx.
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 a handle to the application instance.
GWL_HWNDPARENT | Retrieves a handle to the parent window, if any.
GWL_ID | Retrieves the identifier of the window.
GWL_USERDATA | Retrieves the user data associated with the window. This data is intended for use by the application that created the window. Its value is initially zero.

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.

If SetWindowLong has not been called previously, GetWindowLong returns zero for values in the extra window or class memory.

Remarks

Reserve extra window memory by specifying a nonzero value in the cbWndExtra member of the WNDCLASSEX structure used with the RegisterClassEx function.

For an example, see Creating, Enumerating, and Sizing Child Windows.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Window Classes Overview, Window Class Functions, CallWindowProc, GetWindowLongPtr, RegisterClassEx, SetParent, SetWindowLong, WNDCLASS


GetWindowLongPtr

The GetWindowLongPtr function retrieves information about the specified window. The function also retrieves the value at a specified offset into the extra window memory.

If you are retrieving a pointer or a handle, this function supersedes the GetWindowLong function. (Pointers and handles are 32 bits on 32-bit Windows and 64 bits on 64-bit Windows.) To write code that is compatible with both 32-bit and 64-bit versions of Windows, use GetWindowLongPtr.

LONG_PTR GetWindowLongPtr(
  HWND hWnd,  // handle to window
  int nIndex  // offset of value to retrieve
);

Parameters

hWnd
[in] Handle to the window and, indirectly, the class to which the window belongs.
nIndex
[in] 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 the size of an integer. To retrieve any other value, specify one of the following values.
Value | Action
GWL_EXSTYLE | Retrieves the extended window styles. For more information, see CreateWindowEx.
GWL_STYLE | Retrieves the window styles.
GWLP_WNDPROC | Retrieves the pointer to the window procedure, or a handle representing the pointer to the window procedure. You must use the CallWindowProc function to call the window procedure.
GWLP_HINSTANCE | Retrieves a handle to the application instance.
GWLP_HWNDPARENT | Retrieves a handle to the parent window, if there is one.
GWLP_ID | Retrieves the identifier of the window.
GWLP_USERDATA | Retrieves the user data associated with the window. This data is intended for use by the application that created the window. Its value is initially zero.

The following values are also available when the hWnd parameter identifies a dialog box.
Value | Action
DWLP_DLGPROC | Retrieves the pointer to the dialog box procedure, or a handle representing the pointer to the dialog box procedure. You must use the CallWindowProc function to call the dialog box procedure.
DWLP_MSGRESULT | Retrieves the return value of a message processed in the dialog box procedure.
DWLP_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 value.

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

If SetWindowLong or SetWindowLongPtr has not been called previously, GetWindowLongPtr returns zero for values in the extra window or class memory.

Remarks

Reserve extra window memory by specifying a nonzero value in the cbWndExtra member of the WNDCLASSEX structure used with the RegisterClassEx function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Window Classes Overview, Window Class Functions, CallWindowProc, RegisterClassEx, SetParent, SetWindowLongPtr, WNDCLASSEX


RegisterClass

The RegisterClass function registers a window class for subsequent use in calls to the CreateWindow or CreateWindowEx function.

Note 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  // class data
);

Parameters

lpWndClass
[in] 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 a class atom that uniquely identifies the class being registered. This atom can only be used by the CreateWindow, CreateWindowEx, GetClassInfo, GetClassInfoEx, FindWindow, FindWindowEx, and UnregisterClass functions and the IActiveIMMApp::FilterClientWindows Method.

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/2000 or later: No window classes registered by a .dll are unregistered when the .dll is unloaded. A .dll must explicitly unregister its classes when it is unloaded.

Windows 95: RegisterClass fails if the cbWndExtra or cbClsExtra member of the WNDCLASS structure contains more than 40 bytes.

For an example, see Associating a Window Procedure with a Window Class.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Window Classes Overview, Window Class Functions, CreateWindow, CreateWindowEx, FindWindow, FindWindowEx, GetClassInfo, GetClassInfoEx, GetClassName, RegisterClassEx, UnregisterClass, WindowProc, WNDCLASS, IActiveIMMApp::FilterClientWindows Method


RegisterClassEx

The RegisterClassEx function registers a window class for subsequent use in calls to the CreateWindow or CreateWindowEx function.

ATOM RegisterClassEx(
  CONST WNDCLASSEX *lpwcx  // class data
);

Parameters

lpwcx
[in] 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 a class atom that uniquely identifies the class being registered. This atom can only be used by the CreateWindow, CreateWindowEx, GetClassInfo, GetClassInfoEx, FindWindow, FindWindowEx, and UnregisterClass functions and the IActiveIMMApp::FilterClientWindows Method.

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/2000 or later: No window classes registered by a .dll are unregistered when the .dll is unloaded. A .dll must explicitly unregister its classes when it is unloaded.

Windows 95: RegisterClassEx fails if the cbWndExtra or cbClsExtra member of the WNDCLASSEX structure contains more than 40 bytes.

For an example, see Using Window Classes.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Window Classes Overview, Window Class Functions, CreateWindow, CreateWindowEx, FindWindow, FindWindowEx, GetClassInfo, GetClassInfoEx, GetClassName, RegisterClass, UnregisterClass, WindowProc,WNDCLASSEX, IActiveIMMApp::FilterClientWindows


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.

Note This function has been superseded by the SetClassLongPtr function. To write code that is compatible with both 32-bit and 64-bit versions of Windows, use SetClassLongPtr.

DWORD SetClassLong(
  HWND hWnd,       // handle to window
  int nIndex,      // index of value to change
  LONG dwNewLong   // new value
);

Parameters

hWnd
[in] Handle to the window and, indirectly, the class to which the window belongs.
nIndex
[in] 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 a handle to the background brush associated with the class.
GCL_HCURSOR | Replaces a handle to the cursor associated with the class.
GCL_HICON | Replaces a handle to the icon associated with the class.
GCL_HICONSM | Replace a handle to the small icon associated with the class.
GCL_HMODULE | Replaces a handle to 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
[in] 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.

For an example, see Displaying an Icon.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Window Classes Overview, Window Class Functions, GetClassLong, RegisterClassEx, SetClassLongPtr, SetWindowLong, WindowProc, WNDCLASSEX


SetClassLongPtr

The SetClassLong function replaces the specified value at the specified offset in the extra class memory or the WNDCLASSEX structure for the class to which the specified window belongs.

This function supersedes the SetClassLong function. To write code that is compatible with both 32-bit and 64-bit versions of Windows, use SetClassLongPtr.

ULONG_PTR SetClassLongPtr(
  HWND hWnd,           // handle to window
  int nIndex,          // index of value to change
  LONG_PTR dwNewLong   // new value
);

Parameters

hWnd
[in] Handle to the window and, indirectly, the class to which the window belongs.
nIndex
[in] Specifies the value to replace. To set a 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 eight; for example, if you specified 24 or more bytes of extra class memory, a value of 16 would be an index to the third integer. To set a value other than 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 SetWindowLongPtr.
GCLP_
HBRBACKGROUND 		Replaces a handle to the background brush associated with the class.
GCLP_HCURSOR | Replaces a handle to the cursor associated with the class.
GCLP_HICON | Replaces a handle to the icon associated with the class.
GCLP_HICONSM | Retrieves a handle to the small icon associated with the class.
GCLP_HMODULE | Replaces a handle to the module that registered the class.
GCLP_MENUNAME | Replaces the pointer to the menu name string. The string identifies the menu resource associated with the class.
GCL_STYLE | Replaces the window-class style bits.
GCLP_WNDPROC | Replaces the pointer to the window procedure associated with the class.

dwNewLong
[in] Specifies the replacement value.

Return Values

If the function succeeds, the return value is the previous value of the specified offset. If this 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 SetClassLongPtr function and the GCLP_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 SetClassLongPtr with the GCLP_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 SetClassLongPtr function with care. For example, it is possible to change the background color for a class by using SetClassLongPtr, but this change does not immediately repaint all windows belonging to the class.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Window Classes Overview, Window Class Functions, GetClassLongPtr, RegisterClassEx, SetWindowLongPtr, 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.

Note This function is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should use the SetClassLong function.

WORD SetClassWord(
  HWND hWnd,      // handle to window
  int nIndex,     // index of value to change
  WORD wNewWord   // new value
);

Parameters

hWnd
[in] Handle to the window and, indirectly, the class to which the window belongs.
nIndex
[in] 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
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

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 the 32-bit (long) value at the specified offset into the extra window memory.

Note This function has been superseded by the SetWindowLongPtr function. To write code that is compatible with both 32-bit and 64-bit versions of Windows, use SetWindowLongPtr.

LONG SetWindowLong(
  HWND hWnd,       // handle to window
  int nIndex,      // offset of value to set
  LONG dwNewLong   // new value
);

Parameters

hWnd
[in] Handle to the window and, indirectly, the class to which the window belongs.

Windows 95/98/Me: The SetWindowLong function may fail if the window specified by the hWnd parameter does not belong to the same process as the calling thread.

nIndex
[in] 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 the size of an integer. To set any other value, specify one of the following values.
Value | Action
GWL_EXSTYLE | Sets a new extended window style. For more information, see CreateWindowEx.
GWL_STYLE | Sets a new window style.
GWL_WNDPROC Sets a new address for the window procedure.

Windows NT/2000 or later: You cannot change this attribute if the window does not belong to the same process as the calling thread.
GWL_HINSTANCE | Sets a new application instance handle.
GWL_ID | Sets a new identifier of the window.
GWL_USERDATA | Sets the user data associated with the window. This data is intended for use by the application that created the window. Its value is initially zero.

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
[in] 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

Certain window data is cached, so changes you make using SetWindowLong will not take effect until you call the SetWindowPos function. Specifically, if you change any of the frame styles, you must call SetWindowPos with the SWP_FRAMECHANGED flag for the cache to be updated properly.

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.

If the window has a class style of CS_CLASSDC or CS_OWNDC, do not set the extended window styles WS_EX_COMPOSITED or WS_EX_LAYERED.

For an example, see Subclassing a Window.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Window Classes Overview, Window Class Functions, CallWindowProc, GetWindowLong, RegisterClassEx, SetParent, SetWindowLongPtr, WindowProc, WNDCLASSEX


SetWindowLongPtr

The SetWindowLongPtr function changes an attribute of the specified window. The function also sets a value at the specified offset in the extra window memory.

This function supersedes the SetWindowLong function. To write code that is compatible with both 32-bit and 64-bit versions of Windows, use SetWindowLongPtr.

LONG_PTR SetWindowLongPtr(
  HWND hWnd,           // handle to window
  int nIndex,          // offset of value to set
  LONG_PTR dwNewLong   // new value
);

Parameters

hWnd
[in] Handle to the window and, indirectly, the class to which the window belongs. The SetWindowLongPtr function fails if the window specified by the hWnd parameter does not belong to the same process as the calling thread.
nIndex
[in] 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 the size of an integer. To set any other value, specify one of the following values.
Value | Action
GWL_EXSTYLE | Sets a new extended window style. For more information, see CreateWindowEx.
GWL_STYLE | Sets a new window style.
GWLP_WNDPROC | Sets a new address for the window procedure.
GWLP_HINSTANCE | Sets a new application instance handle.
GWLP_ID | Sets a new identifier of the window.
GWLP_USERDATA | Sets the user data associated with the window. This data is intended for use by the application that created the window. Its value is initially zero.

The following values are also available when the hWnd parameter identifies a dialog box.
Value | Action
DWLP_DLGPROC | Sets the new pointer to the dialog box procedure.
DWLP_MSGRESULT | Sets the return value of a message processed in the dialog box procedure.
DWLP_USER | Sets new extra information that is private to the application, such as handles or pointers.

dwNewLong
[in] Specifies the replacement value.

Return Values

If the function succeeds, the return value is the previous value of the specified offset.

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

If the previous value is zero and the function succeeds, the return value is zero, but the function does not clear the last error information. To determine success or failure, clear the last error information by calling SetLastError(0), then call SetWindowLongPtr. Function failure will be indicated by a return value of zero and a GetLastError result that is nonzero.

Remarks

Certain window data is cached, so changes you make using SetWindowLongPtr will not take effect until you call the SetWindowPos function.

If you use SetWindowLongPtr with the GWLP_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 SetWindowLongPtr with the DWLP_MSGRESULT index to set the return value for a message processed by a dialog box procedure, the dialog box procedure should return TRUE directly afterwards. Otherwise, if you call any function that results in your dialog box procedure receiving a window message, the nested window message could overwrite the return value you set by using DWLP_MSGRESULT.

Calling SetWindowLongPtr with the GWLP_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 SetWindowLongPtr 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.

Do not call SetWindowLongPtr with the GWLP_HWNDPARENT index to change the parent of a child window. Instead, use the SetParent function.

If the window has a class style of CS_CLASSDC or CS_OWNDC, do not set the extended window styles WS_EX_COMPOSITED or WS_EX_LAYERED.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Window Classes Overview, Window Class Functions, CallWindowProc, GetWindowLongPtr, RegisterClassEx, SetParent, WindowProc, WNDCLASSEX


UnregisterClass

The UnregisterClass function unregisters a window class, freeing the memory required for the class.

BOOL UnregisterClass(
  LPCTSTR lpClassName,  // class name
  HINSTANCE hInstance   // handle to application instance
);

Parameters

lpClassName
[in] Pointer to a null-terminated string or a class 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 RegisterClass or RegisterClassEx function. System classes, such as dialog box controls, cannot be unregistered.

If this parameter is an atom, it must be a class atom created by a previous call to the RegisterClass or RegisterClassEx function. The atom must be in the low-order word of lpClassName; the high-order word must be zero.

hInstance
[in] 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.

Class atoms are special atoms returned only by RegisterClass and RegisterClassEx.

Windows 95: All window classes registered by a .dll are unregistered when the .dll is unloaded.

Windows NT/2000 or later: No window classes registered by a .dll registers are unregistered when the .dll is unloaded.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Window Classes Overview, Window Class Functions, RegisterClass, RegisterClassEx


Window Class Structures

The following structures are used with window classes.

WNDCLASS
WNDCLASSEX


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;
    HINSTANCE  hInstance;
    HICON      hIcon;
    HCURSOR    hCursor;
    HBRUSH     hbrBackground;
    LPCTSTR    lpszMenuName;
    LPCTSTR    lpszClassName;
} WNDCLASS, *PWNDCLASS;

Members

style
Specifies the class style(s). This member can be any combination of the class styles.
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 contains the window procedure for the class.
hIcon
Handle to the class icon. This member must be a handle to an icon resource. If this member is NULL, the system provides a default icon.
hCursor
Handle to the class cursor. This member must be a handle to 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 unregistered by using UnregisterClass. An application should not delete these brushes.

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 class atom created by a previous call to the RegisterClass or RegisterClassEx function. The atom 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. The class name can be any name registered with RegisterClass or RegisterClassEx, or any of the predefined control-class names.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Window Classes Overview, Window Class Structures, BeginPaint, CreateWindow, CreateWindowEx, GetDC, MAKEINTRESOURCE, PAINTSTRUCT, RegisterClass, UnregisterClass, 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;
    HINSTANCE  hInstance;
    HICON      hIcon;
    HCURSOR    hCursor;
    HBRUSH     hbrBackground;
    LPCTSTR    lpszMenuName;
    LPCTSTR    lpszClassName;
    HICON      hIconSm;
} WNDCLASSEX, *PWNDCLASSEX;

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). This member can be any combination of the class styles.
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 contains the window procedure for the class.
hIcon
Handle to the class icon. This member must be a handle to an icon resource. If this member is NULL, the system provides a default icon.
hCursor
Handle to the class cursor. This member must be a handle to 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 unregistered by using UnregisterClass. An application should not delete these brushes.

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 class atom created by a previous call to the RegisterClass or RegisterClassEx function. The atom 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. The class name can be any name registered with RegisterClass or RegisterClassEx, or any of the predefined control-class names.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Window Classes Overview, Window Class Structures, GetClassInfoEx, RegisterClassEx, UnregisterClass


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
  • Using Window Procedures
  • Window Procedure Reference


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.

Function | Description
CallWindowProc | Passes message information to the specified window procedure.
DefWindowProc | Calls the default window procedure to provide default processing for any window messages that an application does not process.
WindowProc | An application-defined function that processes messages sent to a window.


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
[in] 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 special internal value meaningful only to CallWindowProc.

hWnd
[in] Handle to the window procedure to receive the message.
Msg
[in] Specifies the message.
wParam
[in] Specifies additional message-specific information. The contents of this parameter depend on the value of the Msg parameter.
lParam
[in] 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/2000: The CallWindowProc function handles Unicode-to-ANSI conversion. You cannot take advantage of this conversion if you call the window procedure directly.

For an example, see Subclassing a Window.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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
[in] Handle to the window procedure that received the message.
Msg
[in] Specifies the message.
wParam
[in] Specifies additional message information. The content of this parameter depends on the value of the Msg parameter.
lParam
[in] 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.

For an example, see Designing a Window Procedure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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
[in] Handle to the window.
uMsg
[in] Specifies the message.
wParam
[in] Specifies additional message information. The contents of this parameter depend on the value of the uMsg parameter.
lParam
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

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
  • Using Window Properties
  • Window Property Reference


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 the specified string. The RemoveProp function destroys the association between a window and a window property but does not destroy the data itself. To destroy the data itself, use the appropriate function to free the handle that is returned by RemoveProp.


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
{
    hData = RemoveProp(hwndSubclass, lpszString);
//
// if appropriate, free the handle hData
//

    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.

Function | Description
EnumProps | Enumerates all entries in the property list of a window.
EnumPropsEx | Enumerates all entries in the property list of a window.
GetProp | Retrieves a data handle from the property list of the specified window.
PropEnumProc | An application-defined callback function used with the EnumProps function.
PropEnumProcEx | An application-defined callback function used with the EnumPropsEx function.
RemoveProp | Removes an entry from the property list of the specified window.
SetProp | Adds a new entry or changes an existing entry in the property list of the specified window.


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.

To pass application-defined data to the callback function, use the EnumPropsEx function.

int EnumProps(
  HWND hWnd,               // handle to window
  PROPENUMPROC lpEnumFunc  // callback function
);

Parameters

hWnd
[in] Handle to the window whose property list is to be enumerated.
lpEnumFunc
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Window Properties Overview, Window Property Functions, EnumPropsEx, PropEnumProc


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,  // callback function
  LPARAM lParam               // application-defined data
);

Parameters

hWnd
[in] Handle to the window whose property list is to be enumerated.
lpEnumFunc
[in] Pointer to the callback function. For more information about the callback function, see the PropEnumProcEx function.
lParam
[in] 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.

For an example, see Listing Window Properties for a Given Window.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Window Properties Overview, Window Property Functions, PropEnumProcEx


GetProp

The GetProp function retrieves a data handle from the property list of the specified window. The 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 to window
  LPCTSTR lpString   // atom or string
);

Parameters

hWnd
[in] Handle to the window whose property list is to be searched.
lpString
[in] 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 string, the return value is the associated data handle. Otherwise, the return value is NULL.

For an example, see Retrieving a Window Property.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Window Properties Overview, Window Property Functions, GlobalAddAtom, 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
  LPCTSTR lpszString,  // string component
  HANDLE hData         // data handle component
);

Parameters

hwnd
[in] Handle to the window whose property list is being enumerated.
lpszString
[in] 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
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Unicode: Declared as Unicode and ANSI prototypes.

See Also

Window Properties Overview, Window Property Functions, EnumProps, 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 to window
  LPTSTR lpszString,  // string component
  HANDLE hData,       // data handle component
  ULONG_PTR dwData    // application-defined data
);

Parameters

hwnd
[in] Handle to the window whose property list is being enumerated.
lpszString
[in] 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
[in] Handle to data. This handle is the data component of a property list entry.
dwData
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Unicode: Declared as Unicode and ANSI prototypes.

See Also

Window Properties Overview, Window Property Functions, EnumPropsEx, 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 string
);

Parameters

hWnd
[in] Handle to the window whose property list is to be changed.
lpString
[in] 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 data. If the data cannot be found in the specified property list, the return value is NULL.

Remarks

The return value is the hData value that was passed to SetProp; it is an application-defined value. Note, this function only destroys the association between the data and the window. If appropriate, the 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.

For an example, see Deleting a Window Property.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Window Properties Overview, Window Property Functions, AddAtom, 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 to window
  LPCTSTR lpString,  // atom or string
  HANDLE hData       // handle to data
);

Parameters

hWnd
[in] Handle to the window whose property list receives the new entry.
lpString
[in] 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
[in] 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 a window is destroyed (that is, before it returns from processing the WM_NCDESTROY 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.

For an example, see Adding a Window Property.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Window Properties Overview, Window Property Functions, GlobalAddAtom, RemoveProp, WM_NCDESTROY


Window Stations and Desktops

This overview describes the new window station and desktop functionality, and is primarily intended for developers of service applications. Developers of typical applications that will be run by the logged-on user do not need to be concerned about window stations and desktops.

  • About Window Stations and Desktops
  • Using Window Stations and Desktops
  • Window Station and Desktop Reference


About Window Stations and Desktops

The window station and desktop functionality enables service applications to call functions in User32.Dll and GDI32.Dll regardless of the logon account in which the service is running. This new functionality enables service applications to make these calls while maintaining the security of applications running in the account of the logged-on interactive user.

For more information on how service applications use the window station and desktop support, see Interactive Services.

  • Window Stations
  • Desktops
  • Window Station and Desktop Creation
  • Process Connection to a Window Station
  • Thread Connection to a Desktop
  • Inherited Handles
  • Logoff Events
  • Window-Station Security and Access Rights
  • Desktop Security and Access Rights


Window Stations

A window station is a secure object that contains a clipboard, a set of global atoms and a group of desktop objects. The interactive window station assigned to the logon session of the interactive user also contains the keyboard, mouse, and display device. The interactive window station is visible to the user and can receive input from the user. All other window stations are noninteractive, which means that they cannot be made visible to the user, and cannot receive user input.

Applications can use the following functions for manipulating window station objects.

Function | Description
CloseWindowStation | Closes a specified window station.
CreateWindowStation | Creates a new window station.
EnumWindowStations | Enumerates the window stations in the system by repeatedly calling an application-defined EnumWindowStationProc callback function.
GetProcessWindowStation | Retrieves a handle to the window station assigned to the calling process.
GetUserObjectInformation | Gets information about a window station or desktop object.
GetUserObjectSecurity | Gets security information for a window station or desktop object.
OpenWindowStation | Opens a handle to an existing window station.
SetProcessWindowStation | Assigns a specified window station to the calling process.
SetUserObjectInformation | Sets information about a window station or desktop object.
SetUserObjectSecurity | Sets security information for a window station or desktop object.


Desktops

A desktop is a secure object contained within a window station. A desktop has a logical display surface and contains windows, menus, and hooks. A window station can have multiple desktops. Only the desktops of the interactive window station can be visible and receive user input. On the interactive window station, only one desktop at a time is active. This active desktop, also known as the input desktop, is the one that is currently visible to the user and that receives user input. Applications can use the OpenInputDesktop function to get a handle to the input desktop. Applications that have the necessary access can use the SwitchDesktop function to specify a different input desktop.

Invisible, noninteractive window stations enable service applications that do not have access to the interactive window station to start GUI applications. Applications running in a noninteractive window station cannot receive input or be visible. For example, the schedule service could use this support to start a GUI backup application on a remote computer on which the interactive window station was not accessible. For more information, see Interactive Services.

Applications can use the following functions for manipulating desktop objects:

Function | Description
CloseDesktop | Closes a specified desktop.
CreateDesktop | Creates a new desktop on a specified window station.
EnumDesktops | Enumerates the desktops on a specified window station by repeatedly calling an application-defined EnumDesktopProc callback function.
EnumDesktopWindows | Enumerates the windows on a specified desktop by repeatedly calling an application-defined EnumWindowsProc callback function.
GetThreadDesktop | Returns a handle to the desktop assigned to the calling thread.
GetUserObjectInformation | Gets information about a window station or desktop object.
GetUserObjectSecurity | Gets security information for a window station or desktop object.
OpenDesktop | Opens a handle to an existing desktop.
SetThreadDesktop | Assigns a specified desktop to the calling thread.
SetUserObjectInformation | Sets information about a window station or desktop object.
SetUserObjectSecurity | Sets security information for a window station or desktop object.


Window Station and Desktop Creation

The system automatically creates the interactive window station. When an interactive user logs on, the system associates the interactive window station with the user's logon session. The system also creates the default input desktop for the interactive window station.

When a noninteractive process such as a service application attempts to connect and no window station exists for the process' logon session, the system attempts to create a window station and desktop for the session. The name of the created window station is based on the logon session identifier, and the desktop is named "Default." The discretionary access control lists (DACLs) for the window station and desktop grant the following accesses to the service's user account.

Window Station

WINSTA_READATTRIBUTES |
WINSTA_ACCESSCLIPBOARD |
WINSTA_CREATEDESKTOP |
WINSTA_ACCESSGLOBALATOMS |
WINSTA_EXITWINDOWS |
STANDARD_RIGHTS_REQUIRED

Desktop

DESKTOP_READOBJECTS |
DESKTOP_WRITEOBJECTS |
DESKTOP_CREATEWINDOW |
DESKTOP_CREATEMENU |
DESKTOP_HOOKCONTROL |
DESKTOP_ENUMERATE |
STANDARD_RIGHTS_REQUIRED

A process can use the CreateWindowStation function to create a new window station, and the CreateDesktop function to create a new desktop.


Process Connection to a Window Station

A process automatically establishes a connection to a window station and desktop when it first calls a USER32 or GDI32 function (other than the window station or desktop functions). The system determines the window station to which a process connects according to the following rules:

  1. If the process has called the SetProcessWindowStation function, it connects to the window station specified in that call.
  2. If the process did not call SetProcessWindowStation, it connects to the window station inherited from the parent process.
  3. If the process did not call SetProcessWindowStation and did not inherit a window station, the system attempts to open for MAXIMUM_ALLOWED access and connect to a window station as follows:
    1. If a window station name was specified in the lpDesktop member of the STARTUPINFO structure that was passed to the CreateProcess function when the process was created, the process connects to the specified window station.
    2. Otherwise, if the process is running in the logon session of the interactive user, the process connects to the interactive window station.
    3. If the process is running in a noninteractive logon session, the window station name is formed based on the logon session identifier and an attempt is made to open that window station. If the open operation fails because this window station does not exist, the system tries to create the window station and a default desktop.


Thread Connection to a Desktop

After a process connects to a window station, the system assigns a desktop to the thread making the connection. The desktop assigned during this connection process cannot be closed by calling the CloseDesktop function. The system determines the desktop to assign to the thread according to the following rules:

  1. If the thread has called the SetThreadDesktop function, it connects to the specified desktop.
  2. If the thread did not call SetThreadDesktop, it connects to the desktop inherited from the parent process.
  3. If the thread did not call SetThreadDesktop and did not inherit a desktop, the system attempts to open for MAXIMUM_ALLOWED access and connect to a desktop as follows:
    1. If a desktop name was specified in the lpDesktop member of the STARTUPINFO structure that was passed to the CreateProcess function when the process was created, the thread connects to the specified desktop.
    2. Otherwise, the thread connects to the default desktop of the window station to which the process connected.

The desktop assigned during this connection process cannot be closed by calling the CloseDesktop function.


Inherited Handles

When a process is connecting to a window station or desktop, the system searches the process's handle table for inherited handles. The system uses the first window station and desktop handles that it finds. If you want a child process to connect to a particular inherited window station or desktop, you must ensure that the only the desired handles are marked inheritable. If a child process inherits multiple window station or multiple desktop handles, the results of the window station and desktop connection are undefined.

Handles to a window station and desktop that the system opens while connecting a process to a window station or desktop are not inheritable.


Logoff Events

A logoff event occurs when a process calls the ExitWindows or ExitWindowsEx function. The logoff event is identified by the window station of the process calling ExitWindowsEx.

When a logoff event occurs, the system notifies all processes in the system as follows:

  • All windows of processes in the logon session being logged off receive the WM_QUERYENDSESSION and WM_ENDSESSION messages. All windows on the desktops of the window station being logged off receive these messages, even if the windows belong to processes running in another logon session.
  • Every process in the system receives the CTRL_LOGOFF_EVENT control signal. This signal does not indicate which session is being logged off. The system sends this signal after sending the window messages. For more information on control signals, see the SetConsoleCtrlHandler function.

If the process that called ExitWindowsEx is running in the logon session of the interactive user, all processes in the logon session are terminated. If the process calling ExitWindowsEx is in some other logon session, only the notifications are made; no processes are terminated.


Window-Station Security and Access Rights

Windows NT/Windows 2000 security enables you to control access to window-station objects. For more information about security, see Access-Control Model.

You can specify a security descriptor for a window-station object when you call the CreateWindowStation function. To get or set the security descriptor of a window-station object, call the GetSecurityInfo and SetSecurityInfo functions.

When you call the OpenWindowStation function, the system checks the requested access rights against the object's security descriptor.

The valid access rights for window-station objects include the DELETE, READ_CONTROL, WRITE_DAC, and WRITE_OWNER standard access rights. Window-station objects do not support the SYNCHRONIZE standard access right. The following table lists the specific access rights for window-station objects.

Constant | Description
WINSTA_ACCESSCLIPBOARD | Required to use the clipboard.
WINSTA_ACCESSGLOBALATOMS | Required to manipulate global atoms.
WINSTA_CREATEDESKTOP | Required to create new desktop objects on the window-station.
WINSTA_ENUMDESKTOPS | Required to enumerate existing desktop objects.
WINSTA_ENUMERATE | Required for the window-station to be enumerated.
WINSTA_EXITWINDOWS | Required to successfully call the ExitWindows or ExitWindowsEx function. Window-stations can be shared by users and this access type can prevent other users of a window-station from logging off the window-station owner.
WINSTA_READATTRIBUTES | Required to read the attributes of a window-station object. This attribute includes color settings and other global window-station properties.
WINSTA_READSCREEN | Required to access screen contents.
WINSTA_WRITEATTRIBUTES | Required to modify the attributes of a window-station object. The attributes include color settings and other global window-station properties.

The following are the generic mappings for the interactive window-station object, which is the window-station assigned to the logon session of the interactive user.

Value | Maps to
GENERIC_READ | STANDARD_RIGHTS_READ, WINSTA_ENUMDESKTOPS, WINSTA_ENUMERATE, WINSTA_READATTRIBUTES, and WINSTA_READSCREEN
GENERIC_WRITE | STANDARD_RIGHTS_WRITE, WINSTA_ACCESSCLIPBOARD, WINSTA_CREATEDESKTOP, and WINSTA_WRITEATTRIBUTES
GENERIC_EXECUTE | STANDARD_RIGHTS_EXECUTE, WINSTA_ACCESSGLOBALATOMS, and WINSTA_EXITWINDOWS
GENERIC_ALL | STANDARD_RIGHTS_REQUIRED, WINSTA_ACCESSCLIPBOARD, WINSTA_ACCESSGLOBALATOMS, WINSTA_CREATEDESKTOP, WINSTA_ENUMDESKTOPS, WINSTA_ENUMERATE, WINSTA_EXITWINDOWS, WINSTA_READATTRIBUTES, WINSTA_READSCREEN, and WINSTA_WRITEATTRIBUTES

The following are the generic mappings for a noninteractive window-station object. The system assigns noninteractive window-stations to all logon sessions other than that of the interactive user.

Value | Maps to
GENERIC_READ | STANDARD_RIGHTS_READ, WINSTA_ENUMDESKTOPS, WINSTA_ENUMERATE, and WINSTA_READATTRIBUTES
GENERIC_WRITE | STANDARD_RIGHTS_WRITE, WINSTA_ACCESSCLIPBOARD, and WINSTA_CREATEDESKTOP
GENERIC_EXECUTE | STANDARD_RIGHTS_EXECUTE, WINSTA_ACCESSGLOBALATOMS, and WINSTA_EXITWINDOWS
GENERIC_ALL | STANDARD_RIGHTS_REQUIRED, WINSTA_ACCESSCLIPBOARD, WINSTA_ACCESSGLOBALATOMS, WINSTA_CREATEDESKTOP, WINSTA_ENUMDESKTOPS, WINSTA_ENUMERATE, WINSTA_EXITWINDOWS, and WINSTA_READATTRIBUTES

You can request the ACCESS_SYSTEM_SECURITY access right to a window-station object if you want to read or write the object's SACL. For more information, see Access-Control Lists (ACLs) and SACL Access Right.


Desktop Security and Access Rights

Windows NT/Windows 2000 security enables you to control access to desktop objects. For more information about security, see Access-Control Model.

You can specify a security descriptor for a desktop object when you call the CreateDesktop function. If none is specified, a new desktop inherits a security descriptor from its parent window-station. To get or set the security descriptor of a window-station object, call the GetSecurityInfo and SetSecurityInfo functions.

When you call the OpenDesktop or OpenInputDesktop function, the system checks the requested access rights against the object's security descriptor.

The valid access rights for desktop objects include the DELETE, READ_CONTROL, WRITE_DAC, and WRITE_OWNER standard access rights. Desktop objects do not support the SYNCHRONIZE standard access right. The following table lists the specific access rights for desktop objects.

Constant | Description
DESKTOP_CREATEMENU | Required to create a menu on the the desktop.
DESKTOP_CREATEWINDOW | Required to create a window on the desktop.
DESKTOP_ENUMERATE | Required for the desktop to be enumerated.
DESKTOP_HOOKCONTROL | Required to establish any of the window hooks.
DESKTOP_JOURNALPLAYBACK | Required to perform journal playback on a desktop.
DESKTOP_JOURNALRECORD | Required to perform journal recording on a desktop.
DESKTOP_READOBJECTS | Required to read objects on the desktop.
DESKTOP_SWITCHDESKTOP | Required to activate the desktop using the SwitchDesktop function.
DESKTOP_WRITEOBJECTS | Required to write objects on the desktop.

The following are the generic mappings for a desktop object contained in the interactive window-station of the user's logon session.

Value | Maps to
GENERIC_READ | DESKTOP_ENUMERATE, DESKTOP_READOBJECTS, and STANDARD_RIGHTS_READ
GENERIC_WRITE | DESKTOP_CREATEMENU, DESKTOP_CREATEWINDOW, DESKTOP_HOOKCONTROL, DESKTOP_JOURNALPLAYBACK, DESKTOP_JOURNALRECORD, DESKTOP_WRITEOBJECTS, and STANDARD_RIGHTS_WRITE
GENERIC_EXECUTE | DESKTOP_SWITCHDESKTOP and STANDARD_RIGHTS_EXECUTE
GENERIC_ALL | DESKTOP_CREATEMENU, DESKTOP_CREATEWINDOW, DESKTOP_ENUMERATE, DESKTOP_HOOKCONTROL, DESKTOP_JOURNALPLAYBACK, DESKTOP_JOURNALRECORD, DESKTOP_READOBJECTS, DESKTOP_SWITCHDESKTOP, DESKTOP_WRITEOBJECTS, and STANDARD_RIGHTS_REQUIRED

You can request the ACCESS_SYSTEM_SECURITY access right to a desktop object if you want to read or write the object's SACL. For more information, see Access-Control Lists (ACLs) and SACL Access Right.


Using Window Stations and Desktops

  • Creating an interactive process
  • Interacting with the user in a service
  • Handling logoff events


Creating an Interactive Process

The following code fragment shows how a service application could use the STARTUPINFO structure in a CreateProcess call to create a process that has access to the user's interactive window station and default desktop. A noninteractive service application could use this technique to interact with the logged on user. The new process could then use a named pipe or some other means of interprocess communication to communicate with the service application.

To create an interactive process as shown in this example, a service application must be logged in to the LocalSystem account.

#include <windows.h>

STARTUPINFO si;
PROCESS_INFORMATION ProcessInformation;

si.cb = sizeof(STARTUPINFO);
si.lpReserved = NULL;
si.lpTitle = NULL;
si.lpDesktop = "WinSta0\\Default";
si.dwX = si.dwY = si.dwXSize = si.dwYSize = 0L;
si.dwFlags = 0;;
si.wShowWindow = SW_SHOW;
si.lpReserved2 = NULL;
si.cbReserved2 = 0;
if (CreateProcess(NULL, lpszCmdLine, NULL, NULL, FALSE,
                   0, NULL, NULL, &si, &ProcessInformation))
{
    CloseHandle(ProcessInformation.hProcess);
    CloseHandle(ProcessInformation.hThread);
}


Interacting with the User in a Service

For a noninteractive service application to interact with the user, it must open the user's window station ("WinSta0") and desktop ("Default"). By default, only the logged-on user and service applications running in the LocalSystem account are granted access to the user's window station and desktop. This means that services running in other accounts must either impersonate the user when opening the interactive window station and desktop, or have access granted to those accounts by the user.

For compatibility with versions of Windows NT/Windows 2000 that support multiple users and/or multiple desktops per user, the user's window station and desktop names should not be hard-coded. Client applications should pass the names of their window station and desktop to the service as part of the request to the service.

This code sample displays a message on the user's desktop in response to an RPC request from one of the user's applications. Note that a global variable dwGuiThreadId in this example is also used in the logoff handling example. If the thread that displays the message box terminates after it is done with the message box, it is not necessary to save and restore the thread's desktop. It is necessary to restore the process's window station.

DWORD dwGuiThreadId = 0;

int
UserMessageBox(
    RPC_BINDING_HANDLE h,
    LPSTR lpszWindowStation,
    LPSTR lpszDesktop,
    LPSTR lpszText,
    LPSTR lpszTitle,
    UINT fuStyle)
{
    DWORD dwThreadId;
    HWINSTA hwinstaSave;
    HDESK hdeskSave;
    HWINSTA hwinstaUser;
    HDESK hdeskUser;
    int result;

    // Ensure connection to service window station and desktop, and
    // save their handles.

    GetDesktopWindow();
    hwinstaSave = GetProcessWindowStation();
    dwThreadId = GetCurrentThreadId();
    hdeskSave = GetThreadDesktop(dwThreadId);

    // Impersonate the client and connect to the User's
    // window station and desktop.

    RpcImpersonateClient(h);
    hwinstaUser = OpenWindowStation(lpszWindowStation, FALSE, MAXIMUM_ALLOWED);
    if (hwinstaUser == NULL)
    {
        RpcRevertToSelf();
        return 0;
    }
    SetProcessWindowStation(hwinstaUser);
    hdeskUser = OpenDesktop(lpszDesktop, 0, FALSE, MAXIMUM_ALLOWED);
    RpcRevertToSelf();
    if (hdeskUser == NULL)
    {
        SetProcessWindowStation(hwinstaSave);
        CloseWindowStation(hwinstaUser);
        return 0;
    }
    SetThreadDesktop(hdeskUser);

    // Display message box.

    dwGuiThreadId = dwThreadId;
    result = MessageBox(NULL, lpszText, lpszTitle, fuStyle);
    dwGuiThreadId = 0;

    // Restore window station and desktop.

    SetThreadDesktop(hdeskSave);
    SetProcessWindowStation(hwinstaSave);
    CloseDesktop(hdeskUser);
    CloseWindowStation(hwinstaUser);

    return result;
}


Handling Logoff Events

Service applications that interact with the user should be prepared to handle logoff events. When a logoff event occurs, the service application must close all handles to the user's window station and desktop.

This sample demonstrates how the message box in the interaction example code should be dismissed at logoff. The ConsoleCtrlHandler function in this example is a HandlerRoutine that was specified by a call to the SetConsoleCtrlHandler function.

BOOL CALLBACK EnumProc(
    HWND hwnd,
    LPARAM lParam)
{
    // Send a WM_CLOSE to destroy the window, because DestroyWindow
    // does not work across threads.

    SendMessage(hwnd, WM_CLOSE, 0, 0);
    return TRUE;
}

BOOL ConsoleCtrlHandler(
    DWORD dwCtrlType)
{
    if (dwCtrlType == CTRL_LOGOFF_EVENT && dwGuiThreadId != 0)
    {
        SetThreadDesktop(GetThreadDesktop(dwGuiThreadId));
        EnumThreadWindows(dwGuiThreadId, EnumProc, 0);
    }
    return FALSE;
}


Window Station and Desktop Reference

The following elements are associated with window station and desktop features.

  • Window Station and Desktop Functions
  • Window Station and Desktop Structures


Window Station and Desktop Functions

Use the following functions to implement window station and desktop features.

Function | Description
CloseDesktop | Closes an open handle to a desktop object.
CloseWindowStation | Closes an open window station handle.
CreateDesktop | Creates a new desktop on the window station associated with the calling process.
CreateWindowStation | Creates a window station object.
EnumDesktopProc | An application-defined callback function used with the EnumDesktops function.
EnumDesktops | Enumerates all desktops in the window station assigned to the calling process.
EnumDesktopWindows | Enumerates all windows on a desktop by passing a handle to each window.
EnumWindowStationProc | An application-defined callback function used with the EnumWindowStations function.
EnumWindowStations | Enumerates all window stations in the system.
GetProcessWindowStation | Retrieves a handle to the window station associated with the calling process.
GetThreadDesktop | Retrieves a handle to the desktop associated with a specified thread.
GetUserObjectInformation | Retrieves information about a window station or desktop object.
GetUserObjectSecurity | Retrieves security information for the specified user object.
OpenDesktop | Retrieves a handle to an existing desktop.
OpenInputDesktop | Retrieves a handle to the desktop that receives user input.
OpenWindowStation | Retrieves a handle to an existing window station.
SetProcessWindowStation | Assigns a window station to the calling process.
SetThreadDesktop | Assigns a desktop to the calling thread.
SetUserObjectInformation | Sets information about a window station or desktop object.
SetUserObjectSecurity | Sets the security of a user object.
SwitchDesktop | Makes a desktop visible and activates it.


CloseDesktop

The CloseDesktop function closes an open handle to a desktop object. A desktop is a secure object contained within a window station object. A desktop has a logical display surface and contains windows, menus and hooks.

BOOL CloseDesktop(
  HDESK hDesktop  // handle to desktop
);

Parameters

hDesktop
[in] Handle to the desktop to close. This can be a handle returned by the CreateDesktop, OpenDesktop, or OpenInputDesktop 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

The CloseDesktop function will fail if any thread in the calling process is using the specified desktop handle or if the handle refers to the initial desktop of the calling process.

For an example, see Interacting with the User in a Service.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Window Stations and Desktops Overview, Window Station and Desktop Functions, CreateDesktop, OpenDesktop, OpenInputDesktop


CloseWindowStation

The CloseWindowStation function closes an open window station handle.

BOOL CloseWindowStation(
  HWINSTA hWinSta  // handle to window station
);

Parameters

hWinSta
[in] Handle to the window station to be closed. This handle is returned by the CreateWindowStation and OpenWindowStation 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

The CloseWindowStation function will fail if the handle being closed is for the window station assigned to the calling process.

For an example, see Interacting with the User in a Service.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Window Stations and Desktops Overview, Window Station and Desktop Functions, SetProcessWindowStation


CreateDesktop

The CreateDesktop function creates a new desktop on the window station associated with the calling process. It retrieves a handle that can be used to access the new desktop. The calling process must have an associated window station, either assigned by the system at process creation time or set by SetProcessWindowStation. A desktop is a secure object contained within a window station object. A desktop has a logical display surface and contains windows, menus, and hooks.

HDESK CreateDesktop(
  LPCTSTR lpszDesktop,         // name of new desktop
  LPCTSTR lpszDevice,          // reserved; must be NULL
  LPDEVMODE pDevmode,          // reserved; must be NULL
  DWORD dwFlags,               // desktop interaction
  ACCESS_MASK dwDesiredAccess, // access of returned handle
  LPSECURITY_ATTRIBUTES lpsa   // security attributes
);

Parameters

lpszDesktop
[in] Pointer to a null-terminated string specifying the name of the desktop to be created. Desktop names are case-insensitive and may not contain backslash characters (\).
lpszDevice
Reserved; must be NULL.
pDevmode
Reserved; must be NULL.
dwFlags
[in] Specifies how the calling application will cooperate with other applications on the desktop. This parameter can be zero or the following value.
Value | Description
DF_ALLOWOTHERACCOUNTHOOK | Allows processes running in other accounts on the desktop to set hooks in this process.

dwDesiredAccess
[in] Specifies the access rights the returned handle has to the desktop. This parameter must include the DESKTOP_CREATEWINDOW flag because internally CreateDesktop uses the handle to create a window. In addition, you can specify any of the standard access rights, such as READ_CONTROL or WRITE_DAC, and a combination of the following desktop-specific access rights.
Value | Description
DESKTOP_CREATEMENU | Required to create a menu on the desktop.
DESKTOP_CREATEWINDOW | Required to create a window on the desktop.
DESKTOP_ENUMERATE | Required for the desktop to be enumerated.
DESKTOP_HOOKCONTROL | Required to establish any of the window hooks.
DESKTOP_JOURNALPLAYBACK | Required to perform journal playback on the desktop.
DESKTOP_JOURNALRECORD | Required to perform journal recording on the desktop.
DESKTOP_READOBJECTS | Required to read objects on the desktop.
DESKTOP_SWITCHDESKTOP | Required to activate the desktop using the SwitchDesktop function.
DESKTOP_WRITEOBJECTS | Required to write objects on the desktop.

lpsa
[in] Pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. If lpsa is NULL, the handle cannot be inherited.

The lpSecurityDescriptor member of the structure specifies a security descriptor for the new desktop. If lpsa is NULL, the desktop inherits its security descriptor from the parent window station.

Return Values

If the function succeeds, the return value is a handle to the newly created desktop. If the specified desktop already exists, the function succeeds and returns a handle to the existing desktop. When you are finished using the handle, call the CloseDesktop function to close it.

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

Remarks

The CreateDesktop function returns a handle that can be used to access the desktop.

If the dwDesiredAccess parameter specifies the READ_CONTROL, WRITE_DAC, or WRITE_OWNER standard access rights to access the security descriptor of the desktop object, you must also request the DESKTOP_READOBJECTS and DESKTOP_WRITEOBJECTS access rights.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Window Stations and Desktops Overview, Window Station and Desktop Functions, CloseDesktop, SECURITY_ATTRIBUTES, SetProcessWindowStation, SwitchDesktop


CreateWindowStation

The CreateWindowStation function creates a window station object. It retrieves a handle that can be used to access the window station. A window station is a secure object that contains a set of global atoms, a clipboard, and a set of desktop objects.

HWINSTA CreateWindowStation(
  LPTSTR lpwinsta,             // new window station name
  DWORD dwReserved,            // reserved; must be zero
  ACCESS_MASK dwDesiredAccess, // requested access
  LPSECURITY_ATTRIBUTES lpsa   // security attributes
);

Parameters

lpwinsta
[in] Pointer to a null-terminated string specifying the name of the window station to be created. Window station names are case-insensitive and cannot contain backslash characters (\). Only members of the Administrators group are allowed to specify a name. If lpwinsta is NULL, the system forms a window station name using the logon session identifier for the calling process. To get this name, call the GetUserObjectInformation function.
dwReserved
Reserved; must be zero.
dwDesiredAccess
[in] Specifies the type of access to the window station. This parameter can be one or more of the following values.
Value | Description
WINSTA_ACCESSCLIPBOARD | Required to use the clipboard.
WINSTA_ACCESSGLOBALATOMS | Required to manipulate global atoms.
WINSTA_CREATEDESKTOP | Required to create new desktop objects on the window station.
WINSTA_ENUMDESKTOPS | Required to enumerate existing desktop objects.
WINSTA_ENUMERATE | Required for the window station to be enumerated.
WINSTA_EXITWINDOWS | Required to successfully call the ExitWindows or ExitWindowsEx functions.
WINSTA_READATTRIBUTES | Required to read the attributes of a window station object.
WINSTA_READSCREEN | Required to access screen contents.
WINSTA_WRITEATTRIBUTES | Required to modify the attributes of a window station object.

lpsa
[in] Pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. If lpsa is NULL, the handle cannot be inherited.

The lpSecurityDescriptor member of the structure specifies a security descriptor for the new window station. If lpsa is NULL, the window station (and any desktops created within the window) gets a security descriptor that grants GENERIC_ALL access to all users.

Return Values

If the function succeeds, the return value is a handle to the newly created window station. If the specified window station already exists, the function succeeds and returns a handle to the existing window station.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Window Stations and Desktops Overview, Window Station and Desktop Functions, GetUserObjectInformation, OpenWindowStation


EnumDesktopProc

The EnumDesktopProc function is an application-defined callback function used with the EnumDesktops function. It receives a desktop name. The DESKTOPENUMPROC type defines a pointer to this callback function. EnumDesktopProc is a placeholder for the application-defined function name.

BOOL CALLBACK EnumDesktopProc(
  LPTSTR lpszDesktop,  // desktop name
  LPARAM lParam        // user-defined value
);

Parameters

lpszDesktop
[in] Pointer to a null-terminated string specifying the name of the desktop.
lParam
[in] The application-defined value specified in the EnumDesktops function.

Return Values

To continue enumeration, the callback function must return TRUE. To stop enumeration, it must return FALSE.

Remarks

An application registers an EnumDesktopProc function by passing its address to the EnumDesktops function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Unicode: Declared as Unicode and ANSI prototypes.

See Also

Window Stations and Desktops Overview, Window Station and Desktop Functions, EnumDesktops


EnumDesktops

The EnumDesktops function enumerates all desktops in the window station assigned to the calling process. The function does so by passing the name of each desktop, in turn, to an application-defined callback function.

BOOL EnumDesktops(
  HWINSTA hwinsta,            // handle to window station
  DESKTOPENUMPROC lpEnumFunc, // callback function
  LPARAM lParam               // value for callback function
);

Parameters

hwinsta
[in] Handle to the window station whose desktops are to be enumerated. The CreateWindowStation, GetProcessWindowStation, and OpenWindowStation functions return a window station handle.
lpEnumFunc
[in] Pointer to an application-defined EnumDesktopProc callback function.
lParam
[in] 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 calling process must have WINSTA_ENUMDESKTOPS access to the window station. The EnumDesktops function enumerates only those desktops for which the calling process has DESKTOP_ENUMERATE access.

The EnumDesktops function repeatedly invokes the lpEnumFunc callback function until the last desktop is enumerated or the callback function returns FALSE.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Window Stations and Desktops Overview, Window Station and Desktop Functions, CreateWindowStation, EnumDesktopProc, GetProcessWindowStation, OpenWindowStation


EnumDesktopWindows

The EnumDesktopWindows function enumerates all top-level windows on a desktop by passing a handle to each window, in turn, to an application-defined callback function.

BOOL EnumDesktopWindows(
  HDESK hDesktop,   // handle to desktop to enumerate
  WNDENUMPROC lpfn, // callback function
  LPARAM lParam     // value to pass to callback function
);

Parameters

hDesktop
[in] Handle to the desktop whose top-level windows are to be enumerated. The CreateDesktop, OpenDesktop, and GetThreadDesktop functions return a desktop handle. If this parameter is NULL, the current desktop is used.
lpfn
[in] Pointer to an application-defined EnumWindowsProc callback function.
lParam
[in] 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.

Windows 2000 or later: If there are no windows on the desktop, GetLastError returns ERROR_INVALID_HANDLE.

Remarks

The EnumDesktopWindows function repeatedly invokes the lpfn callback function until the last top-level window is enumerated or the callback function returns FALSE.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Window Stations and Desktops Overview, Window Station and Desktop Functions, CreateDesktop, EnumWindowsProc, GetThreadDesktop, OpenDesktop


EnumWindowStationProc

The EnumWindowStationProc function is an application-defined callback function used with the EnumWindowStations function. It receives a window station name. The WINSTAENUMPROC type defines a pointer to this callback function. EnumWindowStationProc is a placeholder for the application-defined function name.

BOOL CALLBACK EnumWindowStationProc(
  LPTSTR lpszWindowStation  // window station name
  LPARAM lParam             // user-defined value
);

Parameters

lpszWindowStation
[in] Pointer to the null-terminated name of a window station.
lParam
[in] The application-defined value specified in the EnumWindowStations 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 EnumWindowStations.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Unicode: Declared as Unicode and ANSI prototypes.

See Also

Window Stations and Desktops Overview, Window Station and Desktop Functions, EnumWindowStations


EnumWindowStations

The EnumWindowStations function enumerates all window stations in the system by passing the name of each window station, in turn, to an application-defined callback function.

BOOL EnumWindowStations(
  WINSTAENUMPROC lpEnumFunc, // callback function
  LPARAM lParam              // value for callback function
);

Parameters

lpEnumFunc
[in] Pointer to an application-defined EnumWindowStationProc callback function.
lParam
[in] 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 EnumWindowStations function enumerates only those window stations for which the calling process has WINSTA_ENUMERATE access.

EnumWindowStations repeatedly invokes the lpEnumFunc callback function until the last window station is enumerated or the callback function returns FALSE.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Window Stations and Desktops Overview, Window Station and Desktop Functions, EnumWindowStationProc


GetProcessWindowStation

The GetProcessWindowStation function retrieves a handle to the window station associated with the calling process.

HWINSTA GetProcessWindowStation(VOID);

Parameters

This function has no parameters.

Return Values

If the function succeeds, the return value is a handle to the window station associated with the calling process.

If the function fails, the return value is NULL. This can occur if the calling process is not an application written for Windows NT/Windows 2000. To get extended error information, call GetLastError.

Remarks

The system associates a window station with a process when the process is created. A process can use the SetProcessWindowStation function to change its window station.

The calling process can use the returned handle in calls to the GetUserObjectInformation, GetUserObjectSecurity, SetUserObjectInformation, and SetUserObjectSecurity functions.

Windows NT 4.0 and later: A service application is created with an associated window station and desktop, so there is no need to call a USER or GDI function to connect the service to a window station and desktop.

Windows NT 3.51: A service application does not have an associated window station or desktop until the service calls a USER or GDI function that interacts with the desktop. If a service calls GetProcessWindowStation before it has an associated window station, the return value is NULL. After a service interacts with the desktop, the return value is a valid window station handle.

For an example, see Interacting with the User in a Service.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Window Stations and Desktops Overview, Window Station and Desktop Functions, GetThreadDesktop, GetUserObjectInformation, GetUserObjectSecurity, SetProcessWindowStation, SetUserObjectInformation, SetUserObjectSecurity


GetThreadDesktop

The GetThreadDesktop function retrieves a handle to the desktop associated with a specified thread.

HDESK GetThreadDesktop(
  DWORD dwThreadId   // thread identifier
);

Parameters

dwThreadId
[in] Handle to the thread for which to return the desktop handle. The GetCurrentThreadId and CreateProcess functions return thread identifiers.

Return Values

If the function succeeds, the return value is a handle to the desktop associated with the specified thread. You do not need to call the CloseDesktop function to close the returned handle.

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

Remarks

The system associates a desktop with a thread when that thread is created. A thread can use the SetThreadDesktop function to change its desktop. The desktop associated with a thread must be on the window station associated with the thread's process.

The calling process can use the returned handle in calls to the GetUserObjectInformation, GetUserObjectSecurity, SetUserObjectInformation, and SetUserObjectSecurity functions.

Windows 95/98/Me: The system does not support multiple desktops, so GetThreadDesktop always returns the same value.

Windows NT 4.0 and later: A service application is created with an associated window station and desktop, so there is no need to call a USER or GDI function to connect the service to a window station and desktop.

Windows NT 3.51: A service application does not have an associated window station or desktop until the service calls a USER or GDI function that interacts with the desktop. If a service calls GetThreadDesktop before it has an associated desktop, the return value is NULL. After a service interacts with the desktop, the return value is a valid desktop handle.

For an example, see Interacting with the User in a Service.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Window Stations and Desktops Overview, Window Station and Desktop Functions, GetCurrentThreadId, GetProcessWindowStation, GetUserObjectInformation, GetUserObjectSecurity, SetProcessWindowStation, SetThreadDesktop, SetUserObjectInformation, SetUserObjectSecurity


GetUserObjectInformation

The GetUserObjectInformation function retrieves information about a window station or desktop object.

BOOL GetUserObjectInformation(
  HANDLE hObj,            // handle to object
  int nIndex,             // type of information to retrieve
  PVOID pvInfo,           // information buffer
  DWORD nLength,          // size of the buffer
  LPDWORD lpnLengthNeeded // receives required buffer size
);

Parameters

hObj
[in] Handle to the window station or desktop object for which to return information. This can be a handle of type HDESK or HWINSTA (for example, a handle returned by CreateWindowStation, OpenWindowStation, CreateDesktop, or OpenDesktop).
nIndex
[in] Specifies the object information to be retrieved. The parameter can be one of the following values.
Value | Description
UOI_FLAGS | Returns handle flags. The pvInfo parameter must point to a USEROBJECTFLAGS structure.
UOI_NAME | Returns a string containing the name of the object.
UOI_TYPE | Returns a string containing the type name of the object.
UOI_USER_SID | Returns the SID structure that identifies the user that is currently associated with the specified object. If no user is associated with the object, the value returned in the buffer pointed to by lpnLengthNeeded is zero. Note that SID is a variable length structure. You will usually make a call to GetUserObjectInformation to determine the length of the SID before retrieving its value.

pvInfo
[out] Pointer to a buffer to receive the object information.
nLength
[in] Specifies the size, in bytes, of the buffer pointed to by the pvInfo parameter.
lpnLengthNeeded
[out] Pointer to a variable receiving the number of bytes required to store the requested information. If this variable's value is greater than the value of the nLength parameter when the function returns, the function returns FALSE, and none of the information is copied to the pvInfo buffer. If the value of the variable pointed to by lpnLengthNeeded is less than or equal to the value of nLength, the entire information block is copied.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Window Stations and Desktops Overview, Window Station and Desktop Functions, CreateDesktop, CreateWindowStation, GetUserObjectSecurity, OpenDesktop, OpenWindowStation, SetUserObjectInformation, SetUserObjectSecurity, SID, USEROBJECTFLAGS


OpenDesktop

The OpenDesktop function retrieves a handle to an existing desktop. A desktop is a secure object contained within a window station object. A desktop has a logical display surface and contains windows, menus and hooks.

HDESK OpenDesktop(
  LPTSTR lpszDesktop,          // desktop name
  DWORD dwFlags,               // interaction option
  BOOL fInherit,               // inheritance option
  ACCESS_MASK dwDesiredAccess  // handle access
);

Parameters

lpszDesktop
[in] Pointer to null-terminated string specifying the name of the desktop to be opened. Desktop names are case-insensitive.
dwFlags
[in] Specifies how the calling application will cooperate with other applications on the desktop. This parameter can be zero or the following value.
Value | Description
DF_ALLOWOTHERACCOUNTHOOK | Allows processes running in other accounts on the desktop to set hooks in this process.

fInherit
[in] Specifies whether the returned handle is inherited when a new process is created. If this value is TRUE, new processes will inherit the handle.
dwDesiredAccess
[in] Specifies the access rights the returned handle has to the desktop. This parameter can include any of the standard access rights, such as READ_CONTROL or WRITE_DAC, and a combination of the following desktop-specific access rights.
Value | Description
DESKTOP_CREATEMENU | Required to create a menu on the desktop.
DESKTOP_CREATEWINDOW | Required to create a window on the desktop.
DESKTOP_ENUMERATE | Required for the desktop to be enumerated.
DESKTOP_HOOKCONTROL | Required to establish any of the window hooks.
DESKTOP_JOURNALPLAYBACK | Required to perform journal playback on the desktop.
DESKTOP_JOURNALRECORD | Required to perform journal recording on the desktop.
DESKTOP_READOBJECTS | Required to read objects on the desktop.
DESKTOP_SWITCHDESKTOP | Required to activate the desktop using SwitchDesktop.
DESKTOP_WRITEOBJECTS | Required to write objects on the desktop.

Return Values

If the function succeeds, the return value is a handle to the opened desktop. When you are finished using the handle, call the CloseDesktop function to close it.

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

Remarks

The calling process must have an associated window station, either assigned by the system at process creation time or set by the SetProcessWindowStation function.

If the dwDesiredAccess parameter specifies the READ_CONTROL, WRITE_DAC, or WRITE_OWNER standard access rights to access the security descriptor of the desktop object, you must also request the DESKTOP_READOBJECTS and DESKTOP_WRITEOBJECTS access rights.

For an example, see Interacting with the User in a Service.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Window Stations and Desktops Overview, Window Station and Desktop Functions, CloseDesktop, CreateDesktop, SetProcessWindowStation, SetThreadDesktop, SwitchDesktop


OpenInputDesktop

The OpenInputDesktop function retrieves a handle to the desktop that receives user input. The input desktop is a desktop on the window station associated with the logged-on user.

HDESK OpenInputDesktop(
  DWORD dwFlags,               // interaction option
  BOOL fInherit,               // inheritance option
  ACCESS_MASK dwDesiredAccess  // handle access
);

Parameters

dwFlags
[in] Specifies how the calling application will cooperate with other applications on the desktop. This parameter can be zero or the following value.
Value | Description
DF_ALLOWOTHERACCOUNTHOOK | Allows processes running in other accounts on the desktop to set hooks in this process.

fInherit
[in] Specifies whether the returned handle is inherited when a new process is created. If this value is TRUE, new processes will inherit the handle.
dwDesiredAccess
[in] Specifies the access rights the returned handle has to the desktop. This parameter can include any of the standard access rights, such as READ_CONTROL or WRITE_DAC, and a combination of the following desktop-specific access rights.
Value | Description
DESKTOP_CREATEMENU | Required to create a menu on the desktop.
DESKTOP_CREATEWINDOW | Required to create a window on the desktop.
DESKTOP_ENUMERATE | Required for the desktop to be enumerated.
DESKTOP_HOOKCONTROL | Required to establish any of the window hooks.
DESKTOP_JOURNALPLAYBACK | Required to perform journal playback on the desktop.
DESKTOP_JOURNALRECORD | Required to perform journal recording on the desktop.
DESKTOP_READOBJECTS | Required to read objects on the desktop.
DESKTOP_SWITCHDESKTOP | Required to activate the desktop using SwitchDesktop.
DESKTOP_WRITEOBJECTS | Required to write objects on the desktop.

Return Values

If the function succeeds, the return value is a handle to the desktop that receives user input. When you are finished using the handle, call the CloseDesktop function to close it.

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

Remarks

The calling process must have an associated window station, either assigned by the system at process creation time or set by SetProcessWindowStation. The window station associated with the calling process must be capable of receiving input.

An application can use the SwitchDesktop function to change the input desktop.

If the dwDesiredAccess parameter specifies the READ_CONTROL, WRITE_DAC, or WRITE_OWNER standard access rights to access the security descriptor of the desktop object, you must also request the DESKTOP_READOBJECTS and DESKTOP_WRITEOBJECTS access rights.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Window Stations and Desktops Overview, Window Station and Desktop Functions, CloseDesktop, SetProcessWindowStation, SwitchDesktop


OpenWindowStation

The OpenWindowStation function retrieves a handle to an existing window station.

HWINSTA OpenWindowStation(
  LPTSTR lpszWinSta,           // window station name
  BOOL fInherit,               // inheritance option
  ACCESS_MASK dwDesiredAccess  // handle access
);

Parameters

lpszWinSta
[in] Pointer to a null-terminated string specifying the name of the window station to be opened. Window station names are case-insensitive.
fInherit
[in] Specifies whether the returned handle is inherited when a new process is created. If this value is TRUE, new processes will inherit the handle.
dwDesiredAccess
[in] Specifies the type of access to the window station. This parameter can be one or more of the following values.
Value | Description
WINSTA_ACCESSCLIPBOARD | Required to use the clipboard.
WINSTA_ACCESSGLOBALATOMS | Required to manipulate global atoms.
WINSTA_CREATEDESKTOP | Required to create new desktop objects on the window station.
WINSTA_ENUMDESKTOPS | Required to enumerate existing desktop objects.
WINSTA_ENUMERATE | Required for the window station to be enumerated.
WINSTA_EXITWINDOWS | Required to successfully call the ExitWindows and ExitWindowsEx functions.
WINSTA_READATTRIBUTES | Required to read the attributes of a window station object.
WINSTA_READSCREEN | Required to access screen contents.
WINSTA_WRITEATTRIBUTES | Required to modify the attributes of a window station object.

Return Values

If the function succeeds, the return value is the handle to the specified window station.

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

Remarks

After you are done with the HWINSTA handle, you must call CloseWindowStation to free the handle.

For an example, see Interacting with the User in a Service.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Window Stations and Desktops Overview, Window Station and Desktop Functions, CloseWindowStation, ExitWindows, ExitWindowsEx


SetProcessWindowStation

The SetProcessWindowStation function assigns a window station to the calling process. This enables the process to access objects in the window station such as desktops, the clipboard, and global atoms. All subsequent operations on the window station use the access rights granted to hWinSta.

BOOL SetProcessWindowStation(
  HWINSTA hWinSta  // handle to window station
);

Parameters

hWinSta
[in] Handle to the window station to be assigned to the calling process. This can be a handle returned by the CreateWindowStation, OpenWindowStation, or GetProcessWindowStation 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.

For an example, see Interacting with the User in a Service.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Window Stations and Desktops Overview, Window Station and Desktop Functions, CreateWindowStation, GetProcessWindowStation, OpenWindowStation, SetThreadDesktop


SetThreadDesktop

The SetThreadDesktop function assigns a desktop to the calling thread. All subsequent operations on the desktop use the access rights granted to hDesktop.

BOOL SetThreadDesktop(
  HDESK hDesktop  // handle to the desktop
);

Parameters

hDesktop
[in] Handle to the desktop to be assigned to the calling thread. This handle is returned by the CreateDesktop, GetThreadDesktop, and OpenDesktop 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

The SetThreadDesktop function will fail if the calling thread has any windows or hooks on its current desktop (unless the hDesktop parameter is a handle to the current desktop).

For an example, see Interacting with the User in a Service.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Window Stations and Desktops Overview, Window Station and Desktop Functions, CreateDesktop, GetThreadDesktop, OpenDesktop, SetProcessWindowStation


SetUserObjectInformation

The SetUserObjectInformation function sets information about a window station or desktop object.

BOOL SetUserObjectInformation(
  HANDLE hObj,  // handle to the object
  int nIndex,   // type of information to set
  PVOID pvInfo, // information buffer
  DWORD nLength // size of buffer
);

Parameters

hObj
[in] Handle to the window station or desktop object for which to set object information. This value can be a handle of type HDESK or HWINSTA (for example, a handle returned by CreateWindowStation, OpenWindowStation, CreateDesktop, or OpenDesktop).
nIndex
[in] Specifies the object information to be set. This parameter must be the following value.
Value | Description
UOI_FLAGS | Sets the object's handle flags. The pvInfo parameter must point to a USEROBJECTFLAGS structure.

pvInfo
[in] Pointer to a buffer containing the object information.
nLength
[in] Specifies the size, in bytes, of the information contained in the buffer pointed to by pvInfo.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Window Stations and Desktops Overview, Window Station and Desktop Functions, CreateDesktop, CreateWindowStation, GetUserObjectInformation, OpenDesktop,.OpenWindowStation, USEROBJECTFLAGS


SwitchDesktop

The SwitchDesktop function makes a desktop visible and activates it. This enables the desktop to receive input from the user. The calling process must have DESKTOP_SWITCHDESKTOP access to the desktop for the SwitchDesktop function to succeed.

BOOL SwitchDesktop(
  HDESK hDesktop  // handle to desktop to activate
);

Parameters

hDesktop
[in] Handle to the desktop to be made visible and active. This handle is returned by the CreateDesktop and OpenDesktop 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

The SwitchDesktop function fails if the desktop belongs to an invisible window station. SwitchDesktop also fails when called from a process associated with a secured desktop, such as the WinLogon and ScreenSaver desktops.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Window Stations and Desktops Overview, Window Station and Desktop Functions, CreateDesktop, OpenDesktop


Window Station and Desktop Structures

Use the following structure to manipulate window station and desktop objects.

USEROBJECTFLAGS


USEROBJECTFLAGS

The USEROBJECTFLAGS structure contains information about a window station or desktop handle.

typedef struct tagUSEROBJECTFLAGS {
    BOOL fInherit;
    BOOL fReserved;
    DWORD dwFlags;
} USEROBJECTFLAGS, *PUSEROBJECTFLAGS;

Members

fInherit
Specifies whether the handle is inherited when a new process is created. If this member is TRUE, new processes will inherit the handle.
fReserved
Reserved for future use. This member must be FALSE.
dwFlags
For window stations, this member can contain the following window station attribute.
Value | Description
WSF_VISIBLE | Window station has visible display surfaces.

For desktops, the dwFlags member can contain the following value.
Value | Description
DF_ALLOWOTHERACCOUNTHOOK | Allows processes running in other accounts on the desktop to set hooks in this process.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Window Stations and Desktops Overview, Window Station and Desktop Structures, CreateDesktop, GetUserObjectInformation, OpenDesktop, OpenInputDesktop, SetUserObjectInformation


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
  • Using Windows
  • Window Reference


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
  • Controls and Dialog Boxes
  • Window Attributes
  • Window Creation
  • Window Types
  • Window Relationships
  • Window Show State
  • Window Animation
  • Window Layout and Mirroring
  • 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 file name. SystemParametersInfo then loads the bitmap from the specified file, uses the bitmap to paint the background of the screen, and enters the new file name 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.

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.

Client Area

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.

Nonclient Area

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 the appearance and behavior of its client area.

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.

The buttons in the upper-right corner affect 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. When you click the restore button, the system restores the window to its previous size and position. When you click 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. When you click the close button, the application exits.

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


Controls and Dialog Boxes

An application can create several types of windows in addition to its main window, including controls and dialog 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 file name. Dialog 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.

A message box is a special dialog box 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. For more information, see Message Boxes.


Window Attributes

An application must provide the following information when creating a window:

  • class name
  • window name
  • window style
  • extended window style
  • position
  • size
  • parent or owner window handle
  • menu handle or child-window identifier
  • application instance handle
  • creation data

After creating a window, the creation function returns the following information that uniquely identifies the window:

  • window handle

These window attributes are described in the following sections.

class name

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, and Messages and Message Queues.

window name

A window name 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. A control may display its window name, depending on the control's class. For example, buttons, edit controls, and static controls displays their window names within the rectangle occupied by the control. However, list boxes, combo boxes, and static controls do not display their window names.

To change the window name after creating a window, use the SetWindowText function . This function uses the GetWindowTextLength and GetWindowText functions to retrieve the current window-name string from the 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. An application usually sets window styles when creating windows. It can also set the styles after creating a window by using the SetWindowLong function.

The system and, to some extent, the window procedure for the class, interpret the window styles.

Some window styles apply to all windows, but most apply to windows of specific window classes. The general window 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. For example, the SCROLLBAR class specifies a scroll bar control, but the SBS_HORZ and SBS_VERT styles determine whether a horizontal or vertical scroll bar control is created.

For lists of styles that can be used by windows, see the following topics:

  • Window Styles
  • Button Styles
  • Combo Box Styles
  • Edit Control Styles
  • List Box Styles
  • Rich Edit Control Styles
  • Scroll Bar Control Styles
  • Static Control Styles

extended window style

Every window can optionally have one or more extended window styles. An extended window style is a named constant that defines an aspect of the window's appearance and behavior that is not specified by the window class or the other window styles. An application usually sets extended window styles when creating windows. It can also set the styles after creating a window by using the SetWindowLong function.

For more information, see CreateWindowEx.

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.

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.

parent or owner window handle

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. For more information, see Owned Windows.

menu handle or child-window identifier

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.

application instance handle

Every 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 handle

After creating a window, the creation function returns a window handle that uniquely identifies 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. An application uses this handle in other functions to direct their actions to the 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. 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.


Window Creation

To create application windows, use the CreateWindow or CreateWindowEx function. You must provide the information required to define the window attributes. CreateWindowEx has a parameter, dwExStyle, that CreateWindow does not have; otherwise, the functions are identical. In fact, CreateWindow simply calls CreateWindowEx with the dwExStyle parameter set to zero. For this reason, the remainder of this overview refers only to CreateWindowEx.

This section contains the following topics:

  • Main Window Creation
  • Window-Creation Messages
  • Multithread Applications

Note There are additional functions for creating special-purpose windows such as dialog boxes and message boxes. For more information, see DialogBox, CreateDialog, and MessageBox.


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.

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.


Window Types

This section contains the following topics:

  • Overlapped Windows
  • Pop-up Windows
  • Child Windows
  • Layered Windows
  • Message-Only Windows


Overlapped Windows

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 Windows

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 Windows

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. If no border style is specified, the system creates a borderless window. An application can use borderless child windows to divide a parent window's client area while keeping the divisions invisible to the user.

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.


Layered Windows

Using a layered window can significantly improve performance and visual effects for a window that has a complex shape, animates its shape, or wishes to use alpha blending effects. The system automatically composes and repaints layered windows and the windows of underlying applications. As a result, layered windows are rendered smoothly, without the flickering typical of complex window regions. In addition, layered windows can be partially translucent, that is, alpha-blended.

To create a layered window, specify the WS_EX_LAYERED extended window style when calling the CreateWindowEx function, or call the SetWindowLong function to set WS_EX_LAYERED after the window has been created. After the CreateWindowEx call, the layered window will not become visible until the SetLayeredWindowAttributes or UpdateLayeredWindow function has been called for this window. Note that WS_EX_LAYERED cannot be used for child windows.

To set the opacity level or the transparency color key for a given layered window, call SetLayeredWindowAttributes. After the call, the system may still ask the window to paint when the window is shown or resized. However, because the system stores the image of a layered window, the system will not ask the window to paint if parts of it are revealed as a result of relative window moves on the desktop. Legacy applications do not need to restructure their painting code if they want to add translucency or transparency effects for a window, because the system redirects the painting of windows that called SetLayeredWindowAttributes into off-screen memory and recomposes it to achieve the desired effect.

For faster and more efficient animation or if per-pixel alpha is needed, call UpdateLayeredWindow. UpdateLayeredWindow should be used primarily when the application must directly supply the shape and content of a layered window, without using the redirection mechanism the system provides through SetLayeredWindowAttributes. In addition, using UpdateLayeredWindow directly uses memory more efficiently, because the system does not need the additional memory required for storing the image of the redirected window. For maximum efficiency in animating windows, call UpdateLayeredWindow to change the position and the size of a layered window. Please note that after SetLayeredWindowattributes has been called, subsequent UpdateLayeredWindow calls will fail until the layering style bit is cleared and set again.

Hit testing of a layered window is based on the shape and transparency of the window. This means that the areas of the window that are color-keyed or whose alpha value is zero will let the mouse messages through. However, if the layered window has the WS_EX_TRANSPARENT extended window style, the shape of the layered window will be ignored and the mouse events will be passed to other windows underneath the layered window.


Message-Only Windows

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 Relationships

There are many ways that a window can relate to the user or another window. A window may be an owned window, foreground window, or background window. A window also has a Z order relative to other windows. For more information, see the following topics:

  • background windows
  • foreground windows
  • owned windows
  • Z order


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. To retrieve a handle to the foreground window, use the GetForegroundWindow function. To check if your application window is the foreground window, compare the handle returned by GetForegroundWindow to that of your application window.

An application sets the foreground window by using the SetForegroundWindow function.

Windows NT 4.0 and earlier, Windows 95: If the new foreground window is a top-level window, the system activates it; otherwise, it activates the associated top-level window.

Windows 98/Me, Windows 2000 or later: The system restricts which processes can set the foreground window. A process can set the foreground window only if one of the following conditions is true:

  • The process is the foreground process.
  • The process was started by the foreground process.
  • The process received the last input event.
  • There is no foreground process.
  • The foreground process is being debugged.
  • The foreground is not locked (see LockSetForegroundWindow).
  • The foreground lock time-out has expired (see SPI_GETFOREGROUNDLOCKTIMEOUT in SystemParametersInfo).
  • Windows 2000 or later: No menus are active.

Windows 2000 or later: A process that can set the foreground window can enable another process to set the foreground window by calling the AllowSetForegroundWindow function, or by calling the BroadcastSystemMessage function with the BSF_ALLOWSFW flag. The foreground process can disable calls to SetForegroundWindow by calling the LockSetForegroundWindow function.


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.


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 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 show state. The following topics discuss the window show state:

  • Active Window
  • Disabled Windows
  • 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.


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.


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 or SetWindowLong 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:

  • Default Size and Position
  • Tracking Size
  • System Commands
  • Size and Position Functions
  • Size and Position Messages


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

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, slide, or fade 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.

When you specify the AW_BLEND flag, the system uses an alpha-blended fade.

You can also use the AW_CENTER flag to make a window appear to collapse inward or expand outward.


Window Layout and Mirroring

The window layout defines how text and GDI objects are laid out in a window. Some languages, such as English, French, and German, require a left-to-right (LTR) layout. Other languages, such as Arabic and Hebrew, require right-to-left (RTL) layout. The window layout applies to text but also affects the other GDI elements of the window, including bitmaps, icons, the location of the origin, buttons, cascading tree controls, and whether the horizontal coordinate increases as you go left or right. For example, after an application has set RTL layout, the origin is positioned at the right edge of the window or device, and the number representing the horizontal coordinate increases as you move left. However, not all objects are affected by the layout of a window. For example, the layout for dialog boxes, message boxes, and device contexts that are not associated with a window, such as metafile and printer DCs, must be handled separately. Specifics for these are mentioned later in this topic.

The window functions allow you to specify or change the window layout in Arabic and Hebrew versions of Windows 98, and Windows Me and in all versions of Windows 2000. Note that changing to a RTL layout (also known as mirroring) is not supported for windows that have the style CS_OWNDC or for a DC with the GM_ADVANCED graphic mode.

By default, the window layout is left-to-right (LTR). To set the RTL window layout, call CreateWindowEx with the style WS_EX_LAYOUTRTL. Also by default, a child window (that is, one created with the WS_CHILD style and with a valid parent hWnd parameter in the call to CreateWindow or CreateWindowEx) has the same layout as its parent. To disable inheritance of mirroring to all child windows, specify WS_EX_NOINHERITLAYOUT in the call to CreateWindowEx. Note, mirroring is not inherited by owned windows (those created without the WS_CHILD style) or those created with the parent hWnd parameter in CreateWindowEx set to NULL. To disable inheritance of mirroring for an individual window, process the WM_NCCREATE message with GetWindowLong and SetWindowLong to turn off the WS_EX_LAYOUTRTL flag. This processing is in addition to whatever other processing is needed. The following code fragment shows how this is done.

SetWindowLong (hWnd, GWL_EXSTYLE, GetWindowLong(hWnd,GWL_EXSTYLE) & ~WS_EX_LAYOUTRTL))

You can set the default layout to RTL by calling SetProcessDefaultLayout (LAYOUT_RTL). All windows created after the call will be mirrored, but existing windows are not affected. To turn off default mirroring, call SetProcessDefaultLayout(0).

Note, SetProcessDefaultLayout mirrors the device contexts only of mirrored windows. To mirror any DC, call SetLayout(hdc, LAYOUT_RTL). For more information, see the discussion on mirroring device contexts not associated with windows, which comes later in this topic.

Bitmaps and icons in a mirrored window are also mirrored by default. However, not all of these should be mirrored. For example, those with text, a business logo, or an analog clock should not be mirrored. To disable mirroring of bitmaps, call SetLayout with the LAYOUT_BITMAPORIENTATIONPRESERVED bit set in dwLayout. To disable mirroring in a DC, call SetLayout(hdc, 0).

To query the current default layout, call GetProcessDefaultLayout. Upon a successful return, pdwDefaultLayout contains LAYOUT_RTL or 0. To query the layout settings of the device context, call GetLayout. Upon a successful return, GetLayout returns a DWORD that indicates the layout settings by the settings of the LAYOUT_RTL and the LAYOUT_BITMAPORIENTATIONPRESERVED bits.

After a window has been created, you change the layout using the SetWindowLong function. For example, this is necessary when the user changes the user interface language of an existing window from Arabic or Hebrew to German. However, when changing the layout of an existing window, you must invalidate and update the window to ensure that the contents of the window are all drawn on the same layout. The following snippet is from sample code that changes the window layout as needed:

// Using ANSI versions of GetWindowLong and SetWindowLong because
// Unicode is not needed for these calls
lExStyles = GetWindowLongA(hWnd, GWL_EXSTYLE);
// Check whether new layout is opposite the current layout
if (!!(pLState -> IsRTLLayout) != !!(lExStyles & WS_EX_LAYOUTRTL))
{
    // the following lines will update the window layout
    lExStyles ^= WS_EX_LAYOUTRTL;       // toggle layout
    SetWindowLongA(hWnd, GWL_EXSTYLE, lExStyles);
    InvalidateRect(hWnd, NULL, TRUE);   // to update layout in the
                                        // client area
}

In mirroring, you should think in terms of "near" and "far" instead of "left" and "right". Failure to do so can cause problems. One common coding practice that causes problems in a mirrored window occurs when mapping between screen coordinates and client coordinates. For example, applications often use code similar to the following to position a control in a window:

// DO NOT USE THIS IF APPLICATION MIRRORS THE WINDOW
GetWindowRect(hControl, (LPRECT) &rControlRect);  // gets coordinates
                                // of the window in screen coordinates
ScreenToClient(hDialog, (LPPOINT) &rControlRect.left); // maps screen
                        // coordinates to client coordinates in dialog
ScreenToClient(hDialog, (LPPOINT) &rControlRect.right);

This causes problems in mirroring because the left edge of the rectangle becomes the right edge in a mirrored window, and vice versa. To avoid this problem, replace the ScreenToClient calls with a call to MapWindowPoints as follows:

// USE THIS FOR MIRRORING
GetWindowRect(hControl, (LPRECT) &rControlRect);
MapWindowPoints(NULL, hDialog, (LPPOINT) &rControlRect, 2)

This code works because, on platforms that support mirroring, MapWindowPoints is modified to swap the left and right point coordinates when the client window is mirrored. For more information, see the Remarks section of MapWindowPoints.

Another common practice that can cause problems in mirrored windows is positioning objects in a client window using offsets in screen coordinates instead of client coordinates. For example, the following code uses the difference in screen coordinates as the x position in client coordinates to position a control in a dialog box.

// OK if LTR layout and mapping mode of client is MM_TEXT,
// but WRONG for a mirrored dialog
RECT rdDialog;
RECT rcControl;

HWND hControl = GetDlgItem(hDlg, IDD_CONTROL);
GetWindowRect(hDlg, &rcDialog);  // gets rect in screen coordinates
GetWindowRect(hControl, &rcControl);
MoveWindow(
    hControl,
    rcControl.left - rcDialog.left, //uses x position in client coords
    rcControl.top - rcDialog.top,
    nWidth,
    nHeight,
    FALSE);

This code is fine when the dialog window has left-to-right (LTR) layout and the mapping mode of the client is MM_TEXT, because the new x position in client coordinates corresponds to the difference in left edges of the control and the dialog in screen coordinates. However, in a mirrored dialog, left and right are reversed, so instead you should use MapWindowPoints as follows:

RECT rcDialog;
RECT rcControl;

HWND hControl - GetDlgItem(hDlg, IDD_CONTROL);
GetWindowRect(hControl, &rcControl);
  // MapWindowPoints works correctly in both mirrored and non-mirrored
  // windows.
MapWindowPoints(NULL, hDlg, (LPPOINT) &rcControl, 2);
  // Now rcControl is in client coordinates.
MoveWindow(hControl, rcControl.left, rcControl.top, nWidth, nHeight, FALSE)

Mirroring Dialog Boxes and Message Boxes

Dialog boxes and message boxes do not inherit layout, so you must set the layout explicitly. To mirror a message box, call MessageBox or MessageBoxEx with the MB_RTLREADING option. To layout a dialog box right-to-left, use the extended style WS_EX_LAYOUTRTL in the dialog template structure DLGTEMPLATEEX. Property sheets are a special case of dialog boxes. Each tab is treated as a separate dialog box, so you need to include the WS_EX_LAYOUTRTL style in every tab that you want mirrored.

Mirroring Device Contexts Not Associated with a Window

Device contexts (DCs) that are not associated with a window, such as metafile or printer DCs, do not inherit layout, so you must set the layout explicitly. To change the device context layout, use the SetLayout function.

The SetLayout function is rarely used with windows. Typically, windows receive an associated DC only in processing a WM_PAINT message. Occasionally, a program creates a DC for a window by calling GetDC. Either way, the initial layout for the DC is set by BeginPaint or GetDC according to the window's WS_EX_LAYOUTRTL flag.

The values returned by GetWindowOrgEx, GetWindowExtEx, GetViewportOrgEx and GetViewportExtEx are not affected by calling SetLayout.

When the layout is RTL, GetMapMode will return MM_ISOTROPIC instead of MM_TEXT. Calling SetMapMode with MM_TEXT will function correctly; only the return value from GetMapMode is affected. Similarly, calling SetLayout(hdc, LAYOUT_RTL) when the mapping mode is MM_TEXT causes the reported mapping mode to change to MM_ISOTROPIC.


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
  • Using layered windows


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;


Using layered windows

To have a dialog box come up as a translucent window, first create the dialog as usual. Then, on WM_INITDIALOG, set the layered bit of the window's extended style and call SetLayeredWindowAttributes with the desired alpha value. The code might look like this:

// Set WS_EX_LAYERED on this window
SetWindowLong(hwnd, GWL_EXSTYLE,
        GetWindowLong(hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
// Make this window 70% alpha
SetLayeredWindowAttributes(hwnd, 0, (255 * 70) / 100, LWA_ALPHA);

Note that the third parameter of SetLayeredWindowAttributes is a value that ranges from 0 to 255, with 0 making the window completely transparent and 255 making it completely opaque. This parameter mimics the more versatile BLENDFUNCTION of the AlphaBlend function.

To make this window completely opaque again, remove the WS_EX_LAYERED bit by calling SetWindowLong and then ask the window to repaint. Removing the bit is desired to let the system know that it can free up some memory associated with layering and redirection. The code might look like this:

// Remove WS_EX_LAYERED from this window styles
SetWindowLong(hwnd, GWL_EXSTYLE,
        GetWindowLong(hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED);
// Ask the window and its children to repaint
RedrawWindow(hwnd, NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME |
        RDW_ALLCHILDREN);


Window Reference

The following elements are associated with windows.

  • Window Functions
  • Window Structures
  • Window Messages
  • Window Styles


Window Functions

The following functions are used to create and manage windows.

Function | Description
AdjustWindowRect | Calculates the required size of the window rectangle, based on the desired client-rectangle size.
AdjustWindowRectEx | Calculates the required size of the window rectangle, based on the desired client-rectangle size.
AllowSetForegroundWindow | Enables a process to set the foreground window using the SetForegroundWindow function.
AnimateWindow | Enables you to produce special effects when showing or hiding windows.
ArrangeIconicWindows | Arranges all minimized (iconic) child windows of the specified parent window.
BeginDeferWindowPos | Allocates memory for a multiple-window- position structure and returns the handle to the structure.
BringWindowToTop | Brings the specified window to the top of the Z order.
CascadeWindows | Cascades the specified child windows of the specified parent window.
ChildWindowFromPoint | Determines which, if any, of the child windows belonging to a parent window contains the specified point.
ChildWindowFromPointEx | Determines which, if any, of the child windows belonging to a parent window contains the specified point.
CloseWindow | Minimizes (but does not destroy) the specified window.
CreateWindow | Creates an overlapped, pop-up, or child window.
CreateWindowEx | Creates an overlapped, pop-up, or child window with an extended window style.
DeferWindowPos | Updates the specified multiple-window – position structure for the specified window.
DestroyWindow | Destroys the specified window.
EndDeferWindowPos | Updates the position and size of one or more windows.
EnumChildProc | An application-defined callback function used with EnumChildWindows.
EnumChildWindows | Enumerates the child windows that belong to the specified parent window
EnumThreadWindows | Enumerates all nonchild windows associated with a thread.
EnumThreadWndProc | An application-defined callback function used with EnumThreadWindows.
EnumWindows | Enumerates all top-level windows on the screen.
EnumWindowsProc | An application-defined callback function used with EnumWindows or EnumDesktopWindows.
FindWindow | Retrieves a handle to the top-level window whose class name and window name match the specified strings.
FindWindowEx | Retrieves a handle to the top-level window whose class name and window name match the specified strings.
GetAltTabInfo | Retrieves status information for the application-switching (ALT+TAB) window.
GetAncestor | Retrieves the handle to the ancestor of the specified window.
GetClientRect | Retrieves the coordinates of a window's client area.
GetDesktopWindow | Returns a handle to the desktop window.
GetForegroundWindow | Returns a handle to the foreground window.
GetGUIThreadInfo | Retrieves information about the active window or a GUI thread.
GetLastActivePopup | Determines which pop-up window was most recently active.
GetLayeredWindowAttributes | Retrieves the opacity and transparency color key of a layered window.
GetLayout | Returns the layout of a device context.
GetNextWindow | Retrieves a handle to the next or previous window in Z order.
GetParent | Retrieves a handle to the specified child window's parent window.
GetProcessDefaultLayout | Gets the default layout used for windows with no parent or owner.
GetTitleBarInfo | Retrieves information about the specified title bar.
GetTopWindow | Retrieves a handle to the child window at the top of the Z order.
GetWindow | Retrieves a handle to a window that has the specified relationship to the specified window.
GetWindowInfo | Retrieves information about the specified window.
GetWindowModuleFileName | Retrieves the full path and file name of the module associated with the specified window handle.
GetWindowPlacement | Retrieves the show state and the restored, minimized, and maximized positions of the specified window.
GetWindowRect | Retrieves the dimensions of the bounding rectangle of the specified window.
GetWindowText | Copies the text of the specified window's title bar.
GetWindowTextLength | Retrieves the length of the specified window's title bar text.
GetWindowThreadProcessId | Retrieves the identifier of the thread that created the specified window.
IsChild | Tests whether a window is a child window or descendant window of a specified parent window.
IsGUIThread | Tests whether the calling thread is already a GUI thread and can convert the thread.
IsIconic | Determines whether the specified window is minimized (iconic).
IsWindow | Determines whether the specified window handle identifies an existing window.
IsWindowUnicode | Determines whether the specified window is a Unicode window.
IsWindowVisible | Retrieves the visibility state of the specified window.
IsZoomed | Determines whether a window is maximized (zoomed).
LockSetForegroundWindow | Disables calls to SetForegroundWindow.
MoveWindow | Changes the position and dimensions of the specified window.
OpenIcon | Restores a minimized (iconic) window to its previous size and position.
RealChildWindowFromPoint | Retrieves a handle to the child window at the specified point.
RealGetWindowClass | Retrieves the window type.
SetForegroundWindow | Puts the thread that created the specified window into the foreground and activates the window.
SetLayeredWindowAttributes | Sets the opacity and transparency color key of a layered window.
SetLayout | Changes the layout of a device context.
SetParent | Changes the parent window of the specified child window.
SetProcessDefaultLayout | Sets the default layout used for windows with no parent or owner.
SetWindowPlacement | Sets the show state and the restored, minimized, and maximized positions of the specified window.
SetWindowPos | Changes the size, position, and Z order of a window.
SetWindowText | Changes the text of the specified window's title bar.
ShowOwnedPopups | Shows or hides all pop-up windows owned by the specified window.
ShowWindow | Sets the specified window's show state.
ShowWindowAsync | Sets the show state of a window created by a different thread.
TileWindows | Tiles the specified child windows of the specified parent window.
UpdateLayeredWindow | Updates the position, size, shape, content, and translucency of a layered window.
WindowFromPoint | Retrieves a handle to the window that contains the specified point.
WinMain | An entry-point function called by the system as the initial entry point for a Win32-based application.

Obsolete Functions

This function is provided only for compatibility with 16-bit versions of Windows.

AnyPopup


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.

To specify an extended window style, use the AdjustWindowRectEx function.

BOOL AdjustWindowRect(
  LPRECT lpRect,  // client-rectangle structure
  DWORD dwStyle,  // window styles
  BOOL bMenu      // menu-present option
);

Parameters

lpRect
[in/out] 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
[in] Specifies the window style of the window whose required size is to be calculated. Note that you cannot specify the WS_OVERLAPPED style.
bMenu
[in] 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.

The AdjustWindowRect function does not take the WS_VSCROLL or WS_HSCROLL styles into account. To account for the scroll bars, call the GetSystemMetrics function with SM_CXVSCROLL or SM_CYHSCROLL.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, AdjustWindowRectEx, CreateWindow, GetSystemMetrics, 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,    // client-rectangle structure
  DWORD dwStyle,    // window styles
  BOOL bMenu,       // menu-present option
  DWORD dwExStyle   // extended window style
);

Parameters

lpRect
[in/out] 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
[in] Specifies the window style of the window whose required size is to be calculated. Note that you cannot specify the WS_OVERLAPPED style.
bMenu
[in] Specifies whether the window has a menu.
dwExStyle
[in] Specifies the extended window style of the window whose required size is to be calculated. For more information, see CreateWindowEx.

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.

The AdjustWindowRectEx function does not take the WS_VSCROLL or WS_HSCROLL styles into account. To account for the scroll bars, call the GetSystemMetrics function with SM_CXVSCROLL or SM_CYHSCROLL.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, CreateWindowEx, RECT


AllowSetForegroundWindow

The AllowSetForegroundWindow function enables the specified process to set the foreground window using the SetForegroundWindow function. The calling process must already be able to set the foreground window. For more information, see Remarks later in this topic.

BOOL AllowSetForegroundWindow(
  DWORD dwProcessId   // process identifier
);

Parameters

dwProcessId
[in] Specifies the identifier of the process that will be enabled to set the foreground window. If this parameter is ASFW_ANY, all processes will be enabled to set the foreground window.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. The function will fail if the calling process cannot set the foreground window. To get extended error information, call GetLastError.

Remarks

Starting with Windows 98 and Windows 2000, the system restricts which processes can set the foreground window. A process can set the foreground window only if one of the following conditions is true:

  • The process is the foreground process.
  • The process was started by the foreground process.
  • The process received the last input event.
  • There is no foreground process.
  • The foreground process is being debugged.
  • The foreground is not locked (see LockSetForegroundWindow).
  • The foreground lock time-out has expired (see SPI_GETFOREGROUNDLOCKTIMEOUT in SystemParametersInfo).
  • Windows 2000 or later: No menus are active.

A process that can set the foreground window can enable another process to set the foreground window by calling AllowSetForegroundWindow. The process specified by dwProcessId loses the ability to set the foreground window the next time the user generates input, unless the input is directed at that process, or the next time a process calls AllowSetForegroundWindow, unless that process is specified.

Windows 98/Me: This function is not implemented on Windows 98. Therefore, processes must cooperate to manage the foreground window. For example, an application may wish to support only one instance. When the second instance starts up, it should detect the previous instance and call SetForegroundWindow on the window of the previous instance. It should not post a message to the window of the previous instance asking it to call SetForegroundWindow on itself, because the previous instance will not necessarily have permission to call SetForegroundWindow.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows Me.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, LockSetForegroundWindow, SetForegroundWindow


AnimateWindow

The AnimateWindow function enables you to produce special effects when showing or hiding windows. There are three types of animation: roll, slide, and alpha-blended fade.

BOOL AnimateWindow(
  HWND hwnd,     // handle to window
  DWORD dwTime,  // duration of animation
  DWORD dwFlags  // animation type
);

Parameters

hwnd
[in] Handle to the window to animate. The calling thread must own this window.
dwTime
[in] Specifies how long it takes to play the animation, in milliseconds. Typically, an animation takes 200 milliseconds to play.
dwFlags
[in] Specifies the type of animation. This parameter can be one or more of the following values.
Value | Description
AW_SLIDE | Uses slide animation. By default, roll animation is used. This flag is ignored when used with AW_CENTER.
AW_ACTIVATE | Activates the window. Do not use this value 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 AW_HIDE is used or expand outward if the AW_HIDE is not used.
AW_HOR_POSITIVE | Animates the window from left to right. This flag can be used with roll or slide animation. It is ignored when used with AW_CENTER or AW_BLEND.
AW_HOR_NEGATIVE | Animates the window from right to left. This flag can be used with roll or slide animation. It is ignored when used with AW_CENTER or AW_BLEND.
AW_VER_POSITIVE | Animates the window from top to bottom. This flag can be used with roll or slide animation. It is ignored when used with AW_CENTER or AW_BLEND.
AW_VER_NEGATIVE | Animates the window from bottom to top. This flag can be used with roll or slide animation. It is ignored when used with AW_CENTER or AW_BLEND.

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 AW_HOR_POSITIVE or AW_HOR_NEGATIVE with AW_VER_POSITIVE or AW_VER_NEGATIVE 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.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
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.

Note This function is provided only for compatibility with 16-bit versions of 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, SetWindowPos


CascadeWindows

The CascadeWindows function cascades the specified child windows of the specified parent window.

WORD 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 *lpKids   // array of window handles
);

Parameters

hwndParent
[in] Handle to the parent window. If this parameter is NULL, the desktop window is assumed.
wHow
[in] Specifies a cascade flag. This parameter can be one or more of the following values.
Value | Meaning
MDITILE_SKIPDISABLED | Prevents disabled MDI child windows from being cascaded.
MDITILE_ZORDER Windows 2000 or later: Arranges the windows in Z order.

If this value is not specified, the windows are arranged using the order specified in the lpKids array.

lpRect
[in] 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
[in] Specifies the number of elements in the array specified by the lpKids parameter. This parameter is ignored if lpKids is NULL.
lpKids
[in] 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

By default, CascadeWindows arranges the windows in the order provided by the lpKids array, but preserves the Z order. If you specify the MDITILE_ZORDER flag, CascadeWindows arranges the windows in Z order.

Calling CascadeWindows causes all maximized windows to be restored to their previous size.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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.

To skip certain child windows, use the ChildWindowFromPointEx function.

HWND ChildWindowFromPoint(
  HWND hWndParent,  // handle to parent window
  POINT Point       // structure with point coordinates
);

Parameters

hWndParent
[in] Handle to the parent window.
Point
[in] 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.

For an example, see Creating a Combo-box Toolbar.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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        // skip options
);

Parameters

hwndParent
[in] Handle to the parent window.
pt
[in] Specifies a POINT structure that defines the client coordinates of the point to be checked.
uFlags
[in] Specifies which child windows to skip. This parameter can be one or more of the following values.
Value | Meaning
CWP_ALL | Does not skip any child windows
CWP_SKIPINVISIBLE | Skips invisible child windows
CWP_SKIPDISABLED | Skips disabled child windows
CWP_SKIPTRANSPARENT | Skips 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, 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
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 window styles in addition to the styles supported by CreateWindow, use the CreateWindowEx function.

HWND CreateWindow(
  LPCTSTR lpClassName,  // registered class name
  LPCTSTR lpWindowName, // 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,          // menu handle or child identifier
  HINSTANCE hInstance,  // handle to application instance
  LPVOID lpParam        // window-creation data
);

Parameters

lpClassName
[in] Pointer to a null-terminated string or a class atom created by a previous call to the RegisterClass or RegisterClassEx function. The atom 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 RegisterClass or RegisterClassEx, provided that the module that registers the class is also the module that creates the window. The class name can also be any of the predefined system class names. For a list of system class names, see the Remarks section.

lpWindowName
[in] 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. When creating a static control with the SS_ICON style, use lpWindowName to specify the icon name or identifier. To specify an identifier, use the syntax "#num".

dwStyle
[in] Specifies the style of the window being created. This parameter can be a combination of window styles, plus the control styles indicated in the Remarks section.
x
[in] 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
[in] 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
[in] 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
[in] 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
[in] 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 2000 or later: To create a message-only window, supply HWND_MESSAGE or a handle to an existing message-only window.

hMenu
[in] 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
Windows 95/98/Me: [in] Handle to the instance of the module to be associated with the window.

Windows NT/2000 or later: This value is ignored.

lpParam
[in] 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.

This function typically fails for one of the following reasons:

  • an invalid parameter value
  • the system class was registered by a different module
  • the WH_CBT hook is installed and returns a failure code
  • the window procedure fails for WM_CREATE or WM_NCCREATE

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 system classes can be specified in the lpClassName parameter. Note the corresponding control styles you can use in the dwStyle parameter.

System 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 file names, 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.

For an example, see Using Window Classes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Windows Overview, Window Functions, CreateWindowEx, EnableWindow, RegisterClass, RegisterClassEx, ShowWindow, 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 window 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,  // registered class name
  LPCTSTR lpWindowName, // 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,          // menu handle or child identifier
  HINSTANCE hInstance,  // handle to application instance
  LPVOID lpParam        // window-creation data
);

Parameters

dwExStyle
[in] Specifies the extended window style of the window being created. This parameter can be one or more 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_COMPOSITED | Whistler: Paints all descendants of a window in bottom-to-top painting order using double-buffering. For more information, see Remarks. This cannot be used if the window has a class style of either CS_OWNDC or CS_CLASSDC.
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 | The window itself contains child windows that should take part in dialog box navigation. If this style is specified, the dialog manager recurses into children of this window when performing navigation operations such as handling the TAB key, an arrow key, or a keyboard mnemonic.
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_LAYERED | Windows 2000 or later: Creates a layered window. Note that this cannot be used for child windows. Also, this cannot be used if the window has a class style of either CS_OWNDC or CS_CLASSDC.
WS_EX_LAYOUTRTL | Windows 2000 and the Arabic and Hebrew versions of Windows 98 and Windows Me: Creates a window whose horizontal origin is on the right edge. Increasing horizontal values advance to the left.
WS_EX_LEFT | Creates a window that 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.
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_NOACTIVATE Windows 2000 or later: A top-level window created with this style does not become the foreground window when the user clicks it. The system does not bring this window to the foreground when the user minimizes or closes the foreground window.

To activate the window, use the SetActiveWindow or SetForegroundWindow function.

The window does not appear on the taskbar by default. To force the window to appear on the taskbar, use the WS_EX_APPWINDOW style.
WS_EX_NOINHERITLAYOUT | Windows 2000 or later: A window created with this style does not pass its window layout to its child windows.
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.
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.
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
[in] Pointer to a null-terminated string or a class atom created by a previous call to the RegisterClass or RegisterClassEx function. The atom 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 RegisterClass or RegisterClassEx, provided that the module that registers the class is also the module that creates the window. The class name can also be any of the predefined system class names.

lpWindowName
[in] 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. When creating a static control with the SS_ICON style, use lpWindowName to specify the icon name or identifier. To specify an identifier, use the syntax "#num".

dwStyle
[in] Specifies the style of the window being created. This parameter can be a combination of window styles, plus the control styles indicated in the Remarks section.
x
[in] 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
[in] 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
[in] 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
[in] 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
[in] 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 2000 or later: To create a message-only window, supply HWND_MESSAGE or a handle to an existing message-only window.

hMenu
[in] 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
Windows 95/98/Me: [in] Handle to the instance of the module to be associated with the window.

Windows NT/2000 or later: This value is ignored.

lpParam
[in] 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.

This function typically fails for one of the following reasons:

  • an invalid parameter value
  • the system class was registered by a different module
  • the WH_CBT hook is installed and returns a failure code
  • the window procedure fails for WM_CREATE or WM_NCCREATE

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 2000 or later: The WS_EX_NOACTIVATE value for dwExStyle prevents foreground activation by the system. To prevent queue activation when the user clicks on the window, you must process the WM_MOUSEACTIVATE message appropriately. To bring the window to the foreground or to activate it programmatically, use SetForegroundWindow or SetActiveWindow. Returning FALSE to WM_NCACTIVATE prevents the window from losing queue activation. However, the return value is ignored at activation time.

Whistler: With WS_EX_COMPOSITED set, all descendants of a window get bottom-to-top painting order using double-buffering. Bottom-to-top painting order allows a descendent window to have translucency (alpha) and transparency (color-key) effects, but only if the descendent window also has the WS_EX_TRANSPARENT bit set. Double-buffering allows the window and its descendents to be painted without flicker.

For an example, see Creating a Main Window.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Windows Overview, Window Functions, CLIENTCREATESTRUCT, CREATESTRUCT, CreateWindow, EnableWindow, RegisterClass, RegisterClassEx, SetActiveWindow , SetForegroundWindow , SetWindowLong, SetWindowPos, ShowWindow, 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 options
);

Parameters

hWinPosInfo
[in] 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
[in] Handle to the window for which update information is stored in the structure. All windows in a multiple-window – position structure must have the same parent.
hWndInsertAfter
[in] 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
[in] Specifies the x-coordinate of the window's upper-left corner.
y
[in] Specifies the y-coordinate of the window's upper-left corner.
cx
[in] Specifies the window's new width, in pixels.
cy
[in] Specifies the window's new height, in pixels.
uFlags
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
[in] 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.

For an example, see Destroying a Window.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
[in] Handle to a child window of the parent window specified in EnumChildWindows.
lParam
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

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,  // callback function
  LPARAM lParam            // application-defined value
);

Parameters

hWndParent
[in] Handle to the parent window whose child windows are to be enumerated. If this parameter is NULL, this function is equivalent to EnumWindows.

Windows 95/98/Me: hWndParent cannot be NULL.

lpEnumFunc
[in] Pointer to an application-defined callback function. For more information, see EnumChildProc.
lParam
[in] 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.

For an example, see Creating, Enumerating, and Sizing Child Windows.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, EnumChildProc, EnumThreadWindows, EnumWindows, GetWindow


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,  // callback function
  LPARAM lParam      // application-defined value
);

Parameters

dwThreadId
[in] Identifies the thread whose windows are to be enumerated.
lpfn
[in] Pointer to an application-defined callback function. For more information, see EnumThreadWndProc.
lParam
[in] 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.

For an example, see Handling Logoff Events.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
[in] Handle to a window associated with the thread specified in the EnumThreadWindows function.
lParam
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

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,  // callback function
  LPARAM lParam            // application-defined value
);

Parameters

lpEnumFunc
[in] Pointer to an application-defined callback function. For more information, see EnumWindowsProc.
lParam
[in] 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.

If EnumWindowsProc returns zero, the return value is also zero.

Remarks

The EnumWindows function does not enumerate child windows, with the exception of a few top-level windows owned by the system that have the WS_CHILD style.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
[in] Handle to a top-level window.
lParam
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

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.

To search child windows, beginning with a specified child window, use the FindWindowEx function.

HWND FindWindow(
  LPCTSTR lpClassName,  // class name
  LPCTSTR lpWindowName  // window name
);

Parameters

lpClassName
[in] Pointer to a null-terminated string that specifies the class name or a class atom created by a previous call to the RegisterClass or RegisterClassEx function. The atom 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 RegisterClass or RegisterClassEx, or any of the predefined control-class names.

lpWindowName
[in] 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

If the lpWindowName parameter is not NULL, FindWindow calls the GetWindowText function to retrieve the window name for comparison. For a description of a potential problem that can arise, see the Remarks for GetWindowText.

For an example, see Retrieving the Number of Mouse Wheel Scroll Lines.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Windows Overview, Window Functions, EnumWindows, FindWindowEx, GetClassName, GetWindowText, RegisterClass, RegisterClassEx


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 specified child window. This function does not perform a case-sensitive search.

HWND FindWindowEx(
  HWND hwndParent,      // handle to parent window
  HWND hwndChildAfter,  // handle to child window
  LPCTSTR lpszClass,    // class name
  LPCTSTR lpszWindow    // window name
);

Parameters

hwndParent
[in] 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 2000 or later: If hwndParent is HWND_MESSAGE, the function searches all message-only windows.

hwndChildAfter
[in] 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
[in] Pointer to a null-terminated string that specifies the class name or a class atom created by a previous call to the RegisterClass or RegisterClassEx function. The atom must be placed in the low-order word of lpszClass; the high-order word must be zero.

If lpszClass is a string, it specifies the window class name. The class name can be any name registered with RegisterClass or RegisterClassEx, or any of the predefined control-class names.

lpszWindow
[in] 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.

Remarks

If the lpWindowName parameter is not NULL, FindWindowEx calls the GetWindowText function to retrieve the window name for comparison. For a description of a potential problem that can arise, see the Remarks for GetWindowText.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Windows Overview, Window Functions, EnumWindows, FindWindow, GetClassName, GetWindowText, RegisterClass, RegisterClassEx


GetAltTabInfo

The GetAltTabInfo function retrieves status information for the specified window if it is the application-switching (ALT+TAB) window.

BOOL GetAltTabInfo(
  HWND hwnd,           // handle to window
  int iItem,           // icon index
  PALTTABINFO pati,    // status information
  LPTSTR pszItemText,  // item name buffer
  UINT cchItemText     // size of item name buffer
);

Parameters

hwnd
[in] Handle to the window for which status information will be retrieved. This window must be the application-switching window.
iItem
[in] Specifies the index of the icon in the application-switching window. If the pszItemText parameter is not NULL, the name of the item is copied to the pszItemText string. If this parameter is –1, the name of the item is not copied.
pati
[out] Pointer to an ALTTABINFO structure to receive the status information.
pszItemText
[out] Pointer to a string that receives the name of the item. If this parameter is NULL, the name of the item is not copied.
cchItemText
[in] Specifies the size, in TCHARs, of the pszItemText buffer.

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-switching window enables you to switch to the most recently used application window. To display the application-switching window, press ALT+TAB. To select an application from the list, continue to hold ALT down and press TAB to move through the list. Add SHIFT to reverse direction through the list.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP6 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Windows Overview, Window Functions, ALTTABINFO


GetAncestor

The GetAncestor function retrieves the handle to the ancestor of the specified window.

HWND GetAncestor(
  HWND hwnd,    // handle to window
  UINT gaFlags  // ancestor
);

Parameters

hwnd
[in] Handle to the window whose ancestor is to be retrieved. If this parameter is the desktop window, the function returns NULL.
gaFlags
[in] Specifies the ancestor to be retrieved. This parameter can be one of the following values.
Value | Meaning
GA_PARENT | Retrieves the parent window. This does not include the owner, as it does with the GetParent function.
GA_ROOT | Retrieves the root window by walking the chain of parent windows.
GA_ROOTOWNER | Retrieves the owned root window by walking the chain of parent and owner windows returned by GetParent.

Return Values

The return value is the handle to the ancestor window.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP4 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, GetParent


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   // client coordinates
);

Parameters

hWnd
[in] Handle to the window whose client coordinates are to be retrieved.
lpRect
[out] 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.

For an example, see Creating, Enumerating, and Sizing Child Windows.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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.

For an example, see Initializing a Dialog Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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. The foreground window can be NULL in certain circumstances, such as when a window is losing activation.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, SetForegroundWindow


GetGUIThreadInfo

The GetGUIThreadInfo function retrieves information about the active window or a specified graphical user interface (GUI) thread.

BOOL GetGUIThreadInfo(
  DWORD idThread,       // thread identifier
  LPGUITHREADINFO lpgui  // thread information
);

Parameters

idThread
[in] Identifies the thread for which information is to be retrieved. To retrieve this value, use the GetWindowThreadProcessId function. If this parameter is NULL, the function returns information for the foreground thread.
lpgui
[out] Pointer to a GUITHREADINFO structure that receives information describing the thread.

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

This function succeeds even if the active window is not owned by the calling process. If the specified thread does not exist or have an input queue, the function will fail.

This function is useful for retrieving out-of-context information about a thread. The information retrieved is the same as if an application retrieved the information about itself.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP3 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, GetCursorInfo, GetWindowThreadProcessId, GUITHREADINFO


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
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, AnyPopup, ShowOwnedPopups


GetLayeredWindowAttributes

[This is preliminary documentation and subject to change.]

The GetLayeredWindowAttributes function retrieves the opacity and transparency color key of a layered window.

BOOL GetLayeredWindowAttributes(
  HWND hwnd,           // handle to the layered window
  COLORREF *pcrKey,    // color key
  BYTE *pbAlpha,       // Alpha value
  DWORD *pdwFlags      // layering flags
);

Parameters

hwnd
[in] Handle to the layered window. A layered window is created by specifying WS_EX_LAYERED when creating the window with the CreateWindowEx function or by setting WS_EX_LAYERED via SetWindowLong after the window has been created.
pcrKey
[out] Pointer to a COLORREF value that receives the transparency color key to be used when composing the layered window. All pixels painted by the window in this color will be transparent. This can be NULL if the argument is not needed.
pbAlpha
[out] Pointer to a BYTE that receives the Alpha value used to describe the opacity of the layered window. Similar to the SourceConstantAlpha member of the BLENDFUNCTION structure. When the variable referred to by pbAlpha is 0, the window is completely transparent. When the variable referred to by pbAlpha is 255, the window is opaque. This can be NULL if the argument is not needed.
pdwFlags
[out] Pointer to a DWORD that receives a layering flag. This can be NULL if the argument is not needed. The layering flag can be one or more of the following values.
Value | Meaning
LWA_ALPHA | Use bAlpha to determine the opacity of the layered window.
LWA_COLORKEY | Use crKey as the transparency color.

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

GetLayeredWindowAttributes can be called only if the application has previously called SetLayeredWindowAttributes on the window. The function will fail if the layered window was setup with UpdateLayeredWindow.

For more information, see Layered Windows.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, Layered Windows, CreateWindowEx, SetLayeredWindowAttributes, SetWindowLong, UpdateLayeredWindow, COLORREF, RGB


GetLayout

The GetLayout function returns the layout of a device context (DC).

DWORD GetLayout(
  HDC hdc,      // handle to DC
);

Parameters

hdc
[in] Handle to the device context.

Return Values

If the function succeeds, it returns the layout flags for the current device context.

If the function fails, it returns GDI_ERROR. For extended error information, call GetLastError.

Remarks

The layout specifies how text and graphics are laid out in a window; the default is left to right. The GetLayout function tells you if the default has been changed through a call to SetLayout.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Windows Overview, Window Functions, SetLayout


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
);

Parameters

hWnd
[in] Handle to a window. The window handle retrieved is relative to this window, based on the value of the wCmd parameter.
wCmd
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, GetTopWindow, GetWindow


GetParent

The GetParent function retrieves a handle to the specified window's parent or owner.

To retrieve a handle to a specified ancestor, use the GetAncestor function.

HWND GetParent(
  HWND hWnd   // handle to child window
);

Parameters

hWnd
[in] Handle to the window whose parent window handle is to be retrieved.

Return Values

If the window is a child window, the return value is a handle to the parent window. If the window is a top-level window, the return value is a handle to the owner window. If the window is a top-level unowned window or if the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

Note that, despite its name, this function can return an owner window instead of a parent window. To obtain the parent window and not the owner, use GetAncestor with the GA_PARENT flag.

For an example, see Initializing a Dialog Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, GetAncestor, SetParent


GetProcessDefaultLayout

The GetProcessDefaultLayout function gets the default layout that is used when windows are created with no parent or owner.

BOOL GetProcessDefaultLayout(
  DWORD *pdwDefaultLayout  // default process layout
);

Parameters

pdwDefaultLayout
[out] Pointer to the memory location that receives the current default process layout.

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 layout specifies how text and graphics are laid out in a window; the default is left to right. The GetProcessDefaultLayout function lets you know if the default layout has changed, from using SetProcessDefaultLayout.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, SetProcessDefaultLayout


GetTitleBarInfo

The GetTitleBarInfo function retrieves information about the specified title bar.

BOOL GetTitleBarInfo(
  HWND hwnd,         // handle to title bar
  PTITLEBARINFO pti  // title bar information
);

Parameters

hwnd
[in] Handle to the title bar whose information is to be retrieved.
pti
[out] Pointer to a TITLEBARINFO structure to receive the 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP6 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, TITLEBARINFO


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
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
);

Parameters

hWnd
[in] Handle to a window. The window handle retrieved is relative to this window, based on the value of the uCmd parameter.
uCmd
[in] 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 2000 or 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. For more information, see Owned Windows.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, EnumChildWindows


GetWindowInfo

The GetWindowInfo function retrieves information about the specified window.

BOOL GetWindowInfo(
  HWND hwnd,       // handle to window
  PWINDOWINFO pwi  // window information
);

Parameters

hwnd
[in] Handle to the window whose information is to be retrieved.
pwi
[out] Pointer to a WINDOWINFO structure to receive the information.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP3 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, WINDOWINFO


GetWindowModuleFileName

The GetWindowModuleFileName function retrieves the full path and file name of the module associated with the specified window handle.

UINT GetWindowModuleFileName(
  HWND hwnd,            // handle to window
  LPTSTR lpszFileName,  // file name buffer
  UINT cchFileNameMax   // max size of file name buffer
);

Parameters

hwnd
[in] Handle to the window whose module file name will be retrieved.
lpszFileName
[out] Pointer to a buffer that receives the path and file name.
cchFileNameMax
[in] Specifies the maximum number of TCHARs that can be copied into the lpszFileName buffer.

Return Values

The return value is the total number of TCHARs copied into the buffer.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP3 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Windows Overview, Window Functions


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  // position data
);

Parameters

hWnd
[in] Handle to the window.
lpwndpl
[out] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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   // window coordinates
);

Parameters

hWnd
[in] Handle to the window.
lpRect
[out] 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.

For an example, see Initializing a Dialog Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, GetClientRect, RECT


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
  LPTSTR lpString,  // text buffer
  int nMaxCount     // maximum number of characters to copy
);

Parameters

hWnd
[in] Handle to the window or control containing the text.
lpString
[out] Pointer to the buffer that will receive the text.
nMaxCount
[in] 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. This behavior is by design. It allows applications to call GetWindowText without hanging if the process that owns the target window is hung. However, if the target window is hung and it belongs to the calling application, GetWindowText will hang the calling application.

To retrieve the text of a control in another process, send a WM_GETTEXT message directly instead of calling GetWindowText.

For an example, see Sending a Message.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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
);

Parameters

hWnd
[in] 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.

For an example, see Sending a Message.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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  // process identifier
);

Parameters

hWnd
[in] Handle to the window.
lpdwProcessId
[out] Pointer to a variable that receives the process identifier. If this parameter is not NULL, GetWindowThreadProcessId copies the identifier of the process to the variable; otherwise, it does not.

Return Values

The return value is the identifier of the thread that created the window.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
[in] Handle to the parent window.
hWnd
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, IsWindow, SetParent


IsGUIThread

The IsGUIThread function tests whether the calling thread is already a GUI thread. It can also optionally convert the thread to a GUI thread.

BOOL WINAPI IsGUIThread(
  BOOL bConvert
);

Parameters

bConvert
[in] If TRUE, convert thread to a GUI thread if it is not one.

Return Values

The function returns TRUE in the following situations:

  • if the calling thread is already a GUI thread
  • if bConvert is TRUE and the function successfully converts the thread to a GUI thread

Otherwise the function returns FALSE. If bConvert is TRUE but the function cannot convert the thread to a GUI thread, GetLastError returns ERROR_NOT_ENOUGH_MEMORY.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

Windows Overview, Window Functions


IsIconic

The IsIconic function determines whether the specified window is minimized (iconic).

BOOL IsIconic(
  HWND hWnd   // handle to window
);

Parameters

hWnd
[in] 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.

For an example, see Drawing a Minimized Window.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
[in] 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.

Remarks

An application should not use IsWindow for a window that it did not create because the window could be destroyed after this function was called. Further, because window handles are recycled the handle could even point to a different window.

For an example, see Creating a Modeless Dialog Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
[in] Handle to the window to test.

Return Values

If the specified window, its parent window, its parent's parent window, and so forth, have the WS_VISIBLE style, the return value is nonzero. Otherwise, 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, IsIconic


LockSetForegroundWindow

The foreground process can call the LockSetForegroundWindow function to disable calls to the SetForegroundWindow function.

BOOL LockSetForegroundWindow(
  UINT uLockCode  // disable or enable calls
);

Parameters

uLockCode
[in] Specifies whether to enable or disable calls to SetForegroundWindow. This parameter can be one of the following values.
Value | Description
LSFW_LOCK | Disables calls to SetForegroundWindow.
LSFW_UNLOCK | Enables calls to SetForegroundWindow.

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 system automatically enables calls to SetForegroundWindow if the user presses the ALT key or takes some action that causes the system itself to change the foreground window (for example, clicking a background window).

This function is provided so applications can prevent other applications from making a foreground change that can interrupt its interaction with the user.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows Me.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, AllowSetForegroundWindow, SetForegroundWindow


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 option
);

Parameters

hWnd
[in] Handle to the window.
X
[in] Specifies the new position of the left side of the window.
Y
[in] Specifies the new position of the top of the window.
nWidth
[in] Specifies the new width of the window.
nHeight
[in] Specifies the new height of the window.
bRepaint
[in] 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.

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 application must explicitly invalidate or redraw any parts of the window and parent window that need redrawing.

MoveWindow sends the WM_WINDOWPOSCHANGING, WM_WINDOWPOSCHANGED, WM_MOVE, WM_SIZE, and WM_NCCALCSIZE messages to the window.

For an example, see Creating, Enumerating, and Sizing Child Windows.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, CloseWindow, IsIconic, ShowWindow


RealChildWindowFromPoint

The RealChildWindowFromPoint function retrieves a handle to the child window at the specified point.

HWND RealChildWindowFromPoint(
  HWND hwndParent,            // handle to window
  POINT ptParentClientCoords  // client coordinates
);

Parameters

hwndParent
[in] Handle to the window whose child is to be retrieved.
ptParentClientCoords
[in] 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 specified point.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP4 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, POINT


RealGetWindowClass

The RealGetWindowClass function retrieves a string that specifies the window type.

UINT RealGetWindowClass(
  HWND  hwnd,      // handle to window
  LPTSTR pszType,  // window type buffer
  UINT  cchType    // size of window type buffer
);

Parameters

hwnd
[in] Handle to the window whose type will be retrieved.
pszType
[out] Pointer to a string that receives the window type.
cchType
[in] Specifies the length, in TCHARs, of the buffer pointed to by the pszType parameter.

Return Values

If the function succeeds, the return value is the number of TCHARs copied to the specified buffer.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP4 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Windows Overview, Window Functions


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
);

Parameters

hWnd
[in] 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 98/Me, Windows 2000 or later: The system restricts which processes can set the foreground window. A process can set the foreground window only if one of the following conditions is true:

  • The process is the foreground process.
  • The process was started by the foreground process.
  • The process received the last input event.
  • There is no foreground process.
  • The foreground process is being debugged.
  • The foreground is not locked (see LockSetForegroundWindow).
  • The foreground lock time-out has expired (see SPI_GETFOREGROUNDLOCKTIMEOUT in SystemParametersInfo).
  • Windows 2000 or later: No menus are active.

With this change, 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. However, on Windows 98, if a nonforeground thread calls SetForegroundWindow and passes the handle of a window that was not created by the calling thread, the window is not flashed on the taskbar. To have SetForegroundWindow behave the same as it did on Windows 95 and Windows NT 4.0, change the foreground lock timeout value when the application is installed. This can be done from the setup or installation application with the following function call:

   SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, (LPVOID)0, SPIF_SENDWININICHANGE | SPIF_UPDATEINIFILE);

This method allows SetForegroundWindow on Windows 98 and Windows 2000 to behave the same as Windows 95 and Windows NT 4.0, respectively, for all applications. The setup application should warn the user that this is being done so that the user isn't surprised by the changed behavior. On Windows 2000, the SystemParametersInfo call fails unless the calling thread can change the foreground window, so this must be called from a setup or patch application. For more information, see Foreground and Background Windows.

A process that can set the foreground window can enable another process to set the foreground window by calling the AllowSetForegroundWindow function. The process specified by dwProcessId loses the ability to set the foreground window the next time the user generates input, unless the input is directed at that process, or the next time a process calls AllowSetForegroundWindow, unless that process is specified.

The foreground process can disable calls to SetForegroundWindow by calling the LockSetForegroundWindow function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, AllowSetForegroundWindow, FlashWindowEx, GetForegroundWindow, LockSetForegroundWindow, SetActiveWindow


SetLayeredWindowAttributes

The SetLayeredWindowAttributes function sets the opacity and transparency color key of a layered window.

BOOL SetLayeredWindowAttributes(
  HWND hwnd,           // handle to the layered window
  COLORREF crKey,      // specifies the color key
  BYTE bAlpha,         // value for the blend function
  DWORD dwFlags        // action
);

Parameters

hwnd
[in] Handle to the layered window. A layered window is created by specifying WS_EX_LAYERED when creating the window with the CreateWindowEx function or by setting WS_EX_LAYERED via SetWindowLong after the window has been created.
crKey
[in] Pointer to a COLORREF value that specifies the transparency color key to be used when composing the layered window. All pixels painted by the window in this color will be transparent. To generate a COLORREF, use the RGB macro.
bAlpha
[in] Alpha value used to describe the opacity of the layered window. Similar to the SourceConstantAlpha member of the BLENDFUNCTION structure. When bAlpha is 0, the window is completely transparent. When bAlpha is 255, the window is opaque.
dwFlags
[in] Specifies an action to take. This parameter can be one or more of the following values.
Value | Meaning
LWA_COLORKEY | Use crKey as the transparency color.
LWA_ALPHA | Use bAlpha to determine the opacity of the layered 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

Note that once SetLayeredWindowAttributes has been called for a layered window, subsequent UpdateLayeredWindow calls will fail until the layering style bit is cleared and set again.

For more information, see Layered Windows.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, Layered Windows, AlphaBlend, CreateWindowEx, SetWindowLong, TransparentBlt, UpdateLayeredWindow, COLORREF, RGB


SetLayout

The SetLayout function changes the layout of a device context (DC).

DWORD SetLayout(
  HDC hdc,             // handle to DC
  DWORD dwLayout,      // layout options
);

Parameters

hdc
[in] Handle to the device context.
dwLayout
[in] Specifies the device context layout. This parameter can be one or more of the following values.
Value | Meaning
LAYOUT_BITMAPORIENTATIONPRESERVED | Disables any reflection during BitBlt and StretchBlt operations.
LAYOUT_RTL | Sets the default horizontal layout to be right to left.

Return Values

If the function succeeds, it returns the previous layout of the device context.

If the function fails, it returns GDI_ERROR. To get extended error information, call GetLastError.

Remarks

The layout specifies how text and graphics are laid out; the default is left to right. The SetLayout function changes this to be right to left, which is the standard in Arabic and Hebrew cultures.

Once the LAYOUT_RTL flag is selected, flags normally specifying right or left are reversed. To avoid confusion, consider defining alternate words for standard flags, such as those in the following table.

Standard flag | Suggested alternate name
WS_EX_RIGHT | WS_EX_TRAILING
WS_EX_RTLREADING | WS_EX_REVERSEREADING
WS_EX_LEFTSCROLLBAR | WS_EX_LEADSCROLLBAR
ES_LEFT | ES_LEAD
ES_RIGHT | ES_TRAIL
EC_LEFTMARGIN | EC_LEADMARGIN
EC_RIGHTMARGIN | EC_TRAILMARGIN

SetLayout cannot modify drawing directly into the bits of a DIB.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Windows Overview, Window Functions, GetLayout


SetParent

The SetParent function changes the parent window of the specified child window.

HWND SetParent(
  HWND hWndChild,      // handle to window
  HWND hWndNewParent   // new parent window
);

Parameters

hWndChild
[in] Handle to the child window.
hWndNewParent
[in] Handle to the new parent window. If this parameter is NULL, the desktop window becomes the new parent window.

Windows 2000 or 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.

Windows 2000 or later: When you change the parent of a window, you should synchronize the UISTATE of both windows. For more information, see WM_CHANGEUISTATE and WM_UPDATEUISTATE.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, GetParent


SetProcessDefaultLayout

The SetProcessDefaultLayout function changes the default layout when windows are created with no parent or owner only for the currently running process.

BOOL SetProcessDefaultLayout(
  DWORD dwDefaultLayout      // required default layout
);

Parameters

dwDefaultLayout
[in] Default process layout. This parameter can be one or more of the following values.
Values | Meaning
LAYOUT_RTL | Sets the default horizontal layout to be right to left.

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 layout specifies how text and graphics are laid out; the default is left to right. The SetProcessDefaultLayout function changes layout to be right to left, which is the standard in Arabic and Hebrew cultures.

Once the LAYOUT_RTL flag is selected, flags normally specifying right or left are reversed. To avoid confusion, consider defining alternate words for standard flags, such as those in the following table.

Standard flag | Suggested alternate name
WS_EX_RIGHT | WS_EX_TRAILING
WS_EX_RTLREADING | WS_EX_REVERSEREADING
WS_EX_LEFTSCROLLBAR | WS_EX_LEADSCROLLBAR
ES_LEFT | ES_LEAD
ES_RIGHT | ES_TRAIL
EC_LEFTMARGIN | EC_LEADMARGIN
EC_RIGHTMARGIN | EC_TRAILMARGIN

If using this function with a mirrored window, note that the SetProcessDefaultLayout function does not mirror the whole process and all the DCs created in it. It mirrors only the mirrored window's DCs. To mirror any DC, use the SetLayout function .

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, GetProcessDefaultLayout, SetLayout


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  // position data
);

Parameters

hWnd
[in] Handle to the window.
lpwndpl
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 options
);

Parameters

hWnd
[in] Handle to the window.
hWndInsertAfter
[in] 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
[in] Specifies the new position of the left side of the window, in client coordinates.
Y
[in] Specifies the new position of the top of the window, in client coordinates.
cx
[in] Specifies the new width of the window, in pixels.
cy
[in] Specifies the new height of the window, in pixels.
uFlags
[in] 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 and the thread that owns the window are attached to different input queues, 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 Applies new frame styles set using the SetWindowLong function.

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.

For an example, see Initializing a Dialog Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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   // title or text
);

Parameters

hWnd
[in] Handle to the window or control whose text is to be changed.
lpString
[in] 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.

To set the text of a control in another process, send the WM_SETTEXT message directly instead of calling SetWindowText.

The SetWindowText function does not expand tab characters (ASCII code 0x09). Tab characters are displayed as vertical bar (|) characters.

For an example, see Sending a Message.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

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
);

Parameters

hWnd
[in] Handle to the window that owns the pop-up windows to be shown or hidden.
fShow
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
);

Parameters

hWnd
[in] Handle to the window.
nCmdShow
[in] 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 2000 or 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_ value specified in the STARTUPINFO structure passed to the CreateProcess function by the program that started the application.
SW_SHOWMAXIMIZED | Activates the window and displays it as a maximized window.
SW_SHOWMINIMIZED | Activates the window and displays it as a minimized window.
SW_SHOWMINNOACTIVE Displays the window as a minimized window.

This value is similar to SW_SHOWMINIMIZED, except the window is not activated.
SW_SHOWNA Displays the window in its current size and position.

This value is similar to SW_SHOW, except the window is not activated.
SW_SHOWNOACTIVATE Displays a window in its most recent size and position.

This value is similar to SW_SHOWNORMAL, except the window is not actived.
SW_SHOWNORMAL | Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when displaying the window for the first time.

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

For an example, see Creating the Main Window.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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
);

Parameters

hWnd
[in] Handle to the window.
nCmdShow
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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 TileWindows(
  HWND hwndParent,     // handle to parent window
  UINT wHow,           // tiling options
  CONST RECT *lpRect,  // client area
  UINT cKids,          // number of windows to arrange
  const HWND *lpKids   // array of window handles
);

Parameters

hwndParent
[in] Handle to the parent window. If this parameter is NULL, the desktop window is assumed.
wHow
[in] Specifies tiling flags. 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
[in] 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
[in] Specifies the number of elements in the array specified by the lpKids parameter. This parameter is ignored if lpKids is NULL.
lpKids
[in] 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, CascadeWindows, RECT


UpdateLayeredWindow

The UpdateLayeredWindow function updates the position, size, shape, content, and translucency of a layered window.

BOOL UpdateLayeredWindow(
  HWND hwnd,             // handle to layered window
  HDC hdcDst,            // handle to screen DC
  POINT *pptDst,         // new screen position
  SIZE *psize,           // new size of the layered window
  HDC hdcSrc,            // handle to surface DC
  POINT *pptSrc,         // layer position
  COLORREF crKey,        // color key
  BLENDFUNCTION *pblend, // blend function
  DWORD dwFlags          // options
);

Parameters

hwnd
[in] Handle to a layered window. A layered window is created by specifying WS_EX_LAYERED when creating the window with the CreateWindowEx function.
hdcDst
[in] Handle to a device context (DC) for the screen. This handle is obtained by specifying NULL when calling the GetDC function. It is used for palette color matching when the window contents are updated. If hdcDst is NULL, the default palette will be used.

If hdcSrc is NULL, hdcDst must be NULL.

pptDst
[in] Pointer to a POINT structure that specifies the new screen position of the layered window. If the current position is not changing, pptDst can be NULL.
psize
[in] Pointer to a SIZE structure that specifies the new size of the layered window. If the size of the window is not changing, psize can be NULL.

If hdcSrc is NULL, psize must be NULL.

hdcSrc
[in] Handle to a DC for the surface that defines the layered window. This handle can be obtained by calling the CreateCompatibleDC function. If the shape and visual context of the window are not changing, hdcSrc can be NULL.
pptSrc
[in] Pointer to a POINT structure that specifies the location of the layer in the device context.

If hdcSrc is NULL, pptSrc should be NULL.

crKey
[in] Pointer to a COLORREF value that specifies the color key to be used when composing the layered window. To generate a COLORREF, use the RGB macro.
pblend
[in] Pointer to a BLENDFUNCTION structure that specifies the transparency value to be used when composing the layered window.
dwFlags
[in] This parameter can be one of the following values.
Value | Meaning
ULW_ALPHA | Use pblend as the blend function. If the display mode is 256 colors or less, the effect of this value is the same as the effect of ULW_OPAQUE.
ULW_COLORKEY | Use crKey as the transparency color.
ULW_OPAQUE | Draw an opaque layered window.

If hdcSrc is NULL, dwFlags should be zero.

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 source DC should contain the surface that defines the visible contents of the layered window. For example, you can select a bitmap into a device context obtained by calling the CreateCompatibleDC function.

An application should call SetLayout on the hdcSrc device context to properly set the mirroring mode. SetLayout will properly mirror all drawing into an HDC while properly preserving text glyph and (optionally) bitmap direction order. It cannot modify drawing directly into the bits of a DIB. For more information, see Window Layout and Mirroring.

The UpdateLayeredWindow function maintains the window's appearance on the screen. The windows underneath a layered window do not need to be repainted when they are uncovered due to a call to UpdateLayeredWindow, because the system will automatically repaint them. This permits seamless animation of the layered window.

UpdateLayeredWindow always updates the entire window. To update part of a window, use the traditional WM_PAINT and set the blend value using SetLayeredWindowAttributes.

For best drawing performance by the layered window and any underlying windows, the layered window should be as small as possible. An application should also process the WM_DISPLAYCHANGE message and recreate its layered windows when the display's color depth changes.

For more information, see Layered Windows.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Windows Overview, Window Functions, Layered Windows, AlphaBlend, CreateCompatibleBitmap, CreateCompatibleDC, CreateWindowEx, GetDC, SetLayeredWindowAttributes, SetLayout, SetWindowLong, SetWindowPos, TransparentBlt, COLORREF, RGB, WM_PAINT


WindowFromPoint

The WindowFromPoint function retrieves a handle to the window that contains the specified point.

HWND WindowFromPoint(
  POINT Point  // point
);

Parameters

Point
[in] 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.

For an example, see Interface from Running Object Table.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
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,          // command line
  int nCmdShow              // show state
);

Parameters

hInstance
[in] Handle to the current instance of the application.
hPrevInstance
[in] 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
[in] 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
[in] 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_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_SHOWMAXIMIZED | Activates the window and displays it as a maximized window.
SW_SHOWMINIMIZED | Activates the window and displays it as a minimized window.
SW_SHOWMINNOACTIVE Displays the window as a minimized window.

This value is similar to SW_SHOWMINIMIZED, except the window is not activated.
SW_SHOWNA Displays the window in its current size and position.

This value is similar to SW_SHOW, except the window is not activated.
SW_SHOWNOACTIVATE Displays a window in its most recent size and position.

This value is similar to SW_SHOWNORMAL, except the window is not actived.
SW_SHOWNORMAL | Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when displaying the window for the first time.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.

See Also

Windows Overview, Window Functions, CreateMutex, DispatchMessage, GetCommandLine, GetMessage, PostQuitMessage, TranslateMessage


Window Structures

The following structures are used to create and manage windows.

ALTTABINFO
CLIENTCREATESTRUCT
CREATESTRUCT
GUITHREADINFO
MINMAXINFO
NCCALCSIZE_PARAMS
STYLESTRUCT
TITLEBARINFO
WINDOWINFO
WINDOWPLACEMENT
WINDOWPOS


ALTTABINFO

The ALTTABINFO structure contains status information for the application-switching (ALT+TAB) window.

typedef struct tagALTTABINFO {
    DWORD cbSize;
    int   cItems;
    int   cColumns;
    int   cRows;
    int   iColFocus;
    int   iRowFocus;
    int   cxItem;
    int   cyItem;
    POINT ptStart;
} ALTTABINFO, *PALTTABINFO, *LPALTTABINFO;

Members

cbSize
Specifies the size, in bytes, of the structure.
cItems
Specifies the number of items in the window.
cColumns
Specifies the number of columns in the window.
cRows
Specifies the number of rows in the window.
iColFocus
Specifies the column of the item that has the focus.
iRowFocus
Specifies the row of the item that has the focus.
cxItem
Specifies the width of each icon in the application-switching window.
cyItem
Specifies the height of each icon in the application-switching window.
ptStart
Specifies the top-left corner of the first icon.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP6 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Windows Overview, Window Structures, GetAltTabInfo


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 {
    HANDLE hWindowMenu;
    UINT   idFirstChild;
} CLIENTCREATESTRUCT, *LPCLIENTCREATESTRUCT;

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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. These members are identical to the parameters of the CreateWindowEx function.

typedef struct tagCREATESTRUCT {
    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, *LPCREATESTRUCT;

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/2000 or later: 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 window style for the new window.

Remarks

Windows NT/2000 or later: 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);

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Windows Overview, Window Structures, CreateWindow, CreateWindowEx, MDICREATESTRUCT


GUITHREADINFO

The GUITHREADINFO structure contains information about a GUI thread.

typedef struct tagGUITHREADINFO {
    DWORD   cbSize;
    DWORD   flags;
    HWND    hwndActive;
    HWND    hwndFocus;
    HWND    hwndCapture;
    HWND    hwndMenuOwner;
    HWND    hwndMoveSize;
    HWND    hwndCaret;
    RECT    rcCaret;
} GUITHREADINFO, *PGUITHREADINFO;

Members

cbSize
Specifies the size of this structure, in bytes. This member must be set.
flags
Specifies the thread state. This member can be one or more of the following values.
Value | Meaning
GUI_16BITTASK | Whistler: Represents the thread's application type. This bit is set if the thread corresponds to a 16-bit application.
GUI_CARETBLINKING | Represents the caret's blink state. This bit is set if the caret is visible.
GUI_INMENU | Represents the thread's menu state. This bit is set if the thread is in menu mode.
GUI_INMOVESIZE | Represents the thread's move state. This bit is set if the thread is in a move or size loop.
GUI_POPUPMENUMODE | Represents the thread's pop-up menu state. This bit is set if the thread has an active pop-up menu.
GUI_SYSTEMMENUMODE | Represents the thread's system menu state. This bit is set if the thread is in a system menu mode.

hwndActive
Handle to the active window within the thread.
hwndFocus
Handle to the window that has the keyboard focus.
hwndCapture
Handle to the window that has captured the mouse.
hwndMenuOwner
Handle to the window that owns any active menus.
hwndMoveSize
Handle to the window in a move or size loop.
hwndCaret
Handle to the window that is displaying the caret.
rcCaret
A RECT structure that describes the caret's bounding rectangle, in client coordinates, relative to the window specified by the hwndCaret member.

Remarks

This structure is used with the GetGUIThreadInfo function to retrieve information about the active window or a specified GUI thread.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP3 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Windows Overview, Window Structures, GetGUIThreadInfo, RECT


MINMAXINFO

The MINMAXINFO structure contains information about a window's maximized size and position and its minimum and maximum tracking size.

typedef struct tagMINMAXINFO {
    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. For systems with multiple monitors, this refers to the primary monitor.
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). For systems with multiple monitors, this refers to the monitor on which the window maximizes.
ptMinTrackSize
Specifies the minimum tracking width (point.x) and the minimum tracking height (point.y) of the window. This is unchanged for systems with multiple monitors.
ptMaxTrackSize
Specifies the maximum tracking width (point.x) and the maximum tracking height (point.y) of the window. For systems with multiple monitors, this is the size for a window that is made as large as the virtual screen.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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 {
    RECT        rgrc[3];
    PWINDOWPOS  lppos;
} NCCALCSIZE_PARAMS, *LPNCCALCSIZE_PARAMS;

Members

rgrc
Specifies an array of rectangles. The first contains the new coordinates of a window that has been moved or resized, that is, it is the proposed new window coordinates. 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Windows Overview, Window Structures, MoveWindow, RECT, SetWindowPos, WINDOWPOS, WM_NCCALCSIZE


STYLESTRUCT

The STYLESTRUCT structure contains the styles for a window.

typedef struct tagSTYLESTRUCT {
    DWORD styleOld;
    DWORD styleNew;
} STYLESTRUCT, *LPSTYLESTRUCT;

Members

styleOld
Specifies the previous styles for a window. For more information, see the Remarks.
styleNew
Specifies the new styles for a window. For more information, see the Remarks.

Remarks

The styles in styleOld and styleNew can be either the window styles (WS_*) or the extended window styles (WS_EX_*), depending on the wParam of the message that includes STYLESTRUCT.

The styleOld and styleNew members indicate the styles through their bit pattern. Note that several styles are equal to zero; to detect these styles, test for the negation of their inverse style. For example, to see if WS_EX_LEFT is set, you test for ~WS_EX_RIGHT.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Windows Overview, Window Structures, WM_STYLECHANGED, WM_STYLECHANGING


TITLEBARINFO

The TITLEBARINFO structure contains title bar information.

typedef struct tagTITLEBARINFO {
    DWORD cbSize;
    RECT  rcTitleBar;
    DWORD rgstate[CCHILDREN_TITLEBAR+1];
} TITLEBARINFO, *PTITLEBARINFO, *LPTITLEBARINFO;

Members

cbSize
Specifies the size, in bytes, of the structure.
rcTitleBar
Pointer to a RECT structure that receives the coordinates of the title bar. These coordinates include all title-bar elements except the window menu.
rgstate
Pointer to an array that receives a DWORD value for each element of the title bar. The following are the title bar elements represented by the array.
Index | Element
0 | The title bar itself.
1 | Reserved.
2 | Minimize button.
3 | Maximize button.
4 | Help button.
5 | Close button

Each array element is a combination of one or more of the following values.
Value | Meaning
STATE_SYSTEM_FOCUSABLE | The element can accept the focus.
STATE_SYSTEM_INVISIBLE | The element is invisible.
STATE_SYSTEM_OFFSCREEN | The element has no visible representation.
STATE_SYSTEM_UNAVAILABLE | The element is unavailable.
STATE_SYSTEM_PRESSED | The element is in the pressed state.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP6 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Windows Overview, Window Structures, GetTitleBarInfo, RECT


WINDOWINFO

The WINDOWINFO structure contains window information.

typedef struct tagWINDOWINFO {
    DWORD cbSize;
    RECT  rcWindow;
    RECT  rcClient;
    DWORD dwStyle;
    DWORD dwExStyle;
    DWORD dwWindowStatus;
    UINT  cxWindowBorders;
    UINT  cyWindowBorders;
    ATOM  atomWindowType;
    WORD  wCreatorVersion;
} WINDOWINFO, *PWINDOWINFO, *LPWINDOWINFO;

Members

cbSize
The size of the structure, in bytes.
rcWindow
Pointer to a RECT structure that specifies the coordinates of the window.
rcClient
Pointer to a RECT structure that specifies the coordinates of the client area.
dwStyle
The window styles. For a table of window styles, see CreateWindowEx.
dwExStyle
The extended window styles. For a table of extended window styles, see CreateWindowEx.
dwWindowStatus
The window status. If this member is WS_ACTIVECAPTION, the window is active. Otherwise, this member is zero.
cxWindowBorders
The width of the window border, in pixels.
cyWindowBorders
The height of the window border, in pixels.
atomWindowType
The window class atom (see RegisterClass).
wCreatorVersion
The Windows version of the application that created the window.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP3 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Windows Overview, Window Structures, CreateWindowEx, GetWindowInfo, RECT, RegisterClass


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 more of the following values.
Value Meaning
WPF_
ASYNCWINDOWPLACEMENT 		Windows 2000 or later: If the calling thread and the thread that owns the window are attached to different input queues, 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.
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_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_SHOWMAXIMIZED | Activates the window and displays it as a maximized window.
SW_SHOWMINIMIZED | Activates the window and displays it as a minimized window.
SW_SHOWMINNOACTIVE Displays the window as a minimized window.

This value is similar to SW_SHOWMINIMIZED, except the window is not activated.
SW_SHOWNA Displays the window in its current size and position.

This value is similar to SW_SHOW, except the window is not activated.
SW_SHOWNOACTIVATE Displays a window in its most recent size and position.

This value is similar to SW_SHOWNORMAL, except the window is not actived.
SW_SHOWNORMAL | Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when displaying the window for the first time.

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 application toolbars (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 application toolbars.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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 {
    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 or more 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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_NULL
WM_PARENTNOTIFY
WM_QUERYDRAGICON
WM_QUERYOPEN
WM_QUIT
WM_SETICON
WM_SETTEXT
WM_SHOWWINDOW
WM_SIZE
WM_SIZING
WM_STYLECHANGED
WM_STYLECHANGING
WM_THEMECHANGED
WM_USERCHANGED
WM_WINDOWPOSCHANGED
WM_WINDOWPOSCHANGING


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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_ACTIVATEAPP
  WPARAM wParam,   // activation flag (BOOL)
  LPARAM lParam    // thread identifier (DWORD)
);

Parameters

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.
lParam
Specifies a thread identifier. If the wParam parameter is TRUE, lParam is the identifier of the thread that owns the window being deactivated. If wParam is FALSE, lParam is the identifier of the thread that owns the window being activated.

Return Values

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_CANCELMODE
  WPARAM wParam,   // not used
  LPARAM lParam    // not used
);

Parameters

This message has no parameters.

Return Values

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

Remarks

When the WM_CANCELMODE message is sent, the DefWindowProc function cancels internal processing of standard scroll bar input, cancels internal menu processing, and releases the mouse capture.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Windows Overview, Window Messages, DefWindowProc, EnableWindow, ReleaseCapture


WM_CHILDACTIVATE

The WM_CHILDACTIVATE message is sent to a child window when the user clicks the window's title bar or when the window is activated, moved, or sized.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_CHILDACTIVATE
  WPARAM wParam,   // not used
  LPARAM lParam    // not used
);

Parameters

This message has no parameters.

Return Values

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_CLOSE
  WPARAM wParam,   // not used
  LPARAM lParam    // not used
);

Parameters

This message has no parameters.

Return Values

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

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.

By default, the DefWindowProc function calls the DestroyWindow function to destroy the window.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_COMPACTING
  WPARAM wParam,   // compacting ratio
  LPARAM lParam    // not used
);

Parameters

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.
lParam
This parameter is not used.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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 message is sent before the function returns.) The window procedure of the new window receives this message after the window is created, but before the window becomes visible.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_CREATE
  WPARAM wParam,   // not used
  LPARAM lParam    // creation data (LPCREATESTRUCT)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to a CREATESTRUCT structure that contains information about the window being created.

Return Values

If an application processes this message, it should return zero 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_DESTROY
  WPARAM wParam,   // not used
  LPARAM lParam    // not used
);

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_ENABLE
  WPARAM wParam,   // enabled state (BOOL)
  LPARAM lParam    // not used
);

Parameters

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.
lParam
This parameter is not used.

Return Values

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_ENTERSIZEMOVE
  WPARAM wParam,   // not used
  LPARAM lParam    // not used
);

Parameters

This message has no parameters.

Return Values

An application should return zero if it processes this message.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_EXITSIZEMOVE
  WPARAM wParam,   // not used
  LPARAM lParam    // not used
);

Parameters

This message has no parameters.

Return Values

An application should return zero if it processes this message.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_GETICON
  WPARAM wParam,   // icon type
  LPARAM lParam    // not used
);

Parameters

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.
ICON_SMALL2 | Whistler: Retrieves the small icon provided by the application. If the application does not provide one, the system uses the system-generated icon for that window.

lParam
This parameter is not used.

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 the DefWindowProc function.

Remarks

When an application receives this message, it can return a handle to a large or small icon, or pass the message to DefWindowProc.

DefWindowProc returns a handle to the large or small icon associated with the window, depending on the value of fType.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_GETMINMAXINFO
  WPARAM wParam,   // not used
  LPARAM lParam    // window information (LPMINMAXINFO)
);

Parameters

wParam
This parameter is not used.
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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_GETTEXT,               // message to send
  (WPARAM) wParam,          // number of characters to copy
  (LPARAM) lParam           // text buffer
);

Parameters

wParam
Specifies the maximum number of TCHARs to be copied, including the terminating null character.

Windows NT/2000 or later: ANSI applications may have the string in the buffer reduced in size (to a minimum of half that of the wParam value) due to conversion from ANSI to Unicode.

lParam
Pointer to the buffer that is to receive the text.

Return Values

The return value is the number of TCHARs copied, not including the terminating null character.

Remarks

The DefWindowProc function copies the text associated with the window into the specified buffer and returns the number of characters copied. Note, for non-text static controls this gives you the text with which the control was originally created, that is, the ID number. However, it gives you the ID of the non-text static control as originally created. That is, if you subsequently used a STM_SETIMAGE to change it the original ID would still be returned.

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 lParam. This is true only if the WM_SETTEXT message has been used to set the icon.

Rich Edit: If the text to be copied exceeds 64K, use either the EM_STREAMOUT or EM_GETSELTEXT message.

Windows 2000 or later: Sending a WM_GETTEXT message to a non-text static control, such as a static bitmap or static icon control, does not return a string value. Instead, it returns zero. In addition, in previous versions of Windows and Windows NT, applications could send a WM_GETTEXT message to a non-text static control to retrieve the control's ID. To retrieve a control's ID in Windows 2000, applications can use GetWindowLong passing GWL_ID as the index value or GetWindowLongPtr using GWLP_ID.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Windows Overview, Window Messages, DefWindowProc, EM_GETSELTEXT, EM_STREAMOUT, GetWindowLong, GetWindowLongPtr, 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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_GETTEXTLENGTH,         // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam           // not used; must be zero
);

Parameters

wParam
This parameter is not used and must be zero.
lParam
This parameter is not used and must be zero.

Return Values

The return value is the length of the text in TCHARs, not including the terminating null character.

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.

When the WM_GETTEXTLENGTH message is sent, the DefWindowProc function returns the length, in characters, of the text. 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.

Windows 2000 or later: Sending a WM_GETTEXTLENGTH message to a non-text static control, such as a static bitmap or static icon controlc, does not return a string value. Instead, it returns zero.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_INPUTLANGCHANGE
  WPARAM wParam,   // character set
  LPARAM lParam    // input locale identifier (HKL)
);

Parameters

wParam
Specifies the character set of the new locale.
lParam
Input locale identifier. For more information, see Languages, Locales, and Keyboard Layouts.

Return Values

An application should return nonzero if it processes this message.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_INPUTLANGCHANGEREQUEST
  WPARAM wParam,   // input locale information
  LPARAM lParam    // input locale identifier (HKL)
);

Parameters

wParam
Information about the new input locale. This parameter can be a combination of the following flags.
Flag | Meaning
INPUTLANGCHANGE_BACKWARD | Windows 2000 and later: A hot key was used to choose the previous input locale in the installed list of input locales. This flag cannot be used with the INPUTLANGCHANGE_FORWARD flag.
INPUTLANGCHANGE_FORWARD | Windows 2000 and later: A hot key was used to choose the next input locale in the installed list of input locales. This flag cannot be used with the INPUTLANGCHANGE_BACKWARD flag.
INPUTLANGCHANGE_SYSCHARSET | Windows 2000 and later: The new input locale's keyboard layout can be used with the system character set.

lParam
Input locale identifier. For more information, see Languages, Locales, and Keyboard Layouts.

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.

Remarks

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.

The language indicator is present on the taskbar only if you have installed more than one keyboard layout and if you have enabled the indicator using the Keyboard control panel application.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Windows Overview, Window Messages, DefWindowProc, WM_INPUTLANGCHANGE


WM_MOVE

The WM_MOVE message is sent after a window has been moved.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_MOVE
  WPARAM wParam,   // not used
  LPARAM lParam    // position
);

Parameters

wParam
This parameter is not used.
lParam
Specifies the x and y coordinates of the upper-left corner of the client area of the window. The low-order word contains the x-coordinate while the high-order word contains the y coordinate.

Return Values

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

Remarks

The parameters are given in screen coordinates for overlapped and pop-up windows and in parent-client coordinates for child windows.

The following example demonstrates how to obtain the position from the lParam parameter.

xPos = (int)(short) LOWORD(lParam);   // horizontal position
yPos = (int)(short) HIWORD(lParam);   // vertical position

You can also use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Windows Overview, Window Messages, HIWORD, LOWORD, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_MOVING
  WPARAM wParam,   // edge of window
  LPARAM lParam    // drag rectangle (LPRECT)
);

Parameters

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

lParam
Pointer to 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NCACTIVATE
  WPARAM wParam,   // new state (BOOL)
  LPARAM lParam    // not used
);

Parameters

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 wParam parameter is TRUE. It is FALSE for an inactive title bar or icon.
lParam
This parameter is not used.

Return Values

When the wParam 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 wParam is TRUE, the return value is ignored.

Remarks

The DefWindowProc function draws the title bar or icon title in its active colors when the wParam parameter is TRUE and in its inactive colors when wParam is FALSE.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NCCALCSIZE
  WPARAM wParam,   // validation flag (BOOL)
  LPARAM lParam    // data (LPNCCALCSIZE_PARAMS or LPRECT)
);

Parameters

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.

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 wParam parameter is FALSE, the application should return zero.

If wParam is TRUE, the application should return zero or a combination of the following values.

Value | Meaning
WVR_ALIGNTOP, WVR_ALIGNLEFT, WVR_ALIGNBOTTOM | 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 wParam 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.

Remarks

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NCCREATE
  WPARAM wParam,   // not used
  LPARAM lParam    // creation data (LPCREATESTRUCT)
);

Parameters

wParam
This parameter is not used.
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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

The WM_NCDESTROY message is sent after the child windows have been destroyed. In contrast, WM_DESTROY is sent before the child windows are destroyed.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NCDESTROY
  WPARAM wParam,   // not used
  LPARAM lParam    // not used
);

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Windows Overview, Window Messages, DestroyWindow, WM_DESTROY, WM_NCCREATE


WM_NULL

The WM_NULL message performs no operation. An application sends the WM_NULL message if it wants to post a message that the recipient window will ignore.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NULL
  WPARAM wParam,   // not used
  LPARAM lParam    // not used
);

Parameters

wParam
This parameter is not used.
lParam
This parameter is not used.

Return Values

An application returns zero if it processes this message.

Remarks

For example, if an application has installed a WH_GETMESSAGE hook and wants to prevent a message from being processed, the GetMsgProc callback function can change the message number to WM_NULL so the recipient will ignore it.

As another example, an application can check if a window is responding to messages by sending the WM_NULL message with the SendMessageTimeout function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Windows Overview, Window Messages


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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_PARENTNOTIFY
  WPARAM wParam,   // event and child window identifier
  LPARAM lParam    // child handle or cursor coordinates
);

Parameters

wParam
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.
WM_XBUTTONDOWN | Windows 2000 or later: The user has placed the cursor over the child window and has clicked the first or second X button.

The meaning of the high-order word of wParam depends on the value of the low-order word of wParam, as shown in the following table.
LOWORD(wParam) | Meaning of HIWORD(wParam)
WM_CREATE | Identifier of the child window.
WM_DESTROY | Identifier of the child window.
WM_LBUTTONDOWN | Undefined.
WM_MBUTTONDOWN | Undefined.
WM_RBUTTONDOWN | Undefined.
WM_XBUTTONDOWN Windows 2000 or later: Indicates which button was pressed. This parameter can be one of the following values:

XBUTTON1
XBUTTON2

lParam
The meaning of lParam depends on the value of the low-order word of wParam, as shown in the following table.
LOWORD(wParam) | Meaning of lParam
WM_CREATE | Handle of the child window.
WM_DESTROY | Handle of the child window.
WM_LBUTTONDOWN | The x-coordinate of the cursor is the low-order word, and the y-coordinate of the cursor is the high-order word.
WM_MBUTTONDOWN | The x-coordinate of the cursor is the low-order word, and the y-coordinate of the cursor is the high-order word.
WM_RBUTTONDOWN | The x-coordinate of the cursor is the low-order word, and the y-coordinate of the cursor is the high-order word.
WM_XBUTTONDOWN | The x-coordinate of the cursor is the low-order word, and the y-coordinate of the cursor is 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Windows Overview, Window Messages, CreateWindow, CreateWindowEx, HIWORD, LOWORD, WM_CREATE, WM_DESTROY, WM_LBUTTONDOWN, WM_MBUTTONDOWN, WM_RBUTTONDOWN, WM_XBUTTONDOWN


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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_QUERYDRAGICON
  WPARAM wParam,   // not used
  LPARAM lParam    // not used
);

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.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Windows Overview, Window Messages, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_QUERYOPEN
  WPARAM wParam,   // not used
  LPARAM lParam    // not used
);

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.

Remarks

By default, the DefWindowProc function returns TRUE.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_QUIT
  WPARAM wParam,   // exit code
  LPARAM lParam    // not used
);

Parameters

wParam
Specifies the exit code given in the PostQuitMessage function.
lParam
This parameter is not used.

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.

Remarks

The WM_QUIT message is not associated with a window and therefore will never be received through a window's window procedure. It is retrieved only by the GetMessage or PeekMessage functions.

Do not post the WM_QUIT message using the PostMessage function; use PostQuitMessage.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Windows Overview, Window Messages, GetMessage, PeekMessage, 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 box, and the small icon in the window caption.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_SETICON,               // message to send
  (WPARAM) wParam,          // icon type
  (LPARAM) lParam          // handle to icon (HICON)
);

Parameters

wParam
Specifies the type of icon to be 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.

lParam
Handle to the new large or small icon. If this parameter is NULL, the icon indicated by wParam is removed.

Return Values

The return value is a handle to the previous large or small icon, depending on the value of wParam. It is NULL if the window previously had no icon of the type indicated by wParam.

Remarks

The DefWindowProc function returns a handle to the previous large or small icon associated with the window, depending on the value of wParam.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_SETTEXT,               // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam           // window-text string (LPCTSTR)
);

Parameters

wParam
This parameter is not used.
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.

Remarks

The DefWindowProc function sets and displays the window text. 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Windows Overview, Window Messages, DefWindowProc, CB_SELECTSTRING, WM_GETTEXT


WM_SHOWWINDOW

The WM_SHOWWINDOW message is sent to a window when the window is about to be hidden or shown.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_SHOWWINDOW
  WPARAM wParam,   // show flag (BOOL)
  LPARAM lParam    // status flag
);

Parameters

wParam
Specifies whether a window is being shown. If wParam is TRUE, the window is being shown. If wParam is FALSE, the window is being hidden.
lParam
Specifies the status of the window being shown. If lParam is zero, the message was sent because of a call to the ShowWindow function; otherwise, lParam 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.

Remarks

The DefWindowProc function hides or shows the window, as specified by the message. 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_SIZE
  WPARAM wParam,   // resizing flag
  LPARAM lParam    // client area
);

Parameters

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.

lParam
The low-order word of lParam specifies the new width of the client area.

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 or bRepaint parameter should be nonzero to cause the window to be repainted.

Although the width and height of a window are 32-bit values, the lParam parameter contains only the low-order 16 bits of each.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Windows Overview, Window Messages, HIWORD, LOWORD, 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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_SIZING
  WPARAM wParam,   // edge of window
  LPARAM lParam    // drag rectangle (LPRECT)
);

Parameters

wParam
Specifies which edge of the window is being sized. This parameter can be one or more 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

lParam
Pointer to 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_STYLECHANGED
  WPARAM wParam,   // window style types
  LPARAM lParam    // new styles (LPSTYLESTRUCT)
);

Parameters

wParam
Specifies whether the window's styles or extended window styles have changed. This parameter can be one or more of the following values.
Value | Meaning
GWL_EXSTYLE | The extended window styles have changed.
GWL_STYLE | The window styles have changed.

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.

For more information on the Windows 95/98 implementation of this message, see Window Management Differences.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_STYLECHANGING
  WPARAM wParam,   // window style types
  LPARAM lParam    // new styles (LPSTYLESTRUCT)
);

Parameters

wParam
Specifies whether the window's styles or extended window styles are changing. This parameter can be one or more of the following values.
Value | Meaning
GWL_EXSTYLE | The extended window styles are changing.
GWL_STYLE | The window styles are changing.

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.

For more information on the Windows 95/98 implementation of this message, see Window Management Differences.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Windows Overview, Window Messages, STYLESTRUCT, WM_STYLECHANGED


WM_THEMECHANGED

[This is preliminary documentation and subject to change.]

The WM_THEMECHANGED message is broadcast to every window following a theme change event. Examples of theme change events are the activation of a theme, the deactivation of a theme, or a transition from one theme to another.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,
  WM_THEMECHANGED,
  WPARAM wParam,
  LPARAM lParam
);

Parameters

wParam
Reserved.
lParam
Reserved

Return Values

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

Remarks

Themes are specifications for the appearance of controls, so that the visual element of a control is treated separately from its functionality.

To release an existing theme handle, call CloseThemeData. To acquire a new theme handle, use OpenThemeData.

Following the WM_THEMECHANGED broadcast, any existiing theme handles are invalid. A theme-aware window should release any pre-existing theme handles when it receives the WM_THEMECHANGED message. It may optionally open a new theme handle if the IsThemeActive function returns TRUE.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.

See Also

CloseThemeData, IsThemeActive, OpenThemeData


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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_USERCHANGED
  WPARAM wParam,   // not used
  LPARAM lParam    // not used
);

Parameters

This message has no parameters.

Return Values

An application should return zero if it processes this message.

Requirements

Windows NT/2000 or later: Unsupported .
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_WINDOWPOSCHANGED
  WPARAM wParam,   // not used
  LPARAM lParam    // size and position data (LPWINDOWPOS)
);

Parameters

wParam
This parameter is not used.
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.

Remarks

By default, the DefWindowProc function sends the WM_SIZE and WM_MOVE messages to the window. 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.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.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_WINDOWPOSCHANGING
  WPARAM wParam,   // not used
  LPARAM lParam    // size and position data (LPWINDOWPOS)
);

Parameters

wParam
This parameter is not used.
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.

Remarks

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.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Windows Overview, Window Messages, DefWindowProc, EndDeferWindowPos, SetWindowPos, WINDOWPOS, WM_GETMINMAXINFO, WM_MOVE, WM_SIZE, WM_WINDOWPOSCHANGED


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


GET_X_LPARAM

The GET_X_LPARAM macro retrieves the signed x-coordinate from the given LPARAM value.

int GET_X_LPARAM(
  LPARAM lParam
);

Parameters

lParam
Specifies the value to be converted.

Return Values

The return value is the low-order int of the specified value.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Windowsx.h.

See Also

Windows Overview, Window Macros, GET_Y_LPARAM, 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
);

Parameters

lParam
Specifies the value to be converted.

Return Values

The return value is the high-order int of the specified value.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Windowsx.h.

See Also

Windows Overview, Window Macros, GET_X_LPARAM, HIWORD


HIBYTE

The HIBYTE macro retrieves the high-order byte from the given 16-bit value.

BYTE HIBYTE(
  WORD wValue
);

Parameters

wValue
Specifies the value to be converted.

Return Values

The return value is the high-order byte of the specified value.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Windef.h; include Windows.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
);

Parameters

dwValue
Specifies the value to be converted.

Return Values

The return value is the high-order word of the specified value.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Windef.h; include Windows.h.

See Also

Windows Overview, Window Macros, HIBYTE, LOWORD, MAKELPARAM, MAKEWPARAM


LOBYTE

The LOBYTE macro retrieves the low-order byte from the specified value.

BYTE LOBYTE(
  WORD wValue
);

Parameters

wValue
Specifies the value to be converted.

Return Values

The return value is the low-order byte of the specified value.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Windef.h; include Windows.h.

See Also

Windows Overview, Window Macros, HIBYTE, LOWORD


LOWORD

The LOWORD macro retrieves the low-order word from the specified value.

WORD LOWORD(
  DWORD dwValue
);

Parameters

dwValue
Specifies the value to be converted.

Return Values

The return value is the low-order word of the specified value.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Windef.h; include Windows.h.

See Also

Windows Overview, Window Macros, HIWORD, LOBYTE, MAKELPARAM, MAKEWPARAM


MAKELONG

The MAKELONG macro creates a LONG value by concatenating the specified values.

DWORD MAKELONG(
  WORD wLow,
  WORD wHigh
);

Parameters

wLow
Specifies the low-order word of the new value.
wHigh
Specifies the high-order word of the new value.

Return Values

The return value is a LONG value.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Windef.h; include Windows.h.

See Also

Windows Overview, Window Macros


MAKELPARAM

The MAKELPARAM macro creates a value for use as an lParam parameter in a message. The macro concatenates the specified values.

LPARAM MAKELPARAM(
  WORD wLow,
  WORD wHigh
);

Parameters

wLow
Specifies the low-order word of the new value.
wHigh
Specifies the high-order word of the new value.

Return Values

The return value is an LPARAM value.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Windows Overview, Window Macros, MAKELONG, MAKELRESULT, MAKEWPARAM


MAKELRESULT

The MAKELRESULT macro creates a value for use as a return value from a window procedure. The macro concatenates the specified values.

LRESULT MAKELRESULT(
  WORD wLow,
  WORD wHigh
);

Parameters

wLow
Specifies the low-order word of the new value.
wHigh
Specifies the high-order word of the new value.

Return Values

The return value is an LRESULT value.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Windows Overview, Window Macros, MAKELONG, MAKELPARAM, MAKEWPARAM


MAKEWORD

The MAKEWORD macro creates a WORD value by concatenating the specified values.

WORD MAKEWORD(
  BYTE bLow,
  BYTE bHigh
);

Parameters

bLow
Specifies the low-order byte of the new value.
bHigh
Specifies the high-order byte of the new value.

Return Values

The return value is a WORD value.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Windef.h; include Windows.h.

See Also

Windows Overview, Window Macros


MAKEWPARAM

The MAKEWPARAM macro creates a value for use as a wParam parameter in a message. The macro concatenates the specified values.

WPARAM MAKEWPARAM(
  WORD wLow,
  WORD wHigh
);

Parameters

wLow
Specifies the low-order word of the new value.
wHigh
Specifies the high-order word of the new value.

Return Values

The return value is a WPARAM value.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Windows Overview, Window Macros, MAKELONG, MAKELPARAM, MAKELRESULT


Window Styles

The following styles can be specified wherever a window style is required. After the control has been created, these styles cannot be modified, except as noted.

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. A window with this style cannot have a menu bar. 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. To change this after a window has been created, use EnableWindow.
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. You can turn this style on and off to change dialog box navigation. To change this style after a window has been created, use SetWindowLong.
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. You can turn this style on and off to change dialog box navigation. To change this style after a window has been created, use SetWindowLong.
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. This style can be turned on and off by using ShowWindow or SetWindowPos.
WS_VSCROLL | Creates a window that has a vertical scroll bar.


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.